PHP upload multiple files with random name - php

I got problem to set file name when uploading the image using multiple input file.
<span class="btn btn-default btn-file">
Browse <input type="file" name="image[]" id="image" class="image" onchange="preview_image();" multiple/>
</span>
And here is the PHP:
$total = count($_FILES['image']['name']);
for($i=0; $i<$total; $i++)
{
$tmpFilePath = $_FILES['image']['tmp_name'][$i];
if($tmpFilePath != "")
{
$info1 = pathinfo($_FILES['image']['name'][$i]);
$ext = $info1['extension'];
$newname1 = "CALIBRATION_.".$ext;
$newFilePath = "../assets/img/product/" . $newname1[$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)){}
}
}
When I try to run the code, it show me wrong name & type. You can see below screenshot.
What I want is to rename the file after uploaded with correct name and file type.

You access $newname1 as an array, this is not what you want. Plus, you are missing the random of your name.
try doing
$total = count($_FILES['image']['name']);
for($i=0; $i<$total; $i++)
{
$tmpFilePath = $_FILES['image']['tmp_name'][$i];
if($tmpFilePath != "")
{
$info1 = pathinfo($_FILES['image']['name'][$i]);
$ext = $info1['extension'];
$newname1 = "CALIBRATION_" . rand(10000,99999) . "." . $ext;
$newFilePath = "../assets/img/product/" . $newname1;
if(move_uploaded_file($tmpFilePath, $newFilePath)){}
}
}

Remove [$i] from this line $newname1[$i]. this will create an array of string so the name of the file will be a single character. add rand() or put any unique number to get unique name for the file
$newname1 = "CALIBRATION_".rand(1000, 9999).".".$ext;
$newFilePath = "../assets/img/product/" . $newname1;

$newname1 is string not an array. If you want to concat $i value with new name you can do it like following code
if($tmpFilePath != "")
{
$info1 = pathinfo($_FILES['image']['name'][$i]);
$ext = $info1['extension'];
$newname1 = "CALIBRATION_".$i.".".$ext;
$newFilePath = "../assets/img/product/" . $newname1;
if(move_uploaded_file($tmpFilePath, $newFilePath)){}
}

You need to remove [$i] from this line to get full name and not only the $ith character of file name:
$newFilePath = "../assets/img/product/" . $newname1[$i];
If you want to generate new file name with original name and extension but prefixed with CALIBRATION_. and not a random number, you can use two versions:
$newname1 = "CALIBRATION_" . $info1['basename'];
// or
$newname1 = "CALIBRATION_" . $info1['filename'] . '.' . $info1['extension'];
You don't need to create a variable if you only use it once, as $ext in your code. Here you can use $info1, containing dirname, basename, filename and extension

Related

Integer in while loop wont increase value

I'm having a problem in my code, I am trying to append a number to a filename if filename already exists. It goes something like this
$explode = explode(".", $fileName);
$extension = end($explode);
$fileactualname = reset($explode);
$i = 0;
while (file_exists($location.$fileName)) {
$i++;
}
$fileName= $i.$fileName;
$name = $fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $location . "/". $name);
if ($moveResult != true) {
#unlink($fileTmpLoc);
header('location: ' . URL . '?page=0&sort=name&type=desc&folder=uploads/&message=uploaderror');
}
Unfortunately for some reason $i wont increase its value by 1 every time it loops, instead it adds to the filename this way 1234filename.jpg my file name variable is after the loop and i cant understand why this is accruing. I am expecting to get ($i)filename.jpg a single number
AFTER RESTARTING MY LOCALSERVER IT STARTED WORKING WITH THE CODE PROVIDED BELOW DUUUH
You need to use the actual filename when you concat the number to it and not the one you already added a number to.
// not sure why you are splitting the filname up here
$explode = explode(".", $fileName);
$extension = end($explode);
$fileactualname = reset($explode);
$i = 0;
$fn = $fileName;
while (file_exists($location.$fn)) {
$i++;
// add number to actual filename
$fn = $i.$fileName;
}
$name = $fn;
$moveResult = move_uploaded_file($fileTmpLoc, $location . "/". $name);

Changing file names on upload

I currently have a form with 2x name=userfile[] attributes in the inputs that is handled within the code below. What would be the best way to enable me to rename the filenames foreach file on upload - I want them to be specific to the input
What I am after:
$imageOneName = img1.$var;
$imageTwoName = img2.$var;
Code:
for($i=0; $i<count($_FILES['userfile']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['userfile']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = $local_path .'images/' . $_FILES['userfile']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
Instead of
<input type="file" name="userfile[]" id="input1">
<input type="file" name="userfile[]" id="input2">
You can do the following to distinguish between the two
<input type="file" name="userfile[desiredNameOfFile1]" id="input1">
<input type="file" name="userfile[desiredNameOfFile2]" id="input2">
With PHP handling it like this:
foreach($_FILES['userFile']['name'] AS $desiredNameOfFile => $fileInfo) {
//Get the temp file path
$tmpFilePath = $_FILES['userfile']['tmp_name'][$desiredNameOfFile];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = $local_path .'images/' . $desiredNameOfFile . pathInfo($_FILES['userfile']['tmp_name'][$desiredNameOfFile],PATHINFO_EXTENSION);
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
Be aware: this code will overwrite files that already have that name
Edit
If you want multiple file selects
<input type="file" name="userfile[desiredNameOfFile1][]" id="input1" multiple>
<input type="file" name="userfile[desiredNameOfFile2][]" id="input2" multiple>
Php
foreach($_FILES['userfile']['name'] AS $desiredNameOfFile => $fileInfo) {
for($i = 0; $i < count($fileInfo); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['userfile']['tmp_name'][$desiredNameOfFile][$i];
// Make sure we have a filepath
if ($tmpFilePath != ""){
// Setup our new file path
$newFilePath = $local_path .'images/' . $desiredNameOfFile . $i . pathInfo($_FILES['userfile']['tmp_name'][$desiredNameOfFile][$i],PATHINFO_EXTENSION);
// Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
// Handle other code here
}
}
}
}
}
try this code :-
$extension = pathinfo($_FILES['userfile']['name'][$i], PATHINFO_EXTENSION); //Get extension of image
$new= rand(0000,9999); //creat random name
$file_name=$new.'.'.$extension; //create file name with extension
$newFilePath = $local_path .'images/' . $file_name;
With below code generate unique file name for each file.
$file_name = preg_replace('/\s+/', '', $_FILES['userfile']['name'][$i]); /// remove unexpected symbols , number
$path[$i]="image/".time().$i.$file_name; /// generate unique name
move_uploaded_file($file_tmp[$i],$path[$i]); /// move that file on your path folder

Trouble inserting two array values into database

Here is the code I am using for multiple image upload for every entry in the database; id, image, name, date. By using this code, the image name is inserting correctly but I have a problem with the name field. I want to insert the name using $product_name= $_POST['pro_name']; but it only inserts 'array' in name field.
<?php
include('../config.php');
if (isset($_POST['submit'])) {
$product_name = $_POST['pro_name'];
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']) && $product_name < count($product_name); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$finel_name = explode('/', $target_path);
$image_name_final = $finel_name[1];
$jajsj = "insert into spec_product set image='$image_name_final', name='$product_name'";
$janson = mysql_query($jajsj) or die(mysql_error());
// If file moved to uploads folder.
echo $j . ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j . ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j . ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
The value is inserting as array because the variable $product_name is not a string but an array. Whenever an array is used where a string was expected e.g.: concatenation of a string or in your case the query statment: insert into spec_product set image='$image_name_final', name='$product_name'"; PHP will automatically convert the array into its default string value "Array".
Make sure that $product_name is not an array but a string which contains name of the product you want to insert in the table.
Regards,
Nitin Thakur
replace in your code
for ($i = 0; $i < count($_FILES['file']['name']); $i++)
{
and add this before your query execute
$product_name_final= $product_name[$i];

how to add number in picture when upload if same file name of picture

I have this code for upload
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photo/" . $_FILES["image"]["name"]);
$location="photo/" . $_FILES["image"]["name"];
then the insert $location code for sql to add
The Question is how to have my picture file name number add ex: if i have "Picture.jpg "uploaded if i will upload again and same file name the output of the filename will be Picture(1).jpg and if I upload again with the same file name the output filename will be Picture(2).jpg and so on I want the "()" to increment if ever i will upload same file name. thanks in advance ^^
This can be achived with loop:
$info = pathinfo($_FILES['image']['name']);
$i = 0;
do {
$image_name = $info['filename'] . ($i ? "_($i)" : "") . "." . $info['extension'];
$i++;
$path = "photo/" . $image_name;
} while(file_exists($path));
move_uploaded_file($_FILES['image']['tmp_name'], $path);
You should also sanitize input file name:
string sanitizer for filename
Sanitizing strings to make them URL and filename safe?
If you want to have a unique image name after upload even if they have same name or they are uploading in loop means multiple upload.
$time = time() + sprintf("%06d",(microtime(true) - floor(microtime(true))) * 1000000);
$new_name=$image_name.'_'.$time.'.'.$extension
You can add the image name with a unique time stamp which differ each nano seconds and generate unique time stamp
This code is untested, but I would think something along the lines of:
if (file_exists('path/to/file/image.jpg')){
$i = 1;
while (file_exists('path/to/file/image ('.$i.').jpg')){
$i++;
}
$name = 'image ('.$i.');
}
And then save the image to $name. (which at some point will result in image (2).jpg)
try this
$path = "photo/" . $_FILES["image"]["name"];
$ext = pathinfo ($path, PATHINFO_EXTENSION );
$name = pathinfo ( $path, PATHINFO_FILENAME ] );
for($i = 0; file_exists($path); $i++){
if($i > 0){
$path = "photo/" .$name.'('.$id.').'.$ext;
}
}
echo $path;
Can you try this,
$name = $_FILES['image']['name'];
$pathinfo = pathinfo($name);
$FileName = $pathinfo['filename'];
$ext = $pathinfo['extension'];
$actual_image_name = $FileName.time().".".$ext;
$location="photo/".$converted_name;
if(move_uploaded_file($tmp, $location))
{
}

How to change name of uploaded file without changing extension

i'd like to change the name of uploaded file to md5(file_name).ext, where ext is extension of uploaded file. Is there any function which can help me to do it?
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}"))
{
// other code
}
Use this function to change the file name to md5 with the same extension
function convert_filename_to_md5($filename) {
$filename_parts = explode('.',$filename);
$count = count($filename_parts);
if($count> 1) {
$ext = $filename_parts[$count-1];
unset($filename_parts[$count-1]);
$filename_to_md5 = implode('.',$filename_parts);
$newName = md5($filename_to_md5). '.' . $ext ;
} else {
$newName = md5($filename);
}
return $newName;
}
<?php
$filename = $_FILES['file']['name'];
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = rand(0000,9999);
$newfilename=$new.$filename.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'],$newfilename))
{
//advanced code
}
?>
Find below php code to get file extension and change file name
<?php
if(isset($_FILES['upload_Image']['name']) && $_FILES['upload_Image']['name']!=='') {
$ext = substr($_FILES['upload_Image']['name'], strpos($_FILES['upload_Image']['name'],'.'), strlen($_FILES['upload_Image']['name'])-1);
$imageName = time().$ext;
$normalDestination = "Photos/Orignal/" . $imageName;
move_uploaded_file($_FILES['upload_Image']['tmp_name'], $normalDestination);
}
?>
This one work
<?php
// Your file name you are uploading
$file_name = $HTTP_POST_FILES['ufile']['name'];
// random 4 digit to add to our file name
// some people use date and time in stead of random digit
$random_digit=rand(0000,9999);
//combine random digit to you file name to create new file name
//use dot (.) to combile these two variables
$new_file_name=$random_digit.$file_name;
//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= "upload/".$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";
}
}
?>

Categories