Rename Uploaded File in PHP - php

What I want to do is add a number to the beginning of the file name so I don't have a duplicate file name in the folder.
So I choose my file "example.pdf" and upload, I got the the part of the code that looks like this:
move_uploaded_file($HTTP_POST_FILES['ufile']['tmp_name'][0], $path1);
In this line of code above can I add a variable to change the file name to "1-example.pdf"?
Is that possible?

You can specify the new name as part of the second parameter of move_uploaded_file:
move_uploaded_file($HTTP_POST_FILES['ufile']['tmp_name'][0], "$path1/example.pdf");
Hope this helps!

The move_uploaded_file method's second parameter is not only the path, but the filename to place the file. Try something like this:
move_uploaded_file($_FILES['ufile']['tmp_name'][0], $path1.'/[PUT NUMBER HERE]-'.$_FILES['ufile']['name'][0]);

What I did is that I created a random number which goes until to a million so the program will generate a number to rename a picture like this .though I did not use exactly your codes in your question .
#Rename images
$rand = rand(0,1000000);
$rename = $rand.$name;
$move = move_uploaded_file($temp_name,$target.$rename);

Related

I want to read the content of a text file into a list in PIP

What I am doing is getting the content of a file in a list then according to the content of txt file I have created 3 variables name phnno and dob
the txt file looks like this
talha,04236522155,22/10/1990
Roshan,04235290600,08/11/1999
And my code looks like this
function read_file()
{
$file_name=$GLOBALS['file_name'];
$target="uploads/".$file_name;
$myfile = fopen("$target", "r") or die("Unable to open file!");
while (!feof($myfile))
{
# code...
$buffer=fgets($myfile,"4096");
list($name,$cellphn,$dob)=explode(",",$buffer);
$namearr=array($name);
foreach ($namearr as $value) {
# code...
echo($value);
}
}
fclose($myfile);
}
The output is talha Roshan
which is right but now I want to display only 1st name how should I do that and what if I only want to read phone numbers from the file store it in an array or list and then insert them into database?
So the crux is How should I access elements of my choice from this array?
How should I insert all or selected names in databse?
And how should I only ready phone numbers from the file
Please try to remove the "admin/" and test again. As your F:\xampp\htdocs\proj\admin\index.php to call F:\xampp\htdocs\proj\admin\upload should be "upload/..."
EDIT: to be more specific, do this dirname(FILE)."/uploads/a.txt"
You mentioned you uploaded it to directory named "uploads" but your code has "upload"
$target="admin/upload/".$file_name;
Changing it to this may solve the problem if you didn't made any typo
$target="admin/uploads/".$file_name;
I think your directory name is wrong in this case
$target should be admin/uploads instead of admin/upload

Saving image file name exactly as URL image file into folder in PHP

I have visited this article previously and found it useful, but i would like to add more functionality to it by having it save an image file name according to the URL name.
This is what I've done so far and it works.
$contents=file_get_contents('http://www.domain.com/logo.png');
$save_path="C:/xampp/htdocs/proj1/download/[logo.png]";
file_put_contents($save_path,$contents);
Basically, where I have put square brackets around I want to have that dynamic based on the URL file name. For example, if i have an image url such as this: https://cf.dropboxstatic.com/static/images/brand/glyph-vflK-Wlfk.png, I would like it to save the image into the directory with that exact image name which in this case is glyph-vflK-Wlfk.png.
Is this possible to do?
I would do this way
$url = "http://www.domain.com/logo.png";
$file = file_get_contents($url);
$path = "C:/xampp/htdocs/proj1/download/". basename($url);
return !file_exists($path) ? file_put_contents($path, $file) : false;
From what I understand, what you're trying to do is the following :
$url = 'http://www.domain.com/logo.png';
$contents=file_get_contents($url);
$posSlash = strrpos($url,'/')+1);
$fileName = substr($url,$posSlash);
$save_path="C:/xampp/htdocs/proj1/download/".$fileName;
file_put_contents($save_path,$contents);
There is a function for that, basename():
$url="http://www.domain.com/logo.png";
$contents=file_get_contents($url);
$save_path="C:/xampp/htdocs/proj1/download/".basename($url);
file_put_contents($save_path,$contents);
You might want to check if it already exists with file_exists().

Auto Numbering File on Upload

I have edited the title, so I hope this one will be helpful...
Case:
I have many images and have uploaded it to a server. I was manually change their names with numbers. Of course I remember the last number of the file but could anyone help me with upload script that enable me to check the last number existed on the server folder and rename the file I'm gonna upload so that the name of the file is last_number_exist_on_server+1?
Ah, helping on generating the thumbnail to a specific folder and size will be appreciated also.
Last but not least, I am using PHP. No database... and the image file type is JPG.
Sorry, newbie's question.
Note: there is zero error checking here. Add some before you use in production! :)
<?php
// get the next number for our filename
// returns an array of files and directories in descending alpha-order
$files = scandir("./images", SCANDIR_SORT_DESCENDING);
$last_filename = array_shift($files);
$last_number = (int)substr($last_filename, 0, strrpos($last_filename, "."));
$next_number = $last_number++;
// now rename your file...
?>

PHP: how do I copy a temp file upload to multiple places?

how can I copy two times the same file? I'm trying to do something like this:
copy($file['tmp_name'], $folder."1.jpg");
copy($file['tmp_name'], $folder."2.jpg");
copy($file['tmp_name'], $folder."3.jpg");
And how many time does temp files has before it's destroyed by the server?
I try using move_uploaded_file also, but I can't make it work. I want to generate 2 thumbs from an uploaded file.
Some help?
Thanks,
move_uploaded_file will move the file, and not copy it -- which means it'll work only once.
If you are using copy, there shouldn't be any limit at all on the number of times you can copy : the temporay file created by the upload will only be destroyed at the end of the execution of your script (unless you move/delete it before, of course)
Still, maybe a solution would be to use move_uploaded_file first, and, then, copy ?
A bit like that, I suppose :
if (move_uploaded_file($file['tmp_name'], $folder . '1.jpg')) {
copy($folder . '1.jpg', $folder . '2.jpg');
copy($folder . '1.jpg', $folder . '3.jpg');
}
This would allow you to get the checks provided by move_uploaded_file...
If this doesn't work, then, make sure that :
$folder contains what you want -- including the final /
That $file['tmp_name'] also contains what you want (I'm guessing this is some kind of copy of $_FILES -- make sure the copy of $_FILES to $file is done properly)
Why doesn't move_uploaded_file() work? Are you trying to use it twice? You can't do that, it moves it, so the second time will fail.
I would just use move_uploaded_file() once, and then make the second copy from the location you just moved it to:
move_uploaded_file($uploaded, $destination);
copy($destination, $destination2);
I don't have a reply to your question directly but how about this workaround ?
copy($file['tmp_name'], $folder."1.jpg");
copy($folder."1.jpg" , $folder."2.jpg");
copy($folder."1.jpg" , $folder."3.jpg");
Thanks man, you give me the light.
I made something like this:
$objUpload = new Upload();
$filename = $objUpload->uploadFile($newFile,$folder);
// returns a string
$objUpload->makeThumb($filename,$folder,"thumbs",139);
// makes a 139px thumbnail from the original file uploaded on the first step
$objUpload->makeThumb($filename,$folder,"mini",75);
// makes another thumb from the same file
Using move_ulploaded_file and copy we can make only one thumb. :)

I made an upload script in PHP. How do I avoid overwriting files?

I've made an image upload script using the move_uploaded_file function. This function seems to overwrite any preexisting file with the new one. So, I need to check if the target location already has a file. If it does then I need to append something to the filename(before the extension so that the file name is still valid) so the filename is unique. I'd like to have the change be minimal instead of something like appending the datetime, if possible.
How can I do this with PHP?
When uploading files I will nearly always rename them. Typically there will be some kind of database record for that file. I use the ID of that to guarantee uniqueness of the file. Sometimes I'll even store what the client's original filename was in the database too but I'll never keep it or the temporary name because there is no guarantee that information is good, that your OS will support it or that it's unique (which is your issue).
So just rename it to some scheme of your own devising. That's my advice.
If you don't have any database reference, then you could use file_exists() for this but there's no guarantee that between the time of checking if something exists and moving it that something else won't use that same filename that you'll then overwrite. This is a classic race condition.
http://us3.php.net/manual/en/function.file-exists.php
Don't use file_exists() for the reason that it returns true (on *nix systems at least, since directories are specialized files) if the value is a directory. Use is_file() instead.
For example, say something fails and you have a string like:
$path = "/path/to/file/" . $file; // Assuming $file is an empty value, if something failed for example
if ( true === file_exists($path) ) { echo "This returns true"; }
if ( true === is_file($path) ) { echo "You will not read this"; }
It's caused a few problems in the past for me, so I always use is_file() rather than file_exists().
I use date and time functions to generate a random file name based on the time of upload.
Let's assume you are submitting a file from a form where you have an input named incomingfile like this:
<input type="file" id="incomingfile" name="incomingfile" />
First of all I use to "depure" the filename and copy it from the default temporary directory to a temporary directory. This is necessary to deal with special characters. I had troubles when I didn't adopt this practice.
$new_depured_filename = strtolower(preg_replace('/[^a-zA-Z0-9_ -.]/s', '_', $_FILES["incomingfile"]["name"]));
copy($_FILES["incomingfile"]["tmp_name"], 'my_temp_directory/'.$new_depured_filename);
With the following piece of code I check if the file exists, if so, I find a new name and finally copy it. For example if I want to write a file called myimage.jpg and it already exists I rename the pending file to myimage__000.jpg. If this exists as well I rename the pending file to myimage__001.jpg and so on until I find a non-existing filename.
$i=0; // A counter for the tail to append to the filename
$new_filename = $new_depured_filename;
$new_filepath='myfiles/music/'.$new_filename;
while(file_exists($new_filepath)) {
$tail = str_pad((string) $i, 3, "0", STR_PAD_LEFT); // Converts the integer in $i to a string of 3 characters with left zero fill.
$fileinfos = pathinfo($new_filepath); // Gathers some infos about the file
if($i>0) { // If we aren't at the first while cycle (where you have the filename without any added strings) then delete the tail (like "__000") from the filename to add another one later (otherwise you'd have filenames like myfile__000__001__002__003.jpg)
$previous_tail = str_pad((string) $i-1, 3, "0", STR_PAD_LEFT);
$new_filename = str_replace('__'.$previous_tail,"",$new_filename);
}
$new_filename = str_replace('.'.$fileinfos['extension'],"",$new_filename); // Deletes the extension
$new_filename = $new_filename.'__'.$tail.'.'.$fileinfos['extension']; // Append our tail and the extension
$new_filepath = 'myfiles/music/'.$new_filename; // Crea il nuovo percorso
$i++;
}
copy('my_temp_directory/'.$new_depured_filename, $new_filepath); // Finally we copy the file to its destination directory
unlink('my_temp_directory/'.$new_depured_filename); // and delete the temporary one
Used functions:
strtolower
preg_replace
copy
file_exists
str_pad
pathinfo
str_replace
unlink
To check if a file exists, you can use the file_exists function.
To cut the filename, you can use the pathinfo function.
I use
$file_name = time() . "_" . $uploaded_file_name;

Categories