Reputation: 109
All images are uploaded into image folder under my php project while reference goes into mysql table, but my confusion is, what if there are two images have the same name, are there better way to avoid duplicate naming happen? i know i cant control how will user naming their image file.
Upvotes: 0
Views: 1426
Reputation: 1473
Like VMai said before. Primary key is a good solution. But if You just wan`t to know solution with same name problem:
$filename = 'myfilename'; // without extension!
$extension = '.jpg';
$dir = '/directory/';
$fullPath = $dir.$filename.$extension;
$i=1;
$newFilename = filename;
while(file_exists($fullPath))
{
$newFilename = $filename.'_'.$i;
$i++;
$fullPath = $dir.$newFilename.$extension;
}
Not tested, but You got the concept
Upvotes: 1
Reputation: 4527
For security and yes to avoid duplicate you could change the filename
to your own format,
example. formats
$filename = sha1(time().$original_filename)
or $filename = md5(time().$originalfilename)
it is up to you.
One advantage of changing the filename is that if an attacker uploads something, you are sure he will not find it because of a different name,other than the already security validations you have provided.
Upvotes: 0
Reputation: 6438
I usually do a combination of timestamp and a big random value (just in case):
So for example:
$filename = time() . rand(1000000,9999999) . strtolower($ext);
Where $ext is the extension (whether it's jpg, png or whatever).
This is also more secure than accepting filenames from user.
And the reason for strtolower, is because sometimes someone will upload something like IMAGE.JPG, so rather on counting that your server and all your scripts will be case insensitive, you can simply make sure that all extensions are in lowercase.
Upvotes: 2