Reputation: 693
Ok so while trying to create small 3 characters mini record which is then added to mod_rewriten domain url making link/file shortening service i seem to hit a brick wall when it comes to url record collision. Might be the fact that i have not yet deployed any reall validation system to check with MySQL if the record exist and push it to the user or if the record exist for the tag but not the actuall url/file then re-run the script to create a new short tag.
Here is the current script which causes collisions with tag and for some reason creates a file with name different then the tag (this is used for file sharing only)
function shorten_file() {
$name = $_FILES['file']['name'];
$ltr = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIKLM';
srand((double) microtime() * 1000000);
$short = '';
for ($i = 1; $i <= rand(4,4); $i++) {
$q = rand() %98;
$short = $short . $ltr[$q];
}
$file = strtolower($name);
$rand = mt_rand();
$short = substr($rand.$file, 0, 3);
return $short;
}
$filename = $_FILES['file']['name'];
$filename = str_replace("'", "", $filename);
$ext = $parts[count($parts)-1];
$contenttype = strtolower($ext);
$new_file = shorten($filename).".".$ext;
$new_hash = shorten($filename);
As mentioned the records are created so say I upload a file called: img_4032.jpg the file will be uploaded as tmp then it will be processed and a record will be created. Now the file is saved to /server_id (1-8)/files/hash (md5 of a-g)/file_cLO.jpg and a record cLO should be generated but instead i get file_cLO.jpg record lNm, so there we go the script does not return same record as it gives to the file. I will also note that for some reason UPPERCASE letters are not returned so it is all lowercase along with numbers.
Any suggestions on a fix, or possible idea's what to do to prevent this collisions from happening other then validating actuall record which will be added?
All "logical" ideas are welcomed allong with suggestions
Upvotes: 0
Views: 212
Reputation: 5409
You call shorten
twice, producing two separate random urls (you reseed the random number generator every time you call it).
Upvotes: 0
Reputation: 7351
The problem is that you're calling the shorten function twice generating a new hash each time, instead call it once and assign that to both vars
$new_hash = shorten($filename);
$new_file = $new_hash.".".$ext;
Upvotes: 1