Checking for uploaded files with file_exists - php

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.

Related

php - move uploaded file evaluating to false

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

Does move_uploaded_file() automatically deletes the temporary uploaded file after SUCCESSful Move?

My Question is: "Does move_uploaded_file() automatically deletes the temporary uploaded file after successful move ?"
Just to get out of the confusion that do i need to do this:
// Successful upload
if ( move_uploaded_file($file['tmp_name'], $destination) ) {
unlink($file['tmp_name']);
return TRUE;
} else {
// Upload Failed
unlink($file['tmp_name']);
return FALSE;
}
Or is it not needed at all?
You do not need to manually unlink() the temporary file; PHP cleans up after itself after a successful upload. The function is called move_uploaded_file, not copy_uploaded_file.
Yes, it does.
http://php.net/manual/en/function.move-uploaded-file.php
Function description: This function checks to ensure that the file
designated by filename is a valid upload file (meaning that it was
uploaded via PHP's HTTP POST upload mechanism). If the file is valid,
it will be moved to the filename given by destination.
This sort of check is especially important if there is any chance that
anything done with uploaded files could reveal their contents to the
user, or even to other users on the same system.
So we see here:
If the file is valid, it will be moved to the filename given by destination.
Temporary File is Deleted Automatically. You dont have to delete it manually. move_uploaded_file function also not delete this temporary file.

PHP file upload validation

My php upload script works great and is validated for everything from file type to size except if no file exists. You can just hit the submit button and it will send blank data to the upload script. I was trying this:
if (!is_uploaded_file($HTTP_POST_FILES['ufile1']['name']))
{
header("location:../index.php?code=no_file");
}
It won't work :(
Any way of getting this to work?
-mike
Check the error code:
http://www.php.net/manual/en/features.file-upload.errors.php
if ($_FILES['ufile1']['error'] == UPLOAD_ERR_NO_FILE) { /* no file */ }
Note that you should already be checking the error code to make sure that it's UPLOAD_ERR_OK on files that you actually acccept.
Also, $HTTP_POST_FILES is deprecated in favour of $_FILES these days. That signifies to me that you probably want to find a newer tutorial.
What I use is the file_exists($name_of_submitted_file) function at the end to see whether or not the file has been successfully uploaded.

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.

PHP read from uploaded text file?

If I upload a text file via a form, is it possible to output its contents directly from the $_FILES variable rather than saving it onto the server first? I know this is a security risk, but it will only be run on a local machine.
Doing
file_get_contents($_FILES['uploadedfile']['tmp_name']);
is valid however you should also check to make sure that the file was uploaded through a form and that no errors occurred during upload:
if ($_FILES['uploadedfile']['error'] == UPLOAD_ERR_OK //checks for errors
&& is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) { //checks that file is uploaded
echo file_get_contents($_FILES['uploadedfile']['tmp_name']);
}
A helpful link is http://us2.php.net/manual/en/features.file-upload.php
The file is saved to temp directory the moment it's uploaded, but you can use $_FILES['uploadedfile']['tmp_name'] to read it without having to save in a permanent place.
Unfortunately, no. At least not through the $_FILES variable. Sorry.
EDIT: It is always saved as the temp file in $_FILES and you'll always have to use that one for content.

Categories