cannot set right charset when uploading files - apache2

Please be patient and check this problem.
I wrote some simple PHP code for uploading images.
Here is the code (snippets)
<?php
header('Content-Type: text/plain; charset=utf-8');
//set encoding for prepared statements
$dbh->exec("SET NAMES UTF8");
$dbh->query('SET NAMES UTF8');
//check if file is actually an image etc.
//send image to "upload" folder
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $_FILES["file"]["name"]);
//save to the database a string like "upload/myImage.jpg", so I can render it on the site later
$stu = $dbh->prepare("UPDATE multi SET m_place=:name WHERE m_id = :id");
$stu->bindParam(':name', $n, PDO::PARAM_STR);
$n= "upload/".$_FILES["file"]["name"];
$stu->execute();
If the name of the image is in English, everything is fine. If is in Greek, it saved ok in the database , but not in the folder. In the database I see χωρις τιτλο.jpg (which is right) and in the folder χωΟΞ―Ο‚ τίτλο.jpg which is wrong.
I've tried everything and cannot fix this. To get the right titles in the folder.
The encoding of the database (postgreSQL 9.1) is UTF8, the Collation and the Character Type are Greek_Greece.1235. The collaction in table's column which I save the image's title is pg_catalog."C".
I use DreamWeaver. The file that handles the uploads is a php file. Encoding is utf8, Unicode Normalization Form is C and the Include Unicode Signature (BOM) is unchecked.
The default language is Greek in Region and Language in the control panel. (Windows 7 Home Premium)
The encoding of the browser is utf8
I also use Apache 2.2.22. Is it Apache's fault? Or its the php file? Or the database?
I dont know what else to do...What am I missing? Please please please advice

This seems to be a StackOverflow issue and not related to ServerFault. However, you should take a look at this post:
For naming files in UTF-8:
Can a PHP file name (or a dir in its full path) have UTF-8 characters?
For writing files in UTF-8:
How to write file in UTF-8 format?

Turns out , I had not tried everything.
Thanks to this I found the solution.
It has to do with PHP and how "PHP filesystem functions can only handle characters that are in system codepage"
So I used the iconv function.
I changed the code like so
move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . iconv('UTF-8', 'Windows-1253',$_FILES["file"]["name"]));

For the application using japanese, the code page is cp932
This can be comfirm by using chcp command in commandline.
Sample Code
$fullPath = $uploadFolderPath."\\".iconv("utf-8", "cp932", $fileName);
move_uploaded_file($this->request->data["file_name"]['tmp_name'], $fullPath);

Related

Error 2005: While attempting to GET response from form recognizer

Currently I'm using form recognizer version 2.1 preview to train a custom model. I'm able to test the model in Form Recognizer Labeling Tool and got the output. When I input the same file that I got out in labeling tool in my program I'm getting the error below.
{"status": "failed", "createdDateTime": "2020-09-25T20:03:21Z", "lastUpdatedDateTime": "2020-09-25T20:03:21Z", "analyzeResult": {"version": "2.1.0", "errors": [{"code": "2005", "message": "The file submitted couldn't be parsed. This can be due to one of the following reasons: the file format is not supported ( Supported formats include JPEG, PNG, BMP, PDF and TIFF), the file is corrupted or password protected."}]}}
The GET request code used is:
resp = requests.get(url=get_url,headers={"Ocp-Apim-Subscription-Key":FORM_RECOGNIZER_SUBSCRIPTION_KEY})
I have saved the file to server and then tried to read it from there and pass the read file to form recognizer. This worked for me. But I don't know why did it happen.
I also encountered this exact error message following this article.
The article show 4 steps:
Train Model (require SAS to blob - whole folder)
Get model result
Analyze (require SAS to a single file)
Get analyze result
Profit
I got this error on step 4.
After monkeying around, I figured that the cause is not actually in step 4 but in step 3 instead. I was providing SAS to the blob instead of SAS to the file.
After I corrected the SAS URL it works perfectly.
Here is how to get SAS to blob:
Here is how to get SAS to a file:
What file are you trying to use as input ? Form Recognizer supports PDF, Tiff and images (PNG and JPEG) as file types and inputs to the analyze API. See more details here - https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/python-labeled-data?tabs=v2-0#analyze-forms-for-key-value-pairs-and-tables

Flask in PythonAnywhere doesn't find file name with spanish characters

I'm trying to build a website that has one page for downloading some resources, and it just happened that my local flask version finds perfectly any file name (when using send_from_directory()), but once deployed at PythonAnywhere it just doesn't work for the filenames that have spanish accented characters such as á.
I guess it has something to do with unicode, but I couldn't find how to fix it (the logs at pythonanywhere don't seem to show anything, since flask simply delivers a "Not found" page to the user).
...and I'd really like to have those accents in the name of the files people download (they're anki decks, some of them intended for education purposes, and it just feels wrong to deliver bad ortography in the deck name).
My code looks like this:
#app.route('/anki/d/<file>')
def d_anki(file):
if file == "verbscat":
ankideck = "[Rusca] Temps Verbals Catalans.apkg"
elif file == "irregular":
ankideck = "[Rusca] Verbs Irregulars Anglès.apkg"
# ...
else:
return f"The file {file} wasn't found."
return send_from_directory("./static/anki/", ankideck, as_attachment=True, cache_timeout=0)
(then I link to this url in a button by <a href="/anki/d/irregular" ...>)
Oh I just realized I can choose a different name for the downloaded file by adding attachment_filename="Whatever I want to call it" to the parameters in send_from_directory.
So I guess we can do with this workaround (having the original files with simple non-accented names and adding the proper name afterwards).
if file == "irregular":
ankideck = "irregular.apkg"
name = "[Rusca] Verbs Irregulars Anglès.apkg"
# ...
return send_from_directory("./static/anki/", ankideck, as_attachment=True, attachment_filename=name cache_timeout=0)

Symfony 2.8: how to upload an image from URL soruce?

How are you? First, sorry about my english :(
I'm triying to upload a file from a URL source like https://www.somedomain/somefolder/someimage.jpg but I'm getting some troubles...
I get this error when I'm triying to set $myFile->setFile('url'):
Catchable Fatal Error: Argument 1 passed to
MyBundle\Entity\File::setFile() must be an instance of
Symfony\Component\HttpFoundation\File\UploadedFile, string given
I've also tried through $content = get_file_contents('url') and then $myFile->setFile($content), but this returns the same error.
On the other hand, it's not a problem if I upload the file with an inputfile box in a form. But I cannot do it by indicating only one URL source (for a CronJob, by the way).
I've read the documentation about Files on Symfony, but I can't get success :(
Can anyone help me with this issue, please?
Thanks a lot! Greetings from Barcelona!! :)
To get rid of this issue you can do this:
<?php
use Symfony\Component\HttpFoundation\File\UploadedFile;
$file = new UploadedFile('url', 'name of the file');
$myFile->setFile($file);
Take a look at UploadedFile
Be sure to provide the correct path to the path. Not sure it will work like this because you want to set the UploadedFile without uploading the file through an input file and without submitting the form. Have a try.

Correct way in CakePHP 1.3 to create zip file and download without leaving view

I just upgraded from cakephp 1.1 to 1.3. I have everything on the site updated and working great, except for creating and downloading zip files.
Here is the code in my accounts_controller.php:
function zip() {
$this->checkSession();
$this->checkUpgradedAccount();
$files = array();
$this->layout="zip";
/*
code where I locate the files to zip, combine them, etc
*/
$tmp_file = "/home/[userdirectory]/tmp/".md5(mktime()).".zip"; //directory name edited
$command = "/usr/bin/zip -j $tmp_file ".implode(" ",$zip_files);
exec($command);
foreach($zip_files as $zf) {
unlink($zf);
}
$file_path = $tmp_file;
$this->set("path",$file_path);
$this->render();
}
When I call this action, however, I get an error:
Error: The requested address '/accounts/zip' was not found on this
server.
It worked just like this in version 1.1. I'm assuming something has changed, but I'm not sure what, and was unable to find anything pertinent in the documentation.
The zip.ctp view file does exists, but it has nothing in it other than: <?php ?>
I suspect something is different with layouts. There is NO "zip.ctp" in the /layouts directory. However, I have changed that line to $this->layout('default'); and it renders a blank page with NO ERROR, but also with no download.
Please direct me on the proper way to download my zip file in cake 1.3. Thanks in advance.
You have two different problems here. That error you're getting is because you don't have a zip layout file. As for your problem with getting the zip file, you should be using the media view class - http://book.cakephp.org/1.3/en/The-Manual/Developing-with-CakePHP/Views.html#media-views

Codeigniter "file_exists($filename)"

Need help with the codeigniter, I think file_exists is for server path, not for url. but my image folder got same level with application and system folder. find nothing on google, please help
$url=base_url();
$filename="$url/upload/$id.jpg";
if (file_exists($filename)){
echo "<li><img src=\"".$url."upload/$id.jpg\" width=\"40\" height=\"40\" /></li>";
}else{
echo "<li><img src=\"http://www.mydomain.com/haha/image/noimg.png\" width=\"40\" height=\"40\" /></li>";
}
Codeigniter is always running on index.php, so all paths are relative from there. You can use any of the following, assuming upload/ is at the same level as index.php:
file_exists("upload/$id.jpg")
file_exists("./upload/$id.jpg")
file_exists(FCPATH."upload/$id.jpg")
FCPATH is a constant that Codeigniter sets which contains the absolute path to your index.php.
As a side note, I prefer is_file() when checking files, as file_exists() returns true on directories. In addition, you might want to see if getimagesize() returns FALSE to make sure you have an image.

Resources