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
Related
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();
}
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'];
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.
I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);
I am have uploading site and I want to know how i can know the space of the server via php ?
for example:
if($_FILES ...) {
if($server_rest_space enough for the file){
// upload it!
}
else{
echo 'no space on your server enough!'; //there is no space!!
}
important another question if the server is full! and some one uploaded file is there an error will happen ?
thank you
Try to use disk_free_space()