Ryan A wrote:
Hey all,
I needed to make a simple upload script so users could upload their images
but had a small extra requirment,
after searching google, hotscripts and all the other usual places and
downloading code, i realized its better to
write the whole damn thing myself, so i did.

Now that the little history lesson is over.....I have run into a problem
which i am sure you guys must have too,
when you take the uploaded pic of the user...how do you save it?
I dont mean saving onto disk, i can do that, i mean the name of the file...I
am having all the pics upload to one
common directory (member_pics) so what do you suggest I name the pictures?
eg:
username.jpg?
first_last_name.jpg?
<random_number>_username.jpg?
etc etc
(for this example i wrote only jpg, i will be having png and gif too)


Depends if the images are freely accessible to anyone or you want to protect them so they must be served by php script.


If the former I like to keep the original name that usualy has some meaning. If image of that name already exists (e.g. john.jpg), I append 2, 3, 4 etc. (e.g. john2.jpg). You need to lock the script somehow so it does not run into race condition, I use mysql GET_LOCK function for this. So the whole process looks like:

/* wait 30 seconds to get the lock, then the function fails and returns 0, you should take care of this error */
SELECT GET_LOCK('upload_image', 30);
$image_name = $_FILES['name']['fileinput'];
$i = 2;
while(file_exists('userimages/'.$image_name)) {
$image_name = // append $i here
}
move_uploaded_file($_FILES['tmp_name']['fileinput'], 'userimages/'.$image_name);
// update database
// release lock
SELECT RELEASE_LOCK('upload_image');


If you serve the files by a php script, it does not matter what name you give the file on the filesystem, you can use uniqid() for example. Store the real name in the database, this gives you the advatage that you can have the same names. Still you should use the above lock and loop to make sure the script won't overwrite another file.

HTH, Marek

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to