php - move uploaded file evaluating to false - php

I've got a php file setup for uploading images to an Amazon server via AWS. I've come to an error message which strangely is showing up on my prod server (the amazon server) but not my dev server (just a regular php server). The Amazon server has previously thrown errors when something is not structured exactly how it wants. For example if a an a tag has a href /home it will lead to an error page unless I change the tag to /home/.
Anyway i''ve narrowed down in my PHP script where the error lies and my php function move_uploaded_fileis evaluating to false and stopping my file from beginning the upload to Amazon s3 (at this stage the file is on the server where the site is hosted but not yet on the s3). Here is my if statement with some variables declared above that should be evaluating to true:
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_file)) {
//upload to s3
} else {
//error
}
I inserted the following code above the if statement to see what it was spitting out and here's what it evaluated in comments under it:
echo json_encode($target_file);
// "..\/uploads\/Grad.jpeg"
echo $_FILES["fileToUpload"]["tmp_name"];
// /tmp/phpQA1667
echo json_encode(move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],$target_file));
// false
I'm no php expert and can't seem to put my finder on why it's evaluating to false. Can anyone see where i've gone wrong?

move_uploaded_file returns false in two cases:
If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.
If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.
Either way, you should be getting an error back in your $_FILES superglobal.
Do a print_r($_FILES) and have a look at any error messages it gives you, and whether or not the array is populated.
Once you find that error, it should be easy for you to determine the exact cause of the issue.
A comprehensive list of the errors can be found at http://php.net/manual/en/features.file-upload.errors.php

Related

move_uploaded_file returns false always when uploading file from Node server

I am sending a file from node server to Api in PHP.
$name=dirname(dirname(dirname(__FILE__))).'/location/uploads/'.$files["image"]["name"];
if(!(move_uploaded_file($files["image"]["tmp_name"], $name))){
$errmsg.= '5';
}
But move_uploaded_file returns false everytime without any errors.
The errors are stored in $_FILES, see example code on the move_uploaded_file manual page.
Check it with
var_dump($_FILES);
Somewhere in there is an error key.

Checking for uploaded files with file_exists

I have a form for uploading data into my database.The form has a number of input fields ranging form text,number,textarea and file(images).
When the form is submitted, i check if there are any images being uploaded and if so, check if the image being uploaded passes a series of checks( below maximum file size, correct extension etc), with the entire process in a try/catch block set to throw exceptions should any check fail.
My checks are as follows:
$upload=$_FILES['Upload']['tmp_name'];
if(isset($upload))
{
if(!empty($upload) && is_uploaded_file($upload))
{
//Checks file size,extension and uploads the file
}
else
{
//throw new Exception
}
}
else
{
//throw new Exception
}
However, when using the above, isset would return true, even when no files are being uploaded.Upon some googling and looking on stack overflow, specifically isset and !empty not passing through a check for uploaded files , where it is stated that isset will return true due to $_FILES being a superglobal, i looked around for a solution and eventually settles on file_exists() as a replacement for isset() in my code.
My rationale for using file_exists() is that file that are uploaded(submitted) will be stored in a temp directory during the upload process, and if i check for this temp directory, i would thus be able to ascertain if a file is really uploaded.
After replacing isset() with file_exists my code is now working fine, but i am wondering if this is the correct way to proceed, or if there are any other better alternatives.
I look forward to any opinions and/or advice.
$upload=$_FILES['Upload']['tmp_name'];
if($upload)
{}
This will give the file temp name or null.
I would use the error-code given by $_FILES:
if($_FILES['Upload']['error'] == UPLOAD_ERR_OK) {
//seems to have worked
}
There are even other error-codes you could check against, for example if the file was to big etc.

PHP file upload strange issue

While uploading images files on the live server I have stuck in a strange issue that the move_uploaded_files() function returns true but the image does not get uploaded.
if(move_uploaded_file($_FILES["img"]["tmp_name"],'./shot_images/'.$_FILES["img"]["name"])){
echo "Success";
}
Here, when executed, prints "Success" but the file is not being uploaded on the specified location.
Any kind of help is appreciated.
If move_uploaded_file is returning true then that indicates the file was moved successfully. Let's try some debugging. What happens when you use the following code:
$dest = "./shot_images/{$_FILES["img"]["name"]}";
if(move_uploaded_file($_FILES["img"]["tmp_name"],$dest)){
$realpath = realpath($dest);
$filesize = filesize($realpath);
echo "Success! Uploaded a $filesize file to $realpath";
}
I suspect it is working, it's just not going where you expect...
If this is the case, it might be due to `'./shot_images/' -- personally I rarely (if ever) use relative paths like that. I find it eliminates confusion if I reference the path to the script:
$dest = dirname(__FILE__)."/shot_images/{$_FILES["img"]["name"]}";
if(move_uploaded_file($_FILES["img"]["tmp_name"],$dest)){

PHP - Failed to open stream: no such file or directory - for existing file

I'm writing a PHP application and in my code i want to create create and return images to the browser. However, sometimes i'm getting some weird results where the image cannot be created since the file does not seem to exist.
Here is a sample error message I get and the code in a nutshell. I do know that the image exists, but still the method sometimes fails, and sometimes it succeeds, even for the same file.
The error:
Warning: imagecreatefrompng(path/to/image.png) [function.imagecreatefrompng]: failed to open stream: No such file or directory in file test.php on line 301
The code:
if (file_exists($filename)) {
$image = imagecreatefrompng($filename);
}
I would greatly appreciate any hints or tips of what might be wrong and how I can improve the code to be more stabile.
I suggest you use is_readable
if (is_readable($filename)) {
$image = imagecreatefrompng($filename);
}
The file may "exist" but is the file accessible? what does file_exists actually do?
if it opens the file and then closes it make sure that the file is actualy closed and not locked before imagecreatedfrompng fires.
it would be a good idea to try catching the error in a loop and make 4 or 5 attempts before handing back a controlled error.
maybe try is_readable() or is_writable() instead?
Have you considered checking for the correct permissions? If the file cannot be read, but the directory can, you would get file_exists(...) = true, but would not be able to open a handle to the file.
Use is_readable() to check whatever you have permission to access that file.
You can try GD :
IF($img = #GETIMAGESIZE("testimage.gif")){
ECHO "image exists";
}ELSE{
ECHO "image does not exist";
}
bro check for white spaces in your filepath. I recently had this issue while i was tring to include a file from a module i was creating for an app. Other modules included well when called but one didnt. It turned out that there was a white space in the filepath. I suggest u try php trim() function. If this works holla.

Why 'if(!getimagesize($_FILES['imagefile']['tmp_name']))' doesn't work?

After the file is uploaded, why it always gives me the false even if it is image?
if (!getimagesize($_FILES['imagefile']['tmp_name'])) { $boolean = false; }
By the way, it gives me this error:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in...
Make sure that your file is being uploaded before carrying any operation on it. Just dump the $_FILES array while development, like:
echo '<pre>'; print_r($_FILES);echo '</pre>';
You need to have a enctype attribute applied on your <form> tag, for uploading a file. See http://www.w3.org/TR/html401/interact/forms.html#h-17.3
First check if the upload is actually succeeding:
if ($_FILES['imagefile']['error'] === UPLOAD_ERR_OK) {
if (!getimagesize(....)) {
...
}
} else {
die("Upload failed with error code {$_FILES['imagefile']['error']}");
}
The error constants are defined here. Never assume an upload succeeded. There's only one way for them to work, and a million ways for them to fail.
Given that getimagesize() is complaining about an empty file name, either:
a. the upload failed, the reason code for which will be in the ...['error'] attribute.
b. you're checking the wrong file field name. If you've got <input type="file" name="image" /> then you have to check $_FILES['image'][...].
c. for whatever reason, your web server is able to WRITE files to the temporary directory, but does not have READ permissions.

Categories