A Web Design Community curated by Chris Coyier

A little dab'll do ya

Code Snippets

Home » Code Snippets » PHP » Check if File Exists / Append Number to Name Submit one!

Check if File Exists / Append Number to Name

If the file name exists, returns new file name with _number appended so you don't overwrite it.

function file_newname($path, $filename){
    if ($pos = strrpos($filename, '.')) {
           $name = substr($filename, 0, $pos);
           $ext = substr($filename, $pos);
    } else {
           $name = $filename;
    }

    $newpath = $path.'/'.$filename;
    $newname = $filename;
    $counter = 0;
    while (file_exists($newpath)) {
           $newname = $name .'_'. $counter . $ext;
           $newpath = $path.'/'.$newname;
           $counter++;
     }

    return $newname;
}

Example returns:

myfile.jpg
myfile_0.jpg
myfile_1.jpg

Subscribe to The Thread

  1. Anton says:

    Strange this one doesn’t work on my site.

    My goal is to restrict users to upload only 10 pics each (from 1 to 10) … picture_1-10.jpg.
    If a user decided to delete a picture, for example picture_7.jpg and upload a new one the picture should be renamed with the same title as the deleted one.

    Any suggestions? Thanks in advance.

    Here is my PHP script:

    function Upload_GenFilename($filename, $tag, $filecounter = NULL)
      {
        $filedate = bqSearch;
        //Neuen Startwert f?r Zufallszahl bestimmen
        mt_srand();
        $randomnumber = mt_rand(1, 10);
    
        //Suffix = $tag mit dem . entfernen
        //nur wenn in filename enthalten
        if(stristr($filename,$tag))
        {
          $filename = substr($filename,0,strlen($filename)-strlen($tag)-1);
        }
    
        //Neuer Filename
        if($filecounter == NULL)
        {
          $newfilename = $filename.'_'.$filedate.'.'.$tag;
        }
    
        else
        {
          $newfilename = $filename.'_'.$filecounter.'_'.$filedate.'_'.$tag;
        }
        return $newfilename;

It's Your Turn

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
--- The Management ---