I'm trying to upload multiple files and it uploads them well. But I am also checking for errors (type and size) and catch errors in an array variable. When I select, lets say, 3 images and one of them has some error (more size than allowed and/or type not allowed) and its the first image then the other two images also don't get uploaded. If the file with error is second one then only first one gets uploaded, and when error image is last one the first two get uploaded. What I'm trying to do is even if there is error in one or more images then other valid images should get uploaded no matter the order in which they are selected.
Here is my script:
function filesupload($files) // here files is $_FILES array
{
$i = 0;
$errors = array();
$maxfilesize = 1*1024*1024; // 1 MB
$num = count($files['name']);
$allowed_types = array('image/jpeg', 'image/png');
foreach($files['tmp_name'] as $key=>$tmp_name)
{
$tmpname = $files['tmp_name'][$key]; // file temp name
$fsize = $files['size'][$key]; // file size
if(!empty($files['name'][$key]))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $files['tmp_name'][$key]); // file mime type
}
//validations for file type and size
// no file selected
if(empty($files['name'][$key]))
{
$errors[] = 'Select at least one file for uploading';
}
// file type not allowed
if(in_array($ftype, $allowed_types) === false)
{
$errors[] = 'One or more files have invalid file extension';
}
// file size validation
if($fsize > $maxfilesize)
{
$errors[] = 'Size of one or more files is more than allowed';
}
// if no errors uploaded file(s)
if(empty($errors))
{
$path = 'images/';
$newfilename = time().'_'.rand(100000, 999999).'_'.$files['name'][$key];
$move = move_uploaded_file($tmpname, $path.$newfilename);
if($move)
{
$i = $i + 1;
if($i == $num)
{
$msg = 'Files uploaded';
return $msg;
}
}
}
elseif(!empty($errors))
{
return $errors;
}
}
}
In the loop you have checked $error[]. So when the error is in first file so that array will not be blank and other images will not upload.
Try as below :
function filesupload($files) // here files is $_FILES array
{
$i = 0;
$errors = array();
$maxfilesize = 1*1024*1024; // 1 MB
$num = count($files['name']);
$allowed_types = array('image/jpeg', 'image/png');
foreach($files['tmp_name'] as $key=>$tmp_name)
{
$tmpname = $files['tmp_name'][$key]; // file temp name
$fsize = $files['size'][$key]; // file size
if(!empty($files['name'][$key]))
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$ftype = finfo_file($finfo, $files['tmp_name'][$key]); // file mime type
}
//validations for file type and size
// no file selected
if(empty($files['name'][$key]))
{
$errors[$key] = 'Select at least one file for uploading';
}
// file type not allowed
if(in_array($ftype, $allowed_types) === false)
{
$errors[$key] = 'One or more files have invalid file extension';
}
// file size validation
if($fsize > $maxfilesize)
{
$errors[$key] = 'Size of one or more files is more than allowed';
}
// if no errors uploaded file(s)
if(!isset($errors[$key]))
{
$path = 'images/';
$newfilename = time().'_'.rand(100000, 999999).'_'.$files['name'][$key];
$move = move_uploaded_file($tmpname, $path.$newfilename);
if($move)
{
$i = $i + 1;
if($i == $num)
{
$msg = 'Files uploaded';
return $msg;
}
}
}
}
if(!empty($errors))
{
return $errors;
}
}
I have changed error message array from $errors[] to $errors[$key] and checked the same. So if you have 4 file input and 1st and 3rd are having error then 2nd and 4th will upload and you will get error in 0th and 2nd index of array.
Related
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
require_once("database.php");
if(#$_POST['upload']) {
$file_name = $_FILES['cvs']['name'];
$file_type = $_FILES['cvs']['type'];
$file_temp_loc = $_FILES['cvs']['tmp_name'];
$file_error_msg = $_FILES['cvs']['error'];
$file_size = $_FILES['cvs']['size'];
/* 1. file upload handling */
if(!$file_temp_loc) { // if not file selected
echo "Error: please browse for a file before clicking the upload button.";
exit();
}
if(!preg_match("/\.(csv)$/i", $file_name)) { // check file extension
echo 'Error: your file is not CSV.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
if($file_size > 5242880) { // file check size
echo "Error: you file was larger than 5 Megabytes in size.";
exit();
}
if($file_error_msg == 1) { //
echo "Error: an error occured while processing the file, try agian.";
exit();
}
$move_file = move_uploaded_file($file_temp_loc, "\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/{$file_name}"); // temp loc, file name
if($move_file != true) { // if not move to the temp location
echo 'Error: File not uploaded, try again.';
#unlink($file_temp_loc); // remove to the temp folder
exit();
}
$csvFile = '\\Reformist003-pc/c/xampp/htdocs/FARMAPP/Farmer/'.$file_name;
$csvFileLength = filesize($csvFile);
$csvSeparator = ",";
$handle = fopen($csvFile, 'r');
$count = '';
while($data = fgetcsv($handle, $csvFileLength, $csvSeparator)) { // while for each row
$count += count($data[0]); // count imported
mysql_query("INSERT INTO `csv_data` (`product_title`, `product_price`) VALUES ( '$data[0]', '$data[1]' )");
}
fclose($handle);
unlink($csvFile); // delete cvs after imported
header('Location: index.php?success=1&count='.$count);
exit();
}
?>
please check the spelling of file field's name .. it must be csv in html and you called it cvs
$file_name = $_FILES['csv']['name'];
$file_type = $_FILES['csv']['type'];
$file_temp_loc = $_FILES['csv']['tmp_name'];
$file_error_msg = $_FILES['csv']['error'];
$file_size = $_FILES['csv']['size'];
I have an upload script which uploads files to hosting and the redirects to success urlcode of upload script is as below. I want to get value from this to success url.
<?php
// Folder to upload files to. Must end with slash /
define('DESTINATION_FOLDER',$_SERVER['DOCUMENT_ROOT'].'/upload/');
// Maximum allowed file size, Kb
// Set to zero to allow any size
define('MAX_FILE_SIZE', 0);
// Upload success URL. User will be redirected to this page after upload.
define('SUCCESS_URL','http://sap.layyah.info/result.php');
// Allowed file extensions. Will only allow these extensions if not empty.
// Example: $exts = array('avi','mov','doc');
$exts = array();
// rename file after upload? false - leave original, true - rename to some unique filename
define('RENAME_FILE', false);
// put a string to append to the uploaded file name (after extension);
// this will reduce the risk of being hacked by uploading potentially unsafe files;
// sample strings: aaa, my, etc.
define('APPEND_STRING', '');
####################################################################
END OF SETTINGS. DO NOT CHANGE BELOW
####################################################################
// Allow script to work long enough to upload big files (in seconds, 2 days by default)
#set_time_limit(172800);
// following may need to be uncommented in case of problems
// ini_set("session.gc_maxlifetime","10800");
function showUploadForm($message='') {
$max_file_size_tag = '';
if (MAX_FILE_SIZE > 0) {
// convert to bytes
$max_file_size_tag = "<input name='MAX_FILE_SIZE' value='".(MAX_FILE_SIZE*1024)."' type='hidden' >\n";
}
// Load form template
include ('file-upload.html');
}
// errors list
$errors = array();
$message = '';
// we should not exceed php.ini max file size
$ini_maxsize = ini_get('upload_max_filesize');
if (!is_numeric($ini_maxsize)) {
if (strpos($ini_maxsize, 'M') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024;
elseif (strpos($ini_maxsize, 'K') !== false)
$ini_maxsize = intval($ini_maxsize)*1024;
elseif (strpos($ini_maxsize, 'G') !== false)
$ini_maxsize = intval($ini_maxsize)*1024*1024*1024;
}
if ($ini_maxsize < MAX_FILE_SIZE*1024) {
$errors[] = "Alert! Maximum upload file size in php.ini (upload_max_filesize) is less than script's MAX_FILE_SIZE";
}
// show upload form
if (!isset($_POST['submit'])) {
showUploadForm(join('',$errors));
}
// process file upload
else {
while(true) {
// make sure destination folder exists
if (!#file_exists(DESTINATION_FOLDER)) {
$errors[] = "Destination folder does not exist or no permissions to see it.";
break;
}
// check for upload errors
$error_code = $_FILES['filename']['error'];
if ($error_code != UPLOAD_ERR_OK) {
switch($error_code) {
case UPLOAD_ERR_INI_SIZE:
// uploaded file exceeds the upload_max_filesize directive in php.ini
$errors[] = "File is too big (1).";
break;
case UPLOAD_ERR_FORM_SIZE:
// uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
$errors[] = "File is too big (2).";
break;
case UPLOAD_ERR_PARTIAL:
// uploaded file was only partially uploaded.
$errors[] = "Could not upload file (1).";
break;
case UPLOAD_ERR_NO_FILE:
// No file was uploaded
$errors[] = "Could not upload file (2).";
break;
case UPLOAD_ERR_NO_TMP_DIR:
// Missing a temporary folder
$errors[] = "Could not upload file (3).";
break;
case UPLOAD_ERR_CANT_WRITE:
// Failed to write file to disk
$errors[] = "Could not upload file (4).";
break;
case 8:
// File upload stopped by extension
$errors[] = "Could not upload file (5).";
break;
} // switch
// leave the while loop
break;
}
// get file name (not including path)
$filename = #basename($_FILES['filename']['name']);
// filename of temp uploaded file
$tmp_filename = $_FILES['filename']['tmp_name'];
$file_ext = #strtolower(#strrchr($filename,"."));
if (#strpos($file_ext,'.') === false) { // no dot? strange
$errors[] = "Suspicious file name or could not determine file extension.";
break;
}
$file_ext = #substr($file_ext, 1); // remove dot
// check file type if needed
if (count($exts)) { /// some day maybe check also $_FILES['user_file']['type']
if (!#in_array($file_ext, $exts)) {
$errors[] = "Files of this type are not allowed for upload.";
break;
}
}
// destination filename, rename if set to
$dest_filename = $filename;
if (RENAME_FILE) {
$dest_filename = md5(uniqid(rand(), true)) . '.' . $file_ext;
}
// append predefined string for safety
$dest_filename = $dest_filename . APPEND_STRING;
// get size
$filesize = intval($_FILES["filename"]["size"]); // filesize($tmp_filename);
// make sure file size is ok
if (MAX_FILE_SIZE > 0 && MAX_FILE_SIZE*1024 < $filesize) {
$errors[] = "File is too big (3).";
break;
}
if (!#move_uploaded_file($tmp_filename , DESTINATION_FOLDER . $dest_filename)) {
$errors[] = "Could not upload file (6).";
break;
}
// redirect to upload success url
header('Location: ' . SUCCESS_URL);
die();
break;
} // while(true)
// Errors. Show upload form.
$message = join('',$errors);
showUploadForm($message);
}
?>
I want to show $dest_filename on SUCCESS_URL I have tried include and echo but it is not working
In Success URL I am Using:
<?php
if(isset($_GET['uploaded_file_url'])){
$var_1 = $_GET['uploaded_file_url'];
echo $var_1;
}
echo 'Click here for uploaded file!;
Is this what you're after??
// redirect to upload success url
header('Location: '.SUCCESS_URL."?uploaded_file_url=".DESTINATION_FOLDER."/".$dest_filename);
die();
In your successful url script put this at the top of your page:
if(isset($_GET['uploaded_file_url'])){
$var_1 = $_GET['uploaded_file_url'];
echo $var_1;
}
If you want a hyperlink to the url of that file (for download etc), then just wrap a tags around it like so:
echo 'Click here for uploaded file!;
Try to use POST and GET to pass the string on the URL.
the following piece of code recognizes the image through getimagesize() but then when i try to move the file to an uploaded folder it moves the file there but says it's an array? im confused because im not setting any variables as an array?
<?php
//simple image check using getimagesize() instead of extensions
if($_FILES){
$empty_check = getimagesize($_FILES['file']['tmp_name']);
if(empty($empty_check)){
echo 'this is not an image';
}
else{
echo 'you have uploaded ' . explode('.',$_FILES['file']['name'])[0].'
and it is a ' . explode('.',$_FILES['file']['name'])[1].'.';
//an example of how i would extract the extension
$target = "C:\\xampp\\htdocs";
move_uploaded_file($_FILES['file']['tmp_name'], $target.'\\'.$_FILES['file']);
}
}
?>
$_FILES['file']
is an array, you're trying to use it as the target filename;
comment of deceze.
Echo the file you want to move/save, then you should see what he mentioned..
When using move_uploaded_file you get to pick the filename, so you can pick anything you want.
When you upload the file, its put into a temporary directory with a temporary name, move_uploaded_file() allows you to move that file and in that you need to set the name of the file as well.
Use this coding for multiple file uploading....
//For Multiple file uploading
if (isset($_FILES['photo']) != "") {
$errors = array();
foreach($_FILES['photo']['tmp_name'] as $key = > $tmp_name) {
$file_name = $_FILES['photo']['name'][$key];
$file_size = $_FILES['photo']['size'][$key];
$file_tmp = $_FILES['photo']['tmp_name'][$key];
$file_type = $_FILES['photo']['type'][$key];
//change the image extension as png
$fileExt = "png";
$photorename[$key] = strtolower($property_code.
'_'.$key.
'.'.$fileExt);
if ($file_size > 2097152) {
$errors[] = 'File size must be less than 2 MB';
}
//Path of Uploading file
$target = "images_property";
if (empty($errors) == true) {
if (is_dir($target) == false) {
mkdir("$target", 0700); // Create directory if it does not exist
}
if (file_exists("$target/".$photorename[$key])) {
unlink("$target/".$photorename[$key]);
}
move_uploaded_file($file_tmp, "$target/".$photorename[$key]);
} else {
print_r($errors);
}
}
if (empty($errors)) {
echo "Success";
}
}
I wrote the following php function to upload files but I'm having a hard time with the array of allowed file types. If I assign just one file type i.e. image/png, it works fine. If I assign more than one, its not working. I use the in_array() function to determine the allowed file types but I can't figure out how to use it properly.
Thank you!
function mcSingleFileUpload($mcUpFileName, $mcAllowedFileTypes, $mcFileSizeMax){
if(!empty($mcUpFileName)){
$mcIsValidUpload = true;
// upload directory
$mcUploadDir = UPLOAD_DIRECTORY;
// current file properties
$mcFileName = $_FILES[$mcUpFileName]['name'];
$mcFileType = $_FILES[$mcUpFileName]['type'];
$mcFileSize = $_FILES[$mcUpFileName]['size'];
$mcTempFileName = $_FILES[$mcUpFileName]['tmp_name'];
$mcFileError = $_FILES[$mcUpFileName]['error'];
// file size limit
$mcFileSizeLimit = $mcFileSizeMax;
// convert bytes to kilobytes
$mcBytesInKb = 1024;
$mcFileSizeKb = round($mcFileSize / $mcBytesInKb, 2);
// create array for allowed file types
$mcAllowedFTypes = array($mcAllowedFileTypes);
// create unique file name
$mcUniqueFileName = date('m-d-Y').'-'.time().'-'.$mcFileName;
// if file error
if($mcFileError > 0)
{
$mcIsValidUpload = false;
mcResponseMessage(true, 'File error!');
}
// if no file error
if($mcFileError == 0)
{
// check file type
if( !in_array($mcFileType, $mcAllowedFTypes) ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'Invalid file type!');
}
// check file size
if( $mcFileSize > $mcFileSizeLimit ){
$mcIsValidUpload = false;
mcResponseMessage(true, 'File exceeds maximum limit of '.$mcFileSizeKb.'kB');
}
// move uploaded file to assigned directory
if($mcIsValidUpload == true){
if(move_uploaded_file($mcTempFileName, $mcUploadDir.$mcUniqueFileName)){
mcResponseMessage(false, 'File uploaded successfully!');
}
else{
mcResponseMessage(true, 'File could not be uploaded!');
}
}
}
}
}
//mcRequiredFile('mcFileUpSingle','please select a file to upload!');
mcSingleFileUpload('mcFileUpSingle', 'image/png,image/jpg', 2097152);
Change this line:
$mcAllowedFTypes = array($mcAllowedFileTypes);
To this:
$mcAllowedFTypes = explode(',',$mcAllowedFileTypes);
Don't rely on the clent file type from $_FILES which is unsafe, get it from the file content.
Then define your allowed file types, check if the upload file type in your white list.
if(in_array(mime_type($file_path),$allowed_mime_types)){
// save the file
}
$allowed_mime_types = array(
'image/jpeg',
'image/jpg',
'image/png',
'image/gif',
'video/mp4'
);
/*
For PHP>=5.3.0, you can use php's `finfo_file`([finfo_file](https://www.php.net/manual/en/function.finfo-file.php)) function to get the file infomation about the file.
For PHP<5.3.0, you can use your's system's `file` command to get the file information.
*/
function mime_type($file_path)
{
if (function_exists('finfo_open')) {
$finfo = new finfo(FILEINFO_MIME_TYPE, null);
$mime_type = $finfo->file($file_path);
}
if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {
ob_start();
passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);
if ($return > 0) {
ob_end_clean();
$mime_type = null;
}
$type = trim(ob_get_clean());
if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
$mime_type = null;
}
$mime_type = $match[1];
}
return $mime_type;
}