Auto Numbering File on Upload - php

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...
?>

Related

upload file and register it in a database

If there is any mistake in my writing, please excuse me. I'm not very good at translating from Spanish to English.
I am using pluploadQueue, reading the example script (upload.php). I have tested it and it works fine.
In addition to all that, I need to record information about the files that are attached in a database.
I have tried to add the statements that save the information in the database, but it only works halfway. It generates just one entry in my database table.
I notice that in the "upload" directory it generates a 1024kb .part for the 1st file but it doesn't do anything else there. Although visually the Widget tells me that it has uploaded all the files.
I need to save as many entries as files are selected (many can be uploaded, so it has been thought).
Could someone point me to a reference? I have tried to search for something about my problem but I have not been able to find anything.
I use version 2.3.9 of plupload
Correct me if I'm wrong, but I'm understanding that the upload.php script is executed (or should be) for each file to be uploaded, right?
My logic is such that:
Insert into db basic "header" information for the first time. In the following operations it is recovered.
plupload upload routine
Insert in db file information
thus forming a master-detail relationship bettween 2 tables.
For some reason, it stays at point 2. And this part would not be running:
while (($file = readdir($dir)) !== false) {
$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
// If temp file is current file proceed to the next
if ($tmpfilePath == "{$filePath}.part") {
continue;
}
// Remove temp file if it is older than the max age and is not the current file
if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
#unlink($tmpfilePath);
}
}
closedir($dir);
}
Help me?
EDIT:
Okay. I have found a typo error. I corrected it and now it saves me for each file. What I can't figure out right now is why it has generated hundreds of .part files in the directory instead of overwriting it. And this led to hundreds of records being stored, one for each generated .part.

PHP letting the code add the uploader's last name to the image file he is uploading from a form

Got the server, got the domain, got the code, getting the images successfully, making the products for the customers from the image files they upload. Yay!
Problem: all my image names are image_0001 etc.
Customers can't rename image files from iPhones and do not care to from PCs.
So I was thinking about putting a short form on the upload page asking for customer's last name and having the PHP code attach that name to the image file(s) being uploaded.
If it's not possible, I'm sorry for the inconvenience.
You can rename files after they have been saved to your server, check out the PHP manual for the rename function - http://www.php.net/manual/en/function.rename.php, or just while you are moving them from the tmp directory, you can specify a different name for the uploaded file. See http://www.php.net/manual/en/function.move-uploaded-file.php
Be careful to include something in your code for dealing with naming conflicts.
This one might help :
$imagename = basename($_FILES['file']['name']);
$ext = pathinfo($imagename , PATHINFO_EXTENSION); //we want to change the file name but not the extension
$newImagename= $imageName.$username.'.'.$ext; //assuming you hold the username in $username
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$newImagename}"))
{
....
}

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

PHP include image file with changing filename

I am completely new to PHP so forgive me if this question seems very rudimentry. And thank you in advance.
I need to include a jpg that is generated from a webcam on another page. However I need to include only the latest jpg file. Unfortunately the webcam creates a unique filename for each jpg. How can I use include or another function to only include the latest image file?
(Typically the filename is something like this 2011011011231101.jpg where it stands for year_month_date_timestamp).
Easy way is to get the latest image with the help of the below code
$path = "/path/to/my/dir";
$latest_ctime = 0;
$latest_filename = '';
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
// could do also other checks than just checking whether the entry is a file
if (is_file($filepath) && filectime($filepath) > $latest_ctime) {
$latest_ctime = filectime($filepath);
$latest_filename = $entry;
}
}
}
// now $latest_filename contains the filename of the newest file
give the source of latest image to <img> tag
Since the images are named via pattern which relates to the date, you should be able to just use:
$imgs = glob('C:\images\*.jpg');
rsort($imgs);
$newestImage = $imgs[0];
This is fairly straightforward, since your file names are in order.
The first thing you need is a list of files in the directory. The readdir (doc) function is what you are looking for. Example script that uses it: http://www.liamdelahunty.com/tips/php_list_a_directory.php
Once you have that, use substr() (doc) to chop off the file name extensions.
You're left with an array of numbers, essentially. From here, do a sort (doc) and specify the SORT_NUMERIC flag. Grab the number on the end, stick a .jpg back on it, and you have the last file.
Alternate Solution: Read the timestamps of files to get the last one. This would generally be a better answer, but perhaps not in your situation if you plan to edit any of the files.
I guess you will have to know a way to determine what the latest image file is called. Maybe you can make a textfile or something where every time a new image is created the webcam writes the latest filename in the text file (so the only text in the text file is the file name of the latest image file if it makes any sense). Of course you will have to have access to the script that generates the php file.
addition to #ken 's post, it's probably sorting alphabetically instead of numerically. perhaps you could try:
$imgs = glob('C:\images\*.jpg');
rsort($imgs, SORT_NUMERIC);
$newestImage = $imgs[0];

Rename Uploaded File in 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);

Categories