Posted By

dubogii on 05/17/11


Tagged

number name to exists if append


Versions (?)

Check if File Exists / Append Number to Name


 / Published in: PHP
 

URL: http://css-tricks.com/snippets/php/check-if-file-exists-append-number-to-name/

  1. If the file name exists, returns new file name with _number appended so you don't overwrite it.
  2.  
  3. function file_newname($path, $filename){
  4. if ($pos = strrpos($filename, '.')) {
  5. $name = substr($filename, 0, $pos);
  6. $ext = substr($filename, $pos);
  7. } else {
  8. $name = $filename;
  9. }
  10.  
  11. $newpath = $path.'/'.$filename;
  12. $newname = $filename;
  13. $counter = 0;
  14. while (file_exists($newpath)) {
  15. $newname = $name .'_'. $counter . $ext;
  16. $newpath = $path.'/'.$newname;
  17. $counter++;
  18. }
  19.  
  20. return $newname;
  21. }
  22.  
  23.  
  24.  
  25. Example returns:
  26.  
  27. myfile.jpg
  28. myfile_0.jpg
  29. myfile_1.jpg

Report this snippet  

You need to login to post a comment.