php file upload always uploading files even if errors - php

I am trying to upload either pdf or jpg, jpeg files to a folder and the code is as follows:
//Get the uploaded file information
if(!$_FILES['medreport']['error'])
{
$medreport = basename($_FILES['medreport']['name']);
$medreport_extn = substr($medreport, strrpos($medreport, '.') + 1);//get the file extension of the file
$medreport_size = $_FILES["medreport"]["size"]/1024;//size in KBs
$tmp_path = $_FILES["medreport"]["tmp_name"];
$report_folder = "../reports/";
//Settings
$max_allowed_file_size = 200; // size in KB
$allowed_extensions = array("jpg", "jpeg", "pdf");
//Validations
}
if($medreport_size > $max_allowed_file_size )
{
$error[] = "Size of the report file should be less than $max_allowed_file_size KB";
}
//Validate the file extension
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$medreport_extn) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
$error[] = "The uploaded report file is not a supported file type. "."Only pdf, jpg and jpeg report file types are supported. ";
}
//replace filename with unixtime
$unixtime =time();
$medreport = $unixtime.mt_rand(0,9).'.'.$medreport_extn;
$report_path = $report_folder . $medreport;
if(is_uploaded_file($tmp_path))
{
if(!copy($tmp_path,$report_path))
{
$error[] = 'Error while copying the uploaded report file';
}
}
while trying to upload files with correct extension and size i am able to upload it.
But if i try to upload an over sized or incorrect format file, it displays my error message, but the file always get uploaded to the folder.
Why is it so ?? Please, What is wrong with my code??
Is the way, i am doing it is secure enough ?? the folder is owned by www-data and permission is 755. I have a .htaccess file too in the file upload folder to prevent executables as follows:
SetHandler none
SetHandler default-handler
Options -ExecCGI
php_flag engine off
The file always uploading is confusing me.

You are not using the errors you just found to check if you need to continue.
This:
if(is_uploaded_file($tmp_path))
Should be something like:
if(count($error) === 0 && is_uploaded_file($tmp_path))
And you should initialize your $error array at the start as an empty array if you are not doing that already.

Related

Warning: mime_content_type(): Empty filename or path

Folks,
I created a form where you upload your image file and video file.
Form needs to check if right file formats getting submitted or not and whether the file sizes are within the limits or not.
That is all.
I get this error:
" Warning: mime_content_type(): Empty filename or path in C:\xampp\htdocs\test\02-04-2020\upload_test.php on line 100"
Line 100 code is this:
if(!in_array(mime_content_type($video_file_tmp),$video_mime_type))
NOTE: I checking against tmp file above. Should I be doing that or checking against actual file name ?
Talking about these:
$video_file_name = $_FILES["id_verification_video_file"]["name"];
$video_file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
Context
if(!in_array(mime_content_type($video_file_tmp),$video_mime_type))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 3b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!';
$error = 1;
}
And I get these custom errors triggered:
ERROR STATEMENT 2a: Invalid File! Only JPG, JPEG, PNG and GIF image files are allowed!
ERROR STATEMENT 3b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!
They are related to these lines:
1.
if(!in_array(pathinfo($img_file_tmp, PATHINFO_EXTENSION),$img_allowed_ext))
{
$error_msg['img_error']= '<p class="text- danger">ERROR STATEMENT 2a: Invalid File! Only JPG, JPEG, PNG and GIF image files are allowed!';
$error = 1;
}
2.
if(!in_array(mime_content_type($video_file_tmp),$video_mime_type))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 3b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!';
$error = 1;
}
NOTE AGAIN: I checking against tmp file above. Should I be doing that or checking against actual file name ?
If I can findout why I am getting that first WARNING ERROR then the other 2 custom errors would disappear. What does that WARNING mean and why am I getting it ?
I was checking valid file extensions against the tmp files. Watch-out for this on my code.
Full Code
<?php
$error_msg = array();
$success_msg = array();
$img_allowed_ext = array('gif','jpeg','jpg','png');
$video_allowed_ext = array('mp4','wav','wmv','avi','flv','ogg');
$img_mime_type = array('image/gif','image/jpeg','image /jpg','image/png');
$video_mime_type = array('video/mp4','video/wav','video /wmv','video/avi','video/flv','video/ogg');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$error = 0 ;
//var_dump($_Files); //For debugging.
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) || !isset($_FILES['id_verification_img_file']))
{
$error_msg['all_fields'] = '<p class="text-danger">ERROR STATEMENT 1: Select all fields that have asterisks besides them!</p>';
$error = 1;
}
else
{
//Image Files
$img_file_name = $_FILES["id_verification_img_file"]["name"];
$img_file_tmp = $_FILES["id_verification_img_file"]["tmp_name"];
$img_file_type = $_FILES["id_verification_img_file"]["type"];
$img_file_size = $_FILES["id_verification_img_file"]["size"];
$img_file_error = $_FILES['id_verification_img_file']['error'];
$img_file_ext = pathinfo($img_file_name, PATHINFO_EXTENSION);
//$img_file_ext = pathinfo($img_file_tmp, PATHINFO_EXTENSION); //WRONGLY SAVES FILE NAMES WITH .tmp!
//Video Files
$video_file_name = $_FILES["id_verification_video_file"]["name"];
$video_file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$video_file_type = $_FILES["id_verification_video_file"]["type"];
$video_file_size = $_FILES["id_verification_video_file"]["size"];
$video_file_error = $_FILES['id_verification_video_file']['error'];
$video_file_ext = pathinfo($video_file_name, PATHINFO_EXTENSION);
//$video_file_ext = pathinfo($video_file_tmp, PATHINFO_EXTENSION); //WRONGLY SAVES FILE NAMES WITH .tmp!
//Checking File Type.
//Checking File Type using pathinfo_extension() Function.
/*
if(!in_array(pathinfo($img_file_name, PATHINFO_EXTENSION),$img_allowed_ext))
{
$error_msg['img_error']= '<p class="text-danger">ERROR STATEMENT 2a: Invalid File! Only JPG, JPEG, PNG and GIF image files are allowed!';
$error = 1;
}
*/
//The error statement gets echoed even after selecting right type of file!
if(!in_array(pathinfo($img_file_tmp, PATHINFO_EXTENSION),$img_allowed_ext))
{
$error_msg['img_error']= '<p class="text-danger">ERROR STATEMENT 2a: Invalid File! Only JPG, JPEG, PNG and GIF image files are allowed!';
$error = 1;
}
/*
if(!in_array(pathinfo($video_file_name, PATHINFO_EXTENSION),$video_allowed_ext))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 2b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!';
$error = 1;
}
*/
//The error statement gets echoed even after selecting right type of file!
if(!in_array(pathinfo($video_file_tmp, PATHINFO_EXTENSION),$video_allowed_ext))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 2b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!';
$error = 1;
}
//Checking File Type.
//Checking Mime Type using mime_content_type() Function.
/*
if(!in_array(mime_content_type($img_file_name),$img_mime_type))
{
$error_msg['img_error']= '<p class="text-danger">ERROR STATEMENT 3a: Invalid File! Only JPG, JPEG, PNG and GIF image files are allowed!';
$error = 1;
}
*/
if(!in_array(mime_content_type($img_file_tmp),$img_mime_type))
{
$error_msg['img_error']= '<p class="text-danger">ERROR STATEMENT 3a: Invalid File! Only JPG, JPEG, PNG and GIF image files are allowed!';
$error = 1;
}
/*
if(!in_array(mime_content_type($video_file_name),$video_mime_type))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 3b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!';
$error = 1;
}
*/
if(!in_array(mime_content_type($video_file_tmp),$video_mime_type))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 3b: Invalid File! Only MP4, WAV, OGG, FLV, WMV and AVI video files are allowed!';
$error = 1;
}
//Checking File Sizes using filesize() function.
//5MB Image Size Allowed.
if(filesize($img_file_tmp) > 5000000)
{
$error_msg['img_file_size_err'] = '<p class="text-danger">ERROR STATEMENT 4a: File Size is greater than 5MB. File Size should not exceed the 100MB limit!';
$error = 1;
}
//10MB Video Size Allowed.
if(filesize($video_file_tmp) > 10000000)
{
$error_msg['video_file_size_err'] = '<p class="text-danger">ERROR STATEMENT 4b: File Size is greater than 10MB. File Size should not exceed the 100MB limit!';
$error = 1;
}
//Checking for NO errors to proceed with the script flow.
if($error == 0)
{
$user = $user; //Account Username here.
//$db_user = 'followingbrowser_user'; //Database username here. Has to be in quotes.
$db_user = 'root'; //Database username here. Has to be in quotes.
//Feed Id Verification Video & Image File Upload Directory path.
$default_directory_path = 'uploads/id_verifications'; //Permanent Storage Directory Path.
$default_directory_path_and_user_dir = "$default_directory_path"."/".$user; //Permanent Storage Directory Path for $user Folder.
//Create $user Folder in Permanent Storage Directory Path: 'uploads/videos/id_verifications' Folder.
if(!is_dir($default_directory_path_and_user_dir))
{
//$db_user = 'followingbrowser_user'; //Has to be in quotes.
$db_user = 'root'; //Has to be in quotes.
$mode = 0755;
mkdir($default_directory_path_and_user_dir,$mode,TRUE); //This line is working and is correct even without quoting "$mode". Requinix sugegsted to quote "$mode".
}
//Making Directories of every Files Types for Respective User.
$user_img_directory = "$default_directory_path_and_user_dir"."/"."imgs";
$user_video_directory = "$default_directory_path_and_user_dir"."/"."videos";
if(!is_dir($user_img_directory))
{
//$db_user = 'followingbrowser_user'; //Has to be in quotes.
$db_user = 'root'; //Has to be in quotes.
$mode = 0755;
mkdir($user_img_directory,$mode,TRUE); //This line is correct and working even without quoting $mode.
}
if(!is_dir($user_video_directory))
{
//$db_user = 'followingbrowser_user'; //Has to be in quotes.
$db_user = 'root'; //Has to be in quotes.
$mode = 0755;
mkdir($user_video_directory,$mode,TRUE); //This line is correct and working even without quoting $mode.
}
//User Files Directories.
$default_directory_path = 'uploads/id_verifications'; //Permanent Storage Directory Path.
$default_directory_path_and_user_dir = "$default_directory_path"."/"."$user"; //Permanent Storage Directory Path for $user Folder.
$user_img_directory = "$default_directory_path_and_user_dir"."/"."img";
$user_video_directory = "$default_directory_path_and_user_dir"."/"."videos";
$user_id_img_file = "$user_img_directory"."/"."$img_file_name"."$img_file_ext";
$user_id_video_file = "$user_video_directory"."/"."$video_file_name"."$video_file_ext";
//Uploading the Files.
$upload_err = 0;
//Uploading Image File
if(file_exists("$user_img_directory/$user.gif"))
{
$error_msg['upload_img_error'] = '<p class="text-danger">ERROR STATEMENT 5d: You have already uploaded an Image File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</p>';
$upload_err = 1;
}
elseif(file_exists("$user_img_directory/$user.jpeg"))
{
$error_msg['upload_img_error'] = '<p class="text-danger">ERROR STATEMENT 5a: You have already uploaded an Image File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</p>';
$upload_err = 1;
}
elseif(file_exists("$user_img_directory/$user.jpg"))
{
$error_msg['upload_img_error'] = '<p class="text-danger">ERROR STATEMENT 5b: You have already uploaded an Image File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</p>';
$upload_err = 1;
}
elseif(file_exists("$user_img_directory/$user.png"))
{
$error_msg['upload_img_error'] = '<p class="text-danger">ERROR STATEMENT 5c: You have already uploaded an Image File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</p>';
$upload_err = 1;
}
//Uploading Video File
if(file_exists("$user_video_directory/$user.mp4"))
{
$error_msg['upload_video_error'] = '<p class="text-danger">ERROR STATEMENT 5e: You have already uploaded a Video File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</</p>';
$upload_err = 1;
}
elseif(file_exists("$user_video_directory/$user.wav"))
{
$error_msg['upload_video_error'] = '<p class="text-danger">ERROR STATEMENT 5f: You have already uploaded a Video File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</</p>';
$upload_err = 1;
}
if(file_exists("$user_video_directory/$user.wmv"))
{
$error_msg['upload_video_error'] = '<p class="text-danger">ERROR STATEMENT 5e: You have already uploaded a Video File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</</p>';
$upload_err = 1;
}
elseif(file_exists("$user_video_directory/$user.flv"))
{
$error_msg['upload_video_error'] = '<p class="text-danger">ERROR STATEMENT 5f: You have already uploaded a Video File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</</p>';
$upload_err = 1;
}
elseif(file_exists("$user_video_directory/$user.ogg"))
{
$error_msg['upload_video_error'] = '<p class="text-danger">ERROR STATEMENT 5f: You have already uploaded a Video File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</</p>';
$upload_err = 1;
}
//Checking for NO errors to proceed with the script flow.
if($upload_err == 0)
{
//DIRECTORY PATHS AGAIN
//1. $default_directory_path = 'uploads/id_verifications'; //Permanent Storage Directory Path.
//2. $default_directory_path_and_user_dir = "$default_directory_path"."/".$user; //Permanent Storage Directory Path for $user Folder.
//3. $user_img_directory = $default_directory_path_and_user_dir."."/".img';
//4. $user_video_directory = $default_directory_path_and_user_dir."."/".videos';
if(is_uploaded_file($img_file_tmp) && is_uploaded_file($video_file_tmp))
{
if(move_uploaded_file($img_file_tmp,$user_id_img_file))
{
rename($user_id_img_file,$user_img_directory.$user.'.'.$img_file_ext);
}
if(move_uploaded_file($video_file_tmp,$user_id_video_file))
{
rename($user_id_video_file,$user_video_directory.$user.'.'.$video_file_ext);
}
$success_msg['all_uploads'] = 'SUCCESS STATEMENT 6a: Both Image and Video files have been uploaded successfully!';
}
else
{
$error_msg['all_uploads'] = 'ERROR STATEMENT 6b: Both Image and Video files failed to upload successfully! You may try again another time!';
exit();
}
}
}
}
}
?>
4th Apr 2020 UPDATE:
Folks,
I updated the script but no luck. Problem remains.
I get these errors:
Warning: mime_content_type(loudgob.png): failed to open stream: No such file or directory in C:\xampp\htdocs\test\02-04-2020\upload_test.php on line 57
Warning: mime_content_type(loudgob.mp4): failed to open stream: No such file or directory in C:\xampp\htdocs\test\02-04-2020\upload_test.php on line 63
Warning: filesize(): stat failed for loudgob.png in C:\xampp\htdocs\test\02-04-2020\upload_test.php on line 72
Warning: filesize(): stat failed for loudgob.mp4 in C:\xampp\htdocs\test\02-04-2020\upload_test.php on line 78
Full Update:
<?php
$error_msg = array();
$success_msg = array();
$img_allowed_ext = array('png');
$video_allowed_ext = array('mp4');
$img_mime_type = array('image/png');
$video_mime_type = array('video/mp4');
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$error = 0 ;
//var_dump($_Files); //For debugging.
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]) || !isset($_FILES['id_verification_img_file']))
{
$error_msg['all_fields'] = '<p class="text-danger">ERROR STATEMENT 1: Select all fields that have asterisks besides them!</p>';
$error = 1;
}
else
{
//Image Files
$img_file_name = $_FILES["id_verification_img_file"]["name"];
$img_file_tmp = $_FILES["id_verification_img_file"]["tmp_name"];
$img_file_type = $_FILES["id_verification_img_file"]["type"];
$img_file_size = $_FILES["id_verification_img_file"]["size"];
$img_file_error = $_FILES['id_verification_img_file']['error'];
$img_file_ext = pathinfo($img_file_name, PATHINFO_EXTENSION);
//Video Files
$video_file_name = $_FILES["id_verification_video_file"]["name"];
$video_file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$video_file_type = $_FILES["id_verification_video_file"]["type"];
$video_file_size = $_FILES["id_verification_video_file"]["size"];
$video_file_error = $_FILES['id_verification_video_file']['error'];
$video_file_ext = pathinfo($video_file_name, PATHINFO_EXTENSION);
//Checking File Type using pathinfo_extension() Function.
if(!in_array(pathinfo($img_file_name, PATHINFO_EXTENSION),$img_allowed_ext))
{
$error_msg['img_error']= '<p class="text-danger">ERROR STATEMENT 2a: Invalid File! Only jpg, jpeg, png and gif image files are allowed!';
$error = 1;
}
if(!in_array(pathinfo($video_file_name, PATHINFO_EXTENSION),$video_allowed_ext))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 2b: Invalid File! Only mp4, wav, ogg, flv, wmv and avi video files are allowed!';
$error = 1;
}
//Checking Mime Type using mime_content_type() Function.
if(!in_array(mime_content_type($img_file_name),$img_mime_type))
{
$error_msg['img_error']= '<p class="text-danger">ERROR STATEMENT 3a: Invalid File! Only jpg, jpeg, png and gif image files are allowed!';
$error = 1;
}
if(!in_array(mime_content_type($video_file_name),$video_mime_type))
{
$error_msg['video_error'] = '<p class="text-danger">ERROR STATEMENT 3b: Invalid File! Only mp4, wav, ogg, flv, wmv and avi video files are allowed!';
$error = 1;
}
//Checking File Sizes using filesize() function.
//5MB Image Size Allowed.
if(filesize($img_file_name) > 5000000)
{
$error_msg['img_file_size_err'] = '<p class="text-danger">ERROR STATEMENT 4a: File Size is greater than 5MB. File Size should not exceed the 100MB limit!';
$error = 1;
}
//10MB Video Size Allowed.
if(filesize($video_file_name) > 10000000)
{
$error_msg['video_file_size_err'] = '<p class="text-danger">ERROR STATEMENT 4b: File Size is greater than 10MB. File Size should not exceed the 100MB limit!';
$error = 1;
}
//Checking for NO errors to proceed with the script flow.
if($error == 0)
{
$user = $user; //Account Username here.
//$db_user = 'followingbrowser_user'; //Database username here. Has to be in quotes.
$db_user = 'root'; //Database username here. Has to be in quotes.
//Feed Id Verification Video & Image File Upload Directory path.
$default_directory_path = 'uploads/id_verifications'; //Permanent Storage Directory Path.
$default_directory_path_and_user_dir = "$default_directory_path"."/"."$user"; //Permanent Storage Directory Path for $user Folder.
//Create $user Folder in Permanent Storage Directory Path: 'uploads/videos/id_verifications' Folder.
if(!is_dir($default_directory_path_and_user_dir))
{
//$db_user = 'followingbrowser_user'; //Has to be in quotes.
$db_user = 'root'; //Has to be in quotes.
$mode = 0755;
mkdir($default_directory_path_and_user_dir,$mode,TRUE); //This line is working and is correct even without quoting "$mode". Requinix sugegsted to quote "$mode".
}
//Making Directories of every Files Types for Respective User.
$user_img_directory = "$default_directory_path_and_user_dir"."/"."imgs";
$user_video_directory = "$default_directory_path_and_user_dir"."/"."videos";
if(!is_dir($user_img_directory))
{
//$db_user = 'followingbrowser_user'; //Has to be in quotes.
$db_user = 'root'; //Has to be in quotes.
$mode = 0755;
mkdir($user_img_directory,$mode,TRUE); //This line is correct and working even without quoting $mode.
}
if(!is_dir($user_video_directory))
{
//$db_user = 'followingbrowser_user'; //Has to be in quotes.
$db_user = 'root'; //Has to be in quotes.
$mode = 0755;
mkdir($user_video_directory,$mode,TRUE); //This line is correct and working even without quoting $mode.
}
//User Files Directories.
$default_directory_path = 'uploads/id_verifications'; //Permanent Storage Directory Path.
$default_directory_path_and_user_dir = "$default_directory_path"."/"."$user"; //Permanent Storage Directory Path for $user Folder.
$user_img_directory = "$default_directory_path_and_user_dir"."/"."img";
$user_video_directory = "$default_directory_path_and_user_dir"."/"."videos";
$user_id_img_file = "$user_img_directory"."/"."$img_file_name"."$img_file_ext";
$user_id_video_file = "$user_video_directory"."/"."$video_file_name"."$video_file_ext";
//Uploading the Files.
$upload_err = 0;
//Uploading Image File
if(file_exists("$user_img_directory/$user.png"))
{
$error_msg['upload_img_error'] = '<p class="text-danger">ERROR STATEMENT 5c: You have already uploaded an Image File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</p>';
$upload_err = 1;
}
//Uploading Video File
if(file_exists("$user_video_directory/$user.mp4"))
{
$error_msg['upload_video_error'] = '<p class="text-danger">ERROR STATEMENT 5e: You have already uploaded a Video File to verify your ID! No need to upload to get verified again! If you uploaded the wrong file then you need to delete this account and open a new one!</</p>';
$upload_err = 1;
}
//Checking for NO errors to proceed with the script flow.
if($upload_err == 0)
{
//DIRECTORY PATHS AGAIN
//1. $default_directory_path = 'uploads/id_verifications'; //Permanent Storage Directory Path.
//2. $default_directory_path_and_user_dir = "$default_directory_path"."/".$user; //Permanent Storage Directory Path for $user Folder.
//3. $user_img_directory = $default_directory_path_and_user_dir."."/".img';
//4. $user_video_directory = $default_directory_path_and_user_dir."."/".videos';
if(is_uploaded_file($img_file_tmp) && is_uploaded_file($video_file_tmp))
{
if(move_uploaded_file($img_file_tmp,$user_id_img_file))
{
rename($user_id_img_file,$user_img_directory.$user.'.'.$img_file_ext);
}
if(move_uploaded_file($video_file_tmp,$user_id_video_file))
{
rename($user_id_video_file,$user_video_directory.$user.'.'.$video_file_ext);
}
$success_msg['all_uploads'] = 'SUCCESS STATEMENT 6a: Both Image and Video files have been uploaded successfully!';
}
else
{
$error_msg['all_uploads'] = 'ERROR STATEMENT 6b: Both Image and Video files failed to upload successfully! You may try again another time!';
exit();
}
}
}
}
}
?>
Why is it unable to find the file ? I browsed to the files and selected them. Both png and mp4 files.

is_uploaded_file function worked in linux But not in Windows

Code
if(is_array($_FILES) && isset($_FILES['photography_attachment'])) {
if(is_uploaded_file($_FILES['photography_attachment']['tmp_name'])) {
$fileName = $_FILES["photography_attachment"]["name"]; // The file name
$fileTmpLoc = $_FILES["photography_attachment"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["photography_attachment"]["type"]; // The type of file it is
$fileSize = $_FILES["photography_attachment"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["photography_attachment"]["error"]; // 0 = false | 1 = true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
if (!$fileTmpLoc) { // if file not chosen
$error = $error."<p>Please browse for a file before clicking the upload button.</p>";
} else if($fileSize > 10485760) { // if file size is larger than 2 Megabytes
$error = $error."<p><span>Your file was larger than</span> 10 <span>Megabytes in size</span>.</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if (!preg_match("/.(gif|jpg|png|jpeg)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
$error = $error."<p>Your file was not .gif, .jpg, .png</p>";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
$error = $error."<p>An error occured while processing the file. Try again.</p>";
}
}else{ $error = "Please try again !!!"; }
}else{ $error = "Attachment field cannot be blank!"; }
Always goto "Please try again !!!" else while uploading image in windows, but it worked well in linux system.
Can you please any one help me for this issue?
On windows platforms you musst replace inside the file path the "\" with an "/"
Like this:
$file = str_replace ("\\", "/", $_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}
Or use the php build in method, for all systems:
$file = realpath($_FILES['photography_attachment']['tmp_name']);
if(is_uploaded_file($file)) {
[...]
}

php upload pdf, doc, docx

I am try to upload files to my server the allowed extension should be pdf, doc, docx
this is my code.
$uploadCv = $_FILES['uploadCv']['name'];
$target = "includes/employeeCv/";
$target = $target . basename($_FILES['uploadCv']['name']);
if ($_FILES['uploadCv']['size'] == 0) {
$error['uploadCvErr'] = "<span class='notAllowed'>Please upload your c.v</span>";
} elseif
(
$_FILES['uploadCv']['type'] != 'application/pdf'
&& $_FILES['uploadCv']['type'] != 'application/msword'
&& $_FILES['uploadCv']['type'] != 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
) {
$error['uploadCvErr'] = 'Unsupported file type uploaded.';
} elseif ($_FILES['uploadCv']['size'] > 5000000) {
$error['uploadCvErr'] = 'File uploaded exceeds maximum upload size.';
}
everything is going OK with PDF and doc but on docx it says Unsupported file type uploaded.
what I am doing wrong here.
Edit
I added this to my check files
&& $_FILES['uploadCv']['type'] != 'application/zip'
still not working.
OfficeOpenXML .docx files often have the application/zip mime type because they are a zipped collection of XML files, and browsers are too lazy to check beyond the zip signature when setting mime type

move_uploaded_file error 6 php

Attempting to move an uploaded file so that it is saved in the directory, it fails. I use echo ($_FILES['company_logo'] ['error']); to get the error number. The only place I could find with error numbers for this was http://www.htmlgoodies.com/beyond/php/article.php/3472561/PHP-Tutorial-Error-Handling.htm . However, their list only goes up to 4 and I am getting the error number 6. Does anyone know what this error stands for? Here is my code:
$allowed_filetypes = array('.jpg','.jpeg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 524288; // Maximum filesize in BYTES (currently 0.5MB).
$upload_path = '../images/companies/'; // The place the files will be uploaded to (currently a 'files' directory).
if($_FILES['company_logo']['name'] != "") {
if($row['image'] != ''){
unlink("../".$row['image']);
}
$filename = $_FILES['company_logo']['name']; // Get the name of the file (including file extension).
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.
$ext = strtolower($ext);
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['company_logo']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
$ran = rand();
$filename = $ran.$ext;
if(move_uploaded_file($_FILES['company_logo']['tmp_name'],$upload_path.$filename)){ // This is where it fails
$file = $upload_path.$filename;
$result = mysql_query("UPDATE Companies SET image = 'images/companies/$filename' WHERE id = '$id';");
if($result)
$_SESSION['message'] .= "<p class='copy' style='color:red;'>Your image upload was successful.</p>"; // It worked.
else
$_SESSION['message'] .= "<p class='copy' style='color:red;'>Unable to upload image(s).</p>";
}else{
$_SESSION['message'] .= "<p class='copy' style='color:red;'>Unable to upload image(s).</p>";
echo ($_FILES['company_logo'] ['error']);
die();
}
}
As you can see, I do check for an actual file being uploaded, if the file extension is in a list of file types allowed, if the file exceeds the max file size, and whether the path is even writable. So I don't believe it is any of those things, but I'm not certain. Any help would be appreciated.
PHP manual knows 99,99% answers.
UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and
PHP 5.0.3.
Short answer: here is a list of all file upload errors which can occurs.
Your error is:
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

Restrict file upload to just jpegs with php

Please can someone help? I have the following code which uploads a file to my server and renames it to whoever the logged in user is. For example the user 'coca-cola-lover' uploads a jpeg - the script would also rename the jpeg 'coca-cola-lover.jpg'.
My problem is that I need it to limit the upload to just jpegs - and also limit the file size to 2mb.
Please help - I was trying to find a solution all night.
Thanks in advance
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
$username = $row_Recordset1['username'];
$ext = end(explode('.', $file_name));
$renamed_file_name = $username;
$new_file_name=$renamed_file_name.'.'.$ext;
//set where you want to store files
//in this example we keep file in folder upload
//$new_file_name = new upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif
$path= "../sites/images/users/".$new_file_name;
if($ufile !=none)
{
if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
{
echo "Successful<BR/>";
//$new_file_name = new file name
//$HTTP_POST_FILES['ufile']['size'] = file size
//$HTTP_POST_FILES['ufile']['type'] = type of file
echo "File Name :".$new_file_name."<BR/>";
echo "File Size :".$HTTP_POST_FILES['ufile']['size']."<BR/>";
echo "File Type :".$HTTP_POST_FILES['ufile']['type']."<BR/>";
}
else
{
echo "Error";
}
}
getimagesize tells you what format the file is in
as per bgy's comment, you should also force the file extension to be what you want:
$new_file_name=$renamed_file_name.'.'.$ext; // wrong, uses data from the client
$new_file_name=$renamed_file_name.'.jpg'; // ok, just what we want
never trust and never use filenames provided by the client.
I would recommend exif_imagetype:
<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
die(The picture is not a gif');
}
For details see here: http://php.net/manual/en/function.exif-imagetype.php
You can use any of the four to detect a mimetype of the file:
finfo_open (by default enabled as of 5.3)
getimagesize (requires enabled GD)
exif_imagetype (requires enabled Exif)
mime_content_type (deprecated as of 5.3)
You can also limit the MimeType from the FileUpload element, but since this is client-side code, it can easily be removed by malicious users (and it's also buggy across browsers):
<input type="file" name="picture" id="picture" accept="image/jpeg"/>
For further information on how to handle file uploads with PHP (including limiting file size), check the manual.
There is also a lot of very similar questions on Stack Overflow already, one being:
Check picture file type and size before file upload in php
You restrict the size via the normal mechanisms, but you'll need to use the fileinfo functions to determine the filetype after uploading.
A few advices for the current code
Use $_FILES instead of $HTTP_POST_FILES.
If you need to get file extensions use $extension = pathinfo($filename, PATHINFO_EXTENSION);.
Use is_uploaded_file and move_uploaded_file.
Don't relay on $_FILES['file']['type'] - it can be modified by user.
Indent your code.
If you want to limit file upload to the following requirements:
Filesize: max 2mb.
File type: image/jpeg
Do something like that:
$tmpName = $_FILES['file']['tmp_name'];
if (file_is_uploaded($tmpName) {
$filesize = fielsize($tmpName);
$mimeType = exif_imagetype('image.gif');
if ($filesize <= 2 * 1024 * 1024 && $mimeType == IMAGETYPE_JPEG) {
$filename = $USERNAME . '.jpg';
if (move_uploaded_file($tmpName, $filename) == false) {
// sth goes wrong
}
} else {
die('Invalid.');
}
}

Categories