How to upload same file name with auto increment in PHP? - php

I got a task where I need to upload the same file name with numbers. For example if I upload file1 with the title "cv.pdf" then second file should be named as "cv.pdf(1)",the next one should be "cv.pdf(2)" and so on.
I have tried many ways but still not working out. Can some please help me out to meet the desired objective. This is my
upload.php
<?php
$json = array();
if(!empty($_FILES['upl_file'])){
$dir = "./uploads/";
$allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'pdf', 'doc', 'docx');
$fileName = basename($_FILES['upl_file']['name']);
$filePath = $dir.$fileName;
$actual_name = pathinfo($filePath,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($filePath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("./uploads/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
if(in_array($extension, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath)){
$json = 'success';
} else {
$json = 'failed';
}
}
}
header('Content-Type: application/json');
echo json_encode($json);
?>

I think glob function is your savior here.
Istead of:
$i = 1;
while(file_exists("./uploads/".$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
You should use:
$count = count(glob("./uploads/".$actual_name."*.".$extension));
//Check the * after the name
//EDIT: Before add the count, check if its not zero(0)
$actual_name = "{$name}".( $count > 0 ? "({$count})" : "").".{$extension}";
And last, but not least, you should change the final name of the file:
if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $filePath))
//filePath has the old name
if(move_uploaded_file($_FILES['upl_file']['tmp_name'], $dir.$actual_name))
//newPath with count in the name

Related

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;

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

PHP assign each multiple uploaded files to variable

How can I separate multiple uploaded files ($new_file_name) out of foreach loop for sql query process? How to assign each files to its variable?
// manipulate uploaded images
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $key.'_'.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
//explode fine name and extension
$ext_x = explode('.', $_FILES['files']['name'][$key]);
$ext = strtolower(end($ext_x));
$file_name = str_replace('.'.$ext, '', $_FILES['files']['name'][$key]);
//new file name
$output_dir = '../items/'.$list_id;
$new_file_name = rand(1, 999999).'.'.$ext;
$pathfile = $output_dir.'/'.$new_file_name;
// create directory if does not exist
if(is_dir($output_dir) == false){
mkdir($output_dir, 0700);
}
if(is_dir($pathfile) == false){
if(move_uploaded_file($file_tmp, $pathfile)){
//resize original image
WideImage::load($pathfile)->resize(300, 400)->saveToFile($pathfile);
//generate thumbnail
$split = explode('.', $new_file_name);
$thumb = $split[0].'_t.'.$split[1];
WideImage::load($pathfile)->resize(70, 70)->saveToFile($output_dir.'/'.$thumb);
}
}
}
}
//here I needed to get each of the uploaded images to update database (max 3 images)
//how to explode above $new_file_name into variable here?
$new_file_name1 = $new_file_name[0]; //and so on...
$q = $mysqli->query("UPDATE `listing` SET image1='".$new_file_name1."', image2='".$new_file_name2."', image3='".$new_file_name3."', thumbnail='".$thumb1."', WHERE list_id='".$list_id."' AND user_id='".$user_id."'") or die($mysqli->error);
I can get each of the file by
$var0 = $_FILES['files']['name'][0];
$var1 = $_FILES['files']['name'][1];
$var2 = $_FILES['files']['name'][2];
but I can't
$var0 = $new_file_name[0];
$var1 = $new_file_name[1];
$var2 = $new_file_name[2];
Thanks for advise!
Use this to set the name:
$new_file_name[] = rand(1, 999999).'.'.$ext;
and inside the for loop use:
end($new_file_name)
for the current file. E.g:
$pathfile = $output_dir.'/'.end($new_file_name);
The problem you are having is because in every iteration through the loop you setup the $new_file_name to a new random string. By using $new_file_name[] you are adding an element to $new_file_name which is then becoming an array. Using the end() functions returns the last element of the array so in the current iteration of the loop it will return the last added random string which corresponds to your current file;
EDIT:
// manipulate uploaded images
if(isset($_FILES['files'])){
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name){
$file_name = $key.'_'.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
//explode fine name and extension
$ext_x = explode('.', $_FILES['files']['name'][$key]);
$ext = strtolower(end($ext_x));
$file_name = str_replace('.'.$ext, '', $_FILES['files']['name'][$key]);
//new file name
$output_dir = '../items/'.$list_id;
$new_file_name[] = rand(1, 999999).'.'.$ext;
$pathfile = $output_dir.'/'.end($new_file_name);
// create directory if does not exist
if(is_dir($output_dir) == false){
mkdir($output_dir, 0700);
}
if(is_dir($pathfile) == false){
if(move_uploaded_file($file_tmp, $pathfile)){
//resize original image
WideImage::load($pathfile)->resize(300, 400)->saveToFile($pathfile);
//generate thumbnail
$split = explode('.', end($new_file_name));
$thumb = $split[0].'_t.'.$split[1];
WideImage::load($pathfile)->resize(70, 70)->saveToFile($output_dir.'/'.$thumb);
}
}
}
}
//Getting the variables
$new_file_name1 = $new_file_name[0]; //and so on...
$q = $mysqli->query("UPDATE `listing` SET image1='".$new_file_name1."', image2='".$new_file_name2."', image3='".$new_file_name3."', thumbnail='".$thumb1."', WHERE list_id='".$list_id."' AND user_id='".$user_id."'") or die($mysqli->error);
You could also use: $new_file_name[0] inside the SQL query.

Upload image according to name in PHP

Suppose there are 2 same images in different names. I want to upload these images & put them in different folder. Suppose, img1.jpg & a-img1.jpg are the images. Now img1.jpg will go on "files/images/" location & a-img1.jpg will go on "files/a-images/" location. I've successfully manage to upload images but it'll only go to one destination folder. This is my code,
$upload_errors = 0;
$images= $_FILES['img'];
$img_id = get_new_image_id();
$image_ok = true;
$queries = array();
$allowed_exts = array('jpg', 'png', 'jpeg', 'gif');
foreach ($images['tmp_name'] as $key => $val ) {
$fileName = $images['name'][$key];
$fileSize = $images['size'][$key];
$fileSize = round($fileSize/1024);
$fileTemp = $images['tmp_name'][$key];
$path_parts = pathinfo($fileName);
$fileExt = $path_parts['extension'];
$fileExt = strtolower($fileExt);
if($fileSize > 2*1024){
$image_ok = false;
}
if(!in_array($fileExt, $allowed_exts)){
$image_ok = false;
}
if($image_ok){
$upload_link = "files/images/".$img_id.".".$fileExt;
$tupload_link = "files/a-images/".$img_id.".".$fileExt;
move_uploaded_file($fileTemp, $upload_link);
move_uploaded_file($fileTemp, $tupload_link);
$img_id++;
}else{
$upload_errors++;
}
Is there any way to identify an image file like "a-img1.jpg"? I need this help badly. Tnx in advance!
Since you already moved the file a second move from the same source won't work. Maybe you should copy the file the second time.
You can use this function to see if the string starts with "a-":
function startsWith($haystack, $needle){
return strpos($haystack, $needle) === 0;
}
So you would do something like:
if(startsWith($img_id, "a-")){
$upload_link = "files/a-images/".$img_id.".".$fileExt;
}else{
$upload_link = "files/images/".$img_id.".".$fileExt;
}
move_uploaded_file($fileTemp, $upload_link);

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