>the web server, how should the image be named [uniquely]? The problem is
>that if the user specifes the name of the image file, there's a chance
>he'll name another one the same way (and thus overwrite the original). I
>was thinking of maybe a dual approach, where the user gives the image
>file a name, but then the PHP script appends, say, the table name and
>record ID--so as to make the filename unique.
What I do is this:
<?php
# Get rid of gnarly characters in filenames:
$filename = ereg_replace('[^a-zA-Z0-9_\\.-]', '', $photo_name);
# If their filename was so messed up that there's nothing left, give it a
random name.
$filename = $filename ? $filename : chr(rand(ord('A'),ord('Z'))) .
chr(rand(ord('A'),ord('Z'))) . chr(rand(ord('A'),ord('Z'))) .
chr(rand(ord('A'),ord('Z')));
# Now be sure it's unique:
$appendix = '';
# break the filename up into 'whatever' and '.jpg' (or '.gif' or whatever
it is)
# In order to force uniqueness (below) I want to change 'duplicate.jpg'
into 'duplicate2.jpg', not 'duplicate.jpg2' :-)
$extpos = strrpos($filename, '.');
# echo "extpos is $extpos<BR>\n";
if (!$extpos){
$extension = '';
}
else{
$extension = substr($filename, $extpos);
$filename = substr($filename, 0, $extpos);
}
$pathname = "$directory/$filename$appendix$extension";
# echo "extension $extension<BR>\n";
# echo "filename $filename<BR>\n";
# echo "appendix $appendix<BR>\n";
# echo "pathname $pathname<BR>\n";
while (@file_exists($pathname)){
# It's kinda hacky to ++ the empty string, but it avoids tacking on '0'
# to filenames that were fine as they were...
$appendix++;
$pathname = "$directory/$filename$appendix$extension";
# echo "extension $extension<BR>\n";
# echo "filename $filename<BR>\n";
# echo "appendix $appendix<BR>\n";
# echo "pathname $pathname<BR>\n";
}
if (move_uploaded_file($photo, $pathname)){
# Success!
}
else{
# Error message
}
?>
--
Like Music? http://l-i-e.com/artists.htm
Off-Topic: What is the moral equivalent of 'cat' in Windows?
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php