I do some form validation to ensure that the file a user uploaded is of the right type. But the upload is optional, so I want to skip the validation if he didn't upload anything and submitted the rest of the form. How can I check whether he uploaded something or not? Will $_FILES['myflie']['size'] <=0 work?
You can use is_uploaded_file():
if(!file_exists($_FILES['myfile']['tmp_name']) || !is_uploaded_file($_FILES['myfile']['tmp_name'])) {
echo 'No upload';
}
From the docs:
Returns TRUE if the file named by
filename was uploaded via HTTP POST.
This is useful to help ensure that a
malicious user hasn't tried to trick
the script into working on files upon
which it should not be working--for
instance, /etc/passwd.
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.
EDIT: I'm using this in my FileUpload class, in case it helps:
public function fileUploaded()
{
if(empty($_FILES)) {
return false;
}
$this->file = $_FILES[$this->formField];
if(!file_exists($this->file['tmp_name']) || !is_uploaded_file($this->file['tmp_name'])){
$this->errors['FileNotExists'] = true;
return false;
}
return true;
}
This code worked for me. I am using multiple file uploads so I needed to check whether there has been any upload.
HTML part:
<input name="files[]" type="file" multiple="multiple" />
PHP part:
if(isset($_FILES['files']) ){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
if(!empty($_FILES['files']['tmp_name'][$key])){
// things you want to do
}
}
#karim79 has the right answer, but I had to rewrite his example to suit my purposes. His example assumes that the name of the submitted field is known and can be hard coded in. I took that a step further and made a function that will tell me if any files were uploaded without having to know the name of the upload field.
/**
* Tests all upload fields to determine whether any files were submitted.
*
* #return boolean
*/
function files_uploaded() {
// bail if there were no upload forms
if(empty($_FILES))
return false;
// check for uploaded files
$files = $_FILES['files']['tmp_name'];
foreach( $files as $field_title => $temp_name ){
if( !empty($temp_name) && is_uploaded_file( $temp_name )){
// found one!
return true;
}
}
// return false if no files were found
return false;
}
You should use $_FILES[$form_name]['error']. It returns UPLOAD_ERR_NO_FILE if no file was uploaded. Full list: PHP: Error Messages Explained
function isUploadOkay($form_name, &$error_message) {
if (!isset($_FILES[$form_name])) {
$error_message = "No file upload with name '$form_name' in form.";
return false;
}
$error = $_FILES[$form_name]['error'];
// List at: http://php.net/manual/en/features.file-upload.errors.php
if ($error != UPLOAD_ERR_OK) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
$error_message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
break;
case UPLOAD_ERR_FORM_SIZE:
$error_message = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
break;
case UPLOAD_ERR_PARTIAL:
$error_message = 'The uploaded file was only partially uploaded.';
break;
case UPLOAD_ERR_NO_FILE:
$error_message = 'No file was uploaded.';
break;
case UPLOAD_ERR_NO_TMP_DIR:
$error_message = 'Missing a temporary folder.';
break;
case UPLOAD_ERR_CANT_WRITE:
$error_message = 'Failed to write file to disk.';
break;
case UPLOAD_ERR_EXTENSION:
$error_message = 'A PHP extension interrupted the upload.';
break;
default:
$error_message = 'Unknown error';
break;
}
return false;
}
$error_message = null;
return true;
}
<!DOCTYPE html>
<html>
<body>
<form action="#" method="post" enctype="multipart/form-data">
Select image to upload:
<input name="my_files[]" type="file" multiple="multiple" />
<input type="submit" value="Upload Image" name="submit">
</form>
<?php
if (isset($_FILES['my_files']))
{
$myFile = $_FILES['my_files'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i <$fileCount; $i++)
{
$error = $myFile["error"][$i];
if ($error == '4') // error 4 is for "no file selected"
{
echo "no file selected";
}
else
{
$name = $myFile["name"][$i];
echo $name;
echo "<br>";
$temporary_file = $myFile["tmp_name"][$i];
echo $temporary_file;
echo "<br>";
$type = $myFile["type"][$i];
echo $type;
echo "<br>";
$size = $myFile["size"][$i];
echo $size;
echo "<br>";
$target_path = "uploads/$name"; //first make a folder named "uploads" where you will upload files
if(move_uploaded_file($temporary_file,$target_path))
{
echo " uploaded";
echo "<br>";
echo "<br>";
}
else
{
echo "no upload ";
}
}
}
}
?>
</body>
</html>
But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.
is_uploaded_file() is great to use, specially for checking whether it is an uploaded file or a local file (for security purposes).
However, if you want to check whether the user uploaded a file,
use $_FILES['file']['error'] == UPLOAD_ERR_OK.
See the PHP manual on file upload error messages. If you just want to check for no file, use UPLOAD_ERR_NO_FILE.
I checked your code and think you should try this:
if(!file_exists($_FILES['fileupload']['tmp_name']) || !is_uploaded_file($_FILES['fileupload']['tmp_name']))
{
echo 'No upload';
}
else
echo 'upload';
In general when the user upload the file, the PHP server doen't catch any exception mistake or errors, it means that the file is uploaded successfully.
https://www.php.net/manual/en/reserved.variables.files.php#109648
if ( boolval( $_FILES['image']['error'] === 0 ) ) {
// ...
}
Related
Hello I am trying to check the size of a file in PHP but it does not seem to work. My input page is
<html>
<title>File Upload</title>
<body>
<h1>
Upload Files
</h1>
<form action = "yes.php" method = "POST" enctype="multipart/form-data">
Upload your file
<input type = "file" name = "file" id = "fileToUpload">
<input type ="submit" name ="submit" value = "Start Upload">
</form>
</body>
</html>
This is the yes.php
<?php
$filename = $_FILES["file"]["name"];
$filesize = $_FILES["file"]["size"];
if (isset($_POST["submit"])) {
echo "$filename";
echo "\n$filesize";
if ($filesize < 4) {
echo "good";
} else {
echo "bad";
}
}
?>
It outputs
disc.mp4 0good
The file disc.mp4 is 5.8 MB but it returns as 0 MB even when it correctly identifies the name of the file. How can I fix this?
The different keys of the $_FILES array are explained here. Your code is taking for granted that every script invocation contains a valid file upload, which of course if often untrue: just open yes.php in your browser and you'll see (or you should see) lots of error messages. You're also making a strange check: the upload is valid if the file size is 0 to 3 bytes :-!
The bare minimum you need is:
Accommodate the fact that $_FILES['file'] may or may not exist.
Verify whether the upload succeeded.
If you expect a 5.8 MB file, don't require it to have an arbitrary smaller size.
Following you code style, I'd be something like:
<?php
$error = $_FILES["file"]["error"] ?? null;
$filename = $_FILES["file"]["name"] ?? null;
$filesize = $_FILES["file"]["size"] ?? null;
$expected_size = 5.8 * 1024 * 1024; # Assuming you want to enforce this for some reason
if ($error === UPLOAD_ERR_OK) {
echo "$filename";
echo "\n$filesize";
if ($filesize != $expected_size) {
echo "good";
} else {
echo "bad";
}
} elseif($error !== UPLOAD_ERR_NO_FILE) {
echo "upload failed";
}
I need to get this script to check if the uploaded file is a video file or not and whether the file size is too big or not over the limit. Therefore, need to replace the getimagesize with something else that gets the video file size. How can I accomplish this? Which function to use here? getvideosize function does not exist.
This is where I am stuck.
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications/";
//Make Directory under $user in 'uploads/videos/id_verifications'
Folder.
if(!is_dir($directory_path . $user)) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir($directory_path . $user, "$mode", TRUE); //IS THIS LINE
CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
$file = $_FILES["id_verification_video_file"]["name"];
// in PHP 4, we can do:
$fhandle = finfo_open(FILEINFO_MIME);
$mime_type = finfo_file($fhandle,$file); // e.g. gives "video/mp4"
// in PHP 5, we can do:
$file_info = new finfo(FILEINFO_MIME); // object oriented approach!
$mime_type = $file_info->buffer(file_get_contents($file)); // e.g. gives
"video/mp4"
switch($mime_type) {
case "video/mp4":
// my actions go here...
}
// Let's assume that the name attribute of the file input field I have
used is "id_verification_video_file"
$tempFile = $_FILES['id_verification_video_file']['tmp_name']; // path of
the temp file created by PHP during upload. I MOST LIKELY GOT THIS LINE
WRONG AT THE END PART. HOW TO CORRECT THIS ?
$videoinfo_array = getimagesize($tempFile); // returns a false if not a
valid image file
if ($videoinfo_array !== false) {
$mime_type = $videoinfo_array['mime'];
switch($mime_type) {
case "video/mp4":
// your actions go here...
move_uploaded_file("$file_tmp", "$directory_path" . "$user/" .
"$file_name"); //IS THIS LINE CORRECT ?
//Notify user their Id Verification Video File was uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded successfully!";
exit();
}
}
else {
echo "This is not a valid video file";
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
Best I done so far is above. I'd appreciate if you guys can add the correct lines where they should be and add comments so I can easily spot your changes and learn from the corrections.
EDIT:
Folks, I managed to fix a lot of things on my current update. But, one new problem. The move_uploaded_file() is failing. Why is that ? Do have a look. I actually wrote my questions to you in my code's comments in CAPITAL. If you could kindly answer these questions then I'd be grateful and hopefully we could close this thread as SOLVED asap.
<?php
//Required PHP Files.
include 'header_account.php'; //Required on all webpages of the Site.
?>
<?php
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) &&
$_FILES["id_verification_video_file"]["Error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"]
["ERROR"];
print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
//Feed Id Verification Video File Upload Directory path.
$directory_path = "uploads/videos/id_verifications";
//Make Directory under $user in
'uploads/videos/id_verifications' Folder if it doesn't exist.
if(!is_dir("$directory_path/$user")) //IS THIS LINE CORRECT ?
{
$mode = "0777";
mkdir("$directory_path/$user", $mode, TRUE); //IS THIS
LINE CORRECT ?
}
//Grab Uploading File details.
$Errors = Array(); //SHOULD I KEEP THIS LINE OR NOT ?
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]
["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
echo "File Type: $file_type<br>"; //Outputs: "". WHY $file_type SHOWS
BLANK VALUE WHEN UPLOADING VIDEO FILES ? WORKS WITH OTHER FILES, LIKE
JPEG.
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
echo "File Name: $file_name<br>"; //Outputs: "id_check.mp4"
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
echo "File Extension: $file_extension<br>"; //Outputs: "mp4"
if(file_exists($directory_path . "$user/" . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE NEXT ONE ?
//if(file_exists($directory_path . $user . '/' . $file_name))
//WHICH LINE IS CORRECT ? THIS ONE OR THE PREVIOUS ONE ?
{
$Errors[] = "Error: You have already uploaded a video
file to verify your ID!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*1; //Allowed
limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*1;
$max_file_size_allowed_in_megabytes = 1;
$max_file_size_allowed =
"$max_file_size_allowed_in_bytes";
//Create a fileinfo respource.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
//Apply the fileinfo resource and the finfo_file()
function to the uploading given file.
$mime = finfo_file($finfo,$file_name);
//Close the fileinfo resource.
finfo_close($finfo); echo "Mime: $mime<br>"; //exit;
//Outputs: video/mp4
//Verify File Extension.
//if(!in_array($file_extension, $allowed_file_extensions))
die("Error 1: Select a valid video file format. Select an Mp4 file.");
//Verify MIME Type of the File.
if(!in_array($mime, $allowed_file_extensions)) die("Error 2:
Select a valid video file format. Select an Mp4 file.");
elseif(!in_array($file_type, $allowed_file_extensions))
die("Error 3: There was a problem uploading your file $file_name! Make
sure your file is an MP4 video file. You may try again."); //IS THIS LINE
CORRECT ?
//Verify File Size. Allowed Max Limit: 1MB.
if($file_size>$max_file_size_allowed) die("Error 4: Your
Video File Size is larger than the allowed limit of:
$max_file_size_allowed_in_megabytes.");
//Move uploaded File to newly created directory on the
server.
if(!move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name")) die("Error 5: Your file failed to
upload! Try some other time.");
else
{
move_uploaded_file($file_tmp,
"$directory_path/$user/$file_name"); //WHY IS NOT THIS LINE OF CODE
MOVING THE FILE TO DESTINATION ?
//Notify user their Id Verification Video File was
uploaded successfully.
echo "Your Video File \"$file_name\" has been uploaded
successfully!";
exit();
}
}
}
}
?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification Form</h3>
</p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
<?php
include 'footer_account.php'; //Required on all webpages of the Site.
?>
I get echoed when trying to upload an mp4 file:
Error 3: There was a problem uploading your file id_check.mp4! Make sure your file is an MP4 video file. You may try again.
Should I set the folder permissions to 0644 from 0777 ? I am being told I should not allow any files to be executable in the folder by users (file uploaders) and so I should set it to readable & writeable only to "0644". I need your expert opinion on this.
Just playing around with uploading files as it's actually something I've never done before. I copied some supposedly working code from here.
I'm using cPanel hosting from Namecheap, with absolutely nothing changed from the default config.
I think the most likely problem is something very basic that I haven't activated. My HTML looks like this
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
Your Photo: <input type="file" name="photo" size="25" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and my PHP looks like this
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
//you get the following information for each file:
$_FILES['field_name']['name']
$_FILES['field_name']['size']
$_FILES['field_name']['type']
$_FILES['field_name']['tmp_name']
}
When I try to upload an image, I get a 500 Internal Server Error when I hit submit.
What am I missing?
Thanks
Get rid of the stuff at the bottom:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/'.$new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
Not sure what that was for... Also, try checking the Namecheap php.ini in your CPanel to see what the max upload size is so your users get your error, not a PHP error or a 500.
I would like to show the errors next to input field. I tried echoing the error but it just displays the word Array. How can I show the error next to input field? Also I would like to let the user upload 5 photos and only the first photo is required. I mean the user can upload 5 photos but all the 5 photos aren't required only one. is that possible? thanks
<?php
$out['error'][]=''; //this is what I added
function uploadFile ($file_field = null, $check_image = false, $random_name = false) {
//Config Section
//Set file upload path
$path = 'productpic/'; //with trailing slash
//Set max file size in bytes
$max_size = 2097152;
//Set default file extension whitelist
$whitelist_ext = array('jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
//The Validation
// Create an array to hold any output
$out = array('error'=>null);
if (!$file_field) {
$out['error'][] = "Please specify a valid form field name";
}
if (!$path) {
$out['error'][] = "Please specify a valid upload path";
}
if (count($out['error'])>0) {
return $out;
}
//Make sure that there is a file
if((!empty($_FILES[$file_field])) && ($_FILES[$file_field]['error'] == 0)) {
// Get filename
$file_info = pathinfo($_FILES[$file_field]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];
//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$out['error'][] = "Invalid file Extension";
}
//Check that the file is of the right type
if (!in_array($_FILES[$file_field]["type"], $whitelist_type)) {
$out['error'][] = "Invalid file Type";
}
//Check that the file is not too big
if ($_FILES[$file_field]["size"] > $max_size) {
$out['error'][] = "We are sorry, the image must be less than 2MB";
}
//If $check image is set as true
if ($check_image) {
if (!getimagesize($_FILES[$file_field]['tmp_name'])) {
$out['error'][] = "The file you trying to upload is not an Image, we only accept images";
}
}
//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());
if (!$tmp || $tmp == '') {
$out['error'][] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}
//Check if file already exists on server
if (file_exists($path.$newname)) {
$out['error'][] = "The image you trying to upload already exists, please upload only once";
}
if (count($out['error'])>0) {
//The file has not correctly validated
return $out;
}
if (move_uploaded_file($_FILES[$file_field]['tmp_name'], $path.$newname)) {
//Success
$out['filepath'] = $path;
$out['filename'] = $newname;
return $out;
} else {
$out['error'][] = "Server Error!";
}
} else {
$out['error'][] = "Please select a photo";
return $out;
}
}
?>
<?php
if (isset($_POST['submit'])) {
$file = uploadFile('file', true, false);
if (is_array($file['error'])) {
$message = '';
foreach ($file['error'] as $msg) {
$message .= '<p>'.$msg.'</p>';
}
} else {
$message = "File uploaded successfully";
$sub=1;
}
echo $message;
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<?php
ini_set( "display_errors", 0);
if($sub==0)
{
?>
<input name="file" type="file" size="20" /><span><?php echo $out['error'] ;?></span> //It displays here just the word Array
<input name="submit" type="submit" value="Upload" />
<?php
}
?>
</form>
Because $out['error'] is an array, echoing it will output Array, as you noticed. To output it as a string you'll need to convert it first; one option to do so is using implode. I'd suggest using <br> as the 'glue' so that each error will show on a different line.
So,
<input name="file" type="file" size="20" /><span><?php echo implode('<br>', $out['error']) ;?></span>
<input name="submit" type="submit" value="Upload" />
However, perhaps a better solution would be to store the error as a string ($out['error'] = 'There was an error' rather than $out['error'][] = 'There was an error') and using a proper control structure to ensure that once an error is found the validation check ends and the form with the error message is output.
For the control structure you could do:
if ($first_check)
{
$out['error'] = 'First error message';
}
elseif ($second_check)
{
$out['error'] = 'Second error message';
}
else
{
$out['success'] = 'Success message';
}
I have this code but this code is not allowing me to upload any types of video files.
This always shows 'Please Select File To Upload'.
Code for uploading file shown below:
$fileElementName = 'ufile';
if (!empty($_FILES[$fileElementName]['error'])) {
switch ($_FILES[$fileElementName]['error']) {
case '1':
$error = 'You Are Not Allowed To Upload File Of This Size';
break;
case '2':
$error = 'You Can Not Not Upload File Of This Size';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'Not Able To Upload';
break;
case '6':
$error = 'Server Error Please Try Again Later';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'Error Found But Did Not Found What Was Problem';
}
} elseif (empty($_FILES['ufile']['tmp_name']) || $_FILES['ufile']['tmp_name'] == 'none') {
$error = 'Please Select File To Upload';
$success = FALSE;
} else {
$file = $_FILES['ufile']['name'];
move_uploaded_file($_FILES["ufile"]["tmp_name"], $path);
}
echo json_encode($arr);
In the above code $path is upload/ which is correct--it works for all file except video.
This code always shows 'Please Select File To Upload'
Your error handling is broken. On uploads, a successful upload has error code 0 (UPLOAD_ERR_OK constant). You're doing
if (!empty(...))
empty() evaluates to boolean TRUE for zero values, so you're basically saying "if there was no error, act like there was one".
Your code really should be:
if ($_FILES['ufile']['error'] !== UPLOAD_ERR_OK) {
... error handling switch() here ...
die();
}
Your subsequent empty() checks on the tmp_name are also pointless. If no file was uploaded, then you'll get error code 4 (UPLOAD_ERR_NO_FILE) anyways.
Then for the move_uploaded_file() stuff, you pull out the uploaded filename into $file, but then move the file to $path, which is not set anywhere in your code. As a word of warning, never EVER use the user-supplied filename directly in file-system operations. It is trivial to embed path information in that field, and if you do not take appropriate sanitization/security precautions, you'll be allowing malicious users to scribble on any file on your server.
Did you defined the enctype of your form?
In the form tag insert the enctype as follow: enctype="multipart/form-data"
check permissions, if $path exists, etc, and change move_uploaded_file to copy, some servers have a restrict permission on folders
EDIT: Maybe same issue https://stackoverflow.com/a/3587158/1519436