Uploading files sequentially - php

I want to upload files sequentially. When I do so, the files I uploaded the last will get to the file system whereas my php code will not see the files I uploaded earlier. Anyone had a similar problem?
function inputImages()
{
print_r($_FILES);
$images_number = count($_FILES['images']['name']);
$uploadDir = 'tmp_name/';
$images = array();
for ($i=0; $i<$images_number; $i++) {
$fileName = $_FILES['images']['name'][$i];
$tmpName = $_FILES['images']['tmp_name'][$i];
$permanentname = sha1($tmpName.$fileName.rand()).substr($fileName,-4);
$filePath = $uploadDir . $permanentname;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
$ErrorMessage.= "Error uploading <strong>file</strong>";
} else {
array_push($images, $permanentname);
}
}
return $images;
}

Related

Get image width while uploading image PHP

in my code, while a user is uploading a pic, in my php code i want to read the width of the image while its getting uploaded, below is my code --
<?php
require_once('config.php');
$file_path = $_SERVER['DOCUMENT_ROOT']."AndroidApp/VideoUploads/Thumbnails/";
$emailid=$_GET['emailid'];
$randNum=$_GET['randNum'];
$ext = findexts ($_FILES['uploaded_file']['name']) ;
$thumb_url="DoUpNow_Funny_Video_Thumb"."_".$randNum.".".$ext;
$file_path = $file_path.$thumb_url;
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
list($width) = getimagesize($_FILES['uploaded_file']['tmp_name']);
$stmt2 = $linkID1->prepare("update VideoUploads set video_thumb=?, width=? where emailid=? and randNum=?");
$stmt2->bind_param("ssss", $thumb_url,$width,$emailid,$randNum);
$stmt2->execute();
$stmt2->close();
echo "success";
} else{
echo "fail";
}
function findexts ($filename)
{
$filename = strtolower($filename) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
?>
The file is getting uploaded, but there is no value in the width variable, is anything wrong, or my approach is wrong.
After move_uploaded_file(), the tmp_name variable refers to a file which no longer exists, it was moved.
If the file is valid, it will be moved to the filename given by destination.
So, use $file_path to get your file informations :
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
list($width) = getimagesize($file_path);
try this code it's working fine
check this and let me
<?php
$image_info = getimagesize($_FILES["uploaded_file"]["tmp_name"]);
$image_width = $image_info[0];
$image_height = $image_info[1];
?>

How to increment unique filename based on directory array

I'm creating an upload form that when uploading files will check to see if a file with the same name already exists in the directory. If a file with the same name is found, the script should increment the file by appending the file name with a number such as test1.txt test2.txt and so on until a match is not found. This is what I have come up with so far but wanted to see if there is a different approach I should take.
Also note, my filenames are already cleaned before they enter this part of the script so my filename and extension functions are simplified.
function filename($file){
return substr($file,0,strrpos($file,'.'));
}
function extension($file){
return strtolower(substr(strrchr($file,'.'),1));
}
$new_file = 'test.txt';
$dir = 'files';
$files = scandir($dir);
$exclude = array('.','..');
foreach($files as $file){
if(!in_array($file,$exclude)){
$file_array[] = $file;
}
}
$i = 1;
while(in_array($new_file,$file_array)){
$filename = filename($new_file);
$extension = extension($new_file);
if($i>1){
$num = strlen($filename);
$filename = substr($filename,0,-1);
$new_file = $filename.$i.'.'.$extension;
} else {
$new_file = $filename.$i.'.'.$extension;
}
echo $new_file.'<br>';
echo $i.'<br>';
$i++;
}
echo $new_file;

All images not uploading in multiple images upload

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.

Saving Multiple File path to mysql using PHP

Good Day. I have a php script that move multiple file in my directory..
$filepath = 'uploads/';
if (isset($_FILES['file'])) {
$file_id = $_POST['file_id'];
$count = 0;
foreach($_FILES['file']['tmp_name'] as $k => $tmp_name){
$name = $_FILES['file']['name'][$k];
$size = $_FILES['file']['size'][$k];
if (strlen($name)) {
$extension = substr($name, strrpos($name, '.')+1);
if (in_array(strtolower($extension), $file_formats)) { // check it if it's a valid format or not
if ($size < (2048 * 1024)) { // check it if it's bigger than 2 mb or no
$filename = uniqid()."-00000-". $name;=
$tmp = $_FILES['file']['tmp_name'][$k];
if (move_uploaded_file($tmp_name, $filepath . $filename)) {
$id = $file_id;
$file_path_array = array();
$files_path = $filepath . $filename;
$file_extension = $extension;
foreach($file_name as $k_file_path => $v_file_path){
$file_path_array[] = $v_file_path;
}
foreach($file_extension as $k_file_extension){
$file_extension_array[] = $v_file_extension;
}
$file_path = json_encode($files_path);
$file_name = str_replace("\/", "/",$file_path);
var_dump($file_name);
$update = $mysqli->query("UPDATE detail SET file_path='$file_name' WHERE id='$id'");
} else {
echo "Could not move the file.";
}
} else {
echo "Your file is more than 2MB.";
}
} else {
echo "Invalid file format PLEASE CHECK YOU FILE EXTENSION.";
}
} else {
echo "Please select FILE";
}
}
exit();
}
this is my php script that move file to 'uploads/' directory and i want to save the path to my database. i try to dump the $file_name and this is my example path how to save that to my database.. ? any suggestions ?
NOTE: i already move the file to uploads/ directory and i only want to save the path to my database
string(46) "uploads/5638067602b48-00000-samplePDF.pdf"
string(46) "uploads/5638067602dee-00000-samplePDF1.pdf"
string(46) "uploads/5638067602f8d-00000-samplePDF2.pdf"
if you must store them in one field..
inside the loop
$file_name_for_db[]=$file_name;
outside the loop:
$update = $mysqli->query("UPDATE detail SET file_path='".json_encode($file_name_for_db)."' WHERE id='$id'");
there is serialize() instead of json_encode() if you prefer

Notice: Undefined index: cvs in C:\xampp\htdocs\FARMAPP\Farmer\import.php on line

<?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'];

Categories