mehdi_php Posted September 24, 2008 Share Posted September 24, 2008 hi , i have upload form , each time user upload a file i must rename file to unique name , but i don't want to use random number to access this images later . so i write this function but this not work and also i used HTTP_UPLOAD Pear to upload image . is there anyway to determind file name on the server ? any function ? i can't find it . first i check if the file exist and the number is 1 for example change file name to 2 . is this the regular form to do this ? <?php $fp = PROFILE.$id ; function check_file($fp , $file ){ if(file_exists($fp.'1'.'.jpg')){ $file->setName('2'.'jpg'); }elseif(file_exists($fp.'2'.'.jpg')){ $file->setName('3'.'jpg'); }elseif(file_exists($fp.'3'.'.jpg')){ $file->setName('4'.'jpg'); }elseif(file_exists($fp.'4'.'.jpg')){ $file->setName('5'.'jpg'); }elseif(file_exists($fp.'5'.'.jpg')){ $file->setName('6'.'jpg'); }elseif(file_exists($fp.'6'.'.jpg')){ $file->setName('7'.'jpg'); }elseif(file_exists($fp.'7'.'.jpg')){ $file->setName('8'.'jpg'); }elseif(file_exists($fp.'8'.'.jpg')){ $file->setName('9'.'jpg'); }elseif(file_exists($fp.'9'.'.jpg')){ $file->setName('10'.'jpg'); } } if(is_dir(PROFILE.$id)){ if($file->isValid()){ check_file($fp , $file); $file->setName('1'.'.jpg'); $moved = $file->moveTo($fp); if(!PEAR::isError($moved)){ echo '<div id="notic">file uploaded </div>'; }else{ echo 'error during file upload ' ; } } ?> Link to comment https://forums.phpfreaks.com/topic/125595-upload-file-with-uniqe-name/ Share on other sites More sharing options...
Adam Posted September 24, 2008 Share Posted September 24, 2008 Do they need to be in form of 1, 2, 3, 4 etc ?? If not just create yourself a naming formula like.. md5(TodaysDate_TimeToTheSecond_Random4DigitNum) Chances are like 1 in 10 thousand per second that someone will ever get the same number.. or something daft! If they do need to be in order, could loop through, eg: $x = 1; while ( !file_exists($x . '.jpg')) { $x++; } $filename = $x . '.jpg'; ..not tested though! If you had a lot of uploads however, and it gets to like 300.jpg, or even 3000.jpg, don't wanna have to loop through each time. so could use a database or flatfile or something to store the current count... Adam Link to comment https://forums.phpfreaks.com/topic/125595-upload-file-with-uniqe-name/#findComment-649373 Share on other sites More sharing options...
JasonLewis Posted September 24, 2008 Share Posted September 24, 2008 Another solution, although I don't recommend it in-case you are deleting files. $files = count(glob("path/to/dir/*.*")) + 1; //You need the *.* at the end. It gets any file with any extension, so it doesn't get folders. Although, as I mentioned, if you delete files it could get messy. Link to comment https://forums.phpfreaks.com/topic/125595-upload-file-with-uniqe-name/#findComment-649390 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.