This is my first post on Stack Overflow so please be patient with me - I've resorted to posting because I can't find an answer via Google/Stack Overflow otherwise.
I'm new to PHP and learning how to add file uploads. I have a very basic html form that leads to a PHP page.
<form action="UploadPage.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="100000"/>
<input type="file" name="uploadedXML"/>
<input type="submit" value="Upload"/>
The PHP code which processes the file upload has a series of if statements to check whether file is the right type size etc. If there is an error, an appropriate error message is generated on an error page.
I've been testing uploading various file types to ascertain whether the error statements are occurring properly and I'm having trouble with the second (check for file type) and third (check for file size).
If the file type check if statement comes first, I'm finding that if I upload an XML file bigger than the max size (100kb) I still get the error message pertaining to the file type check - when I should be getting the error message pertaining to the file size.
However if i swap the IF statements around so the file size check comes before the file type check, if i upload the incorrect file type but of an agreeable size (eg a small image) I get an error message pertaining to the file being too big, when I'm expecting one pertaining to the file type being incorrect.
<?php
const UploadKey = 'uploadedXML';
const AllowedTypes = ['application/xml','text/xml'];
session_start();
/*Checking for errors*/
if (empty($_FILES[UploadKey]['name'])){//check file actually been uploaded
header("Location: ErrorPage.php");
$_SESSION['errorMessage']="You forgot to add your file!";
die();
}
if (!in_array($_FILES[UploadKey]['type'],AllowedTypes)){//Check correct type of file
header("Location: ErrorPage.php");
$_SESSION['errorMessage']="We only accept XML files I'm afraid";
die();
}
if ($_FILES[UploadKey]['error'] == 2) {//Check if size too big
header("Location: ErrorPage.php");
$_SESSION['errorMessage']="Your file is too big for us to handle, awkward! Please choose a file under 100KB.";
die();
}
$tempFileLoc = $_FILES[UploadKey]['tmp_name'];
$destFileLoc = 'Uploads/'.$_FILES[UploadKey]['name'];
if (file_exists($destFileLoc)) {// Check if file already exists
header("Location: ErrorPage.php");
$_SESSION['errorMessage']="We've already got this file, thanks though";
die();
}
if ($_FILES[UploadKey]['error']>0){
header("Location: ErrorPage.php");
$_SESSION['errorMessage']="Unfortunately there's been an error with the uploading process";
die();
}
Please let me know if you need to see any more of my code to help in answering.
Thanks very much in advance!
Best practice is to build up an error array and if its empty continue to your next step or if not return the errors. You could try something like this. In your code you were overwriting error messages so you only saw the last to apply and not all of the messages that upload may have triggered.
<?php
const UploadKey = 'uploadedXML';
const AllowedTypes = ['application/xml','text/xml'];
$errors = array();
session_start();
/*Checking for errors*/
if (empty($_FILES[UploadKey]['name'])){//check file actually been uploaded
$errors[] = "You forgot to add your file!";
}
if (!in_array($_FILES[UploadKey]['type'],AllowedTypes)){//Check correct type of file
$errors[] ="We only accept XML files I'm afraid";
}
if ($_FILES[UploadKey]['error'] == 2) {//Check if size too big
$errors[] ="Your file is too big for us to handle, awkward! Please choose a file under 100KB.";
}
$tempFileLoc = $_FILES[UploadKey]['tmp_name'];
$destFileLoc = 'Uploads/'.$_FILES[UploadKey]['name'];
if (file_exists($destFileLoc)) {// Check if file already exists
$errors[] ="We've already got this file, thanks though";
}
if ($_FILES[UploadKey]['error'] > 0){
$errors[] = "Unfortunately there's been an error with the uploading process";
}
//if errors were found
if(!empty($error)){
header("Location: ErrorPage.php");
//beware this is now an array and not a single string
$_SESSION['errorMessage']= $errors;
die();
}
That issue was caused as a result of the MAX_FILE_SIZE you included in the HTML form.
If the file you are uploading exceeds the MAX_FILE_SIZE set in the form, PHP automatically empties the tmp_name and type and also turns size to 0 for the file ($_FILES).
So $_FILES[UploadKey]['type'] is empty, thereby the condition you are using to check whether the file type is allowed will return false.
To correct that, you should also check to make sure the type is not empty as well
if (!empty($_FILES[UploadKey]['type']) && !in_array($_FILES[UploadKey]['type'],AllowedTypes)
Something like this:
<?php
if (!empty($_FILES[UploadKey]['type']) && !in_array($_FILES[UploadKey]['type'],AllowedTypes)){// Make sure the file type is not empty
header("Location: ErrorPage.php");
$_SESSION['errorMessage']="We only accept XML files I'm afraid";
die();
}
Related
Ok, I used google over the last 2 days and didn't got what is wrong with my code. First it seemed that I used the wrong path but the official "Hilfe Center" (like helping center or so) from 1&1 said that this must be the right path "e:\Kunden\Homepages\11\d12345678\www\UploadTest" (obviously you have to adapt it to your path, which i got throught phpinfo() )
so I'm using the following code:
<form action=\"upload.php\" method=\"post\" enctype=\"multipart/form-data\">
<input type=\"file\" name=\"datei\"><br>
<input style=\"position:absolute;left:5px\" type=\"submit\" value=\"Hochladen\">
</form>
on the site where you upload the file and
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = "e:\\Kunden\\Homepages\\11\\d12345678\\www\\UploadTest";
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.'); // if we upload large file then we get error.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.'); // if we have no enough permission then got error.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)){
// if everything is fine then we upload file and go to somewhere else
header ('location: whereeveryouwantogo.php');
} else {
echo 'There was an error during the file upload. Please try again.';
}
on the site where the php script is running (upload.php). I got the code on another thread here and wanted to use it for troubleshooting. Later I'm going back to my own code.
I am now at the last error:
'There was an error during the file upload. Please try again.';
I just want to upload .txt files that are later used on a news based site. Thx for any helps in advance!
I think the problem is name of the input or name of the files variable.
$files=$_FILES['datei']['tmp_name'];
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.
Hi guys I'm using this code http://www.w3schools.com/php/php_file_upload.asp to upload files and it works great but now I'm doing a form with an optional image and it won't let me upload. It says it's an invalid file format since it's no file at all. How do I check if there is a file to upload or not and then skip the upload script if there is none?
Thanks!
Note: I have removed the size limitation from the script if that makes any differance.
if ($_FILES['nameofyourfileinput']['error'] === UPLOAD_ERR_OK) {
... file has been uploaded and everything went ok ...
} else if ($_FILES['nameofyourfieinput']['error'] !== UPLOAD_ERR_NO_FILE) {
... something OTHER than a 'no file was uploaded' error has occured...
}
Upload error codes defined here.
Just check if the file's error code isnt 4;
http://php.net/manual/en/features.file-upload.errors.php
So I want to:
upload a csv file which will contain a list of student numbers, one to each line (392232, per line).
populate an array with the student numbers (as i already have a process in place of looking up ids from an array of student numbers and storing etc if they were to add students manually)
I have been lookin at a tutorial found here.
however I am slightly confused with this:
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){...
where does he establish 'tmp_name' from?
anyway, if somebody could explain how I should be going about this I would appreciate the help.
many thanks,
EDIT: added progress of where it is not working.
if(isset($_POST['csv_submit'])){
if(isset($_FILES['csv_file']) && is_uploaded_file($_FILES['csv_file']['tmp_name'])){
//upload directory
$upload_dir = "/ece70141/csv_files/";
//create file name
$file_path = $upload_dir . $_FILES['csv_file']['name'];
//move uploaded file to upload dir
// GETTING THE ERROR BELOW.
if (!move_uploaded_file($_FILES['csv_file']['tmp_name'], $file_path)) {
//error moving upload file
echo "Error moving file upload";
}
print_r($_FILES['csv_file']);
//delete csv file
unlink($file_path);
}
}
$_FILES is a magic superglobal similar to $_POST. It's an array of every file that's been uploaded in the last request, and where that file is stored (tmp_name).
tmp_name is basically generated by the web server to let PHP know where they've stored the file.
You have the following items available to you in each element of the $_FILES array:
name (Original Name of the file)
type (MIME Type of the file, ie. text/plain)
tmp_name (Path to the uploaded files' temporary location)
error (Error occurred when uploading, 0 when no error)
size (Size of the uploaded file, in bytes)
From what I can see in your code, this will work perfectly fine and as discussed in comments, I think the issue lies in your HTML.
The tutorial that you linked to has an incorrect <form ..> tag definition. For file uploads, you're required to set the enctype attribute, below is what it should look like:
<form action="" method="post" enctype="multipart/form-data">
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.