Grow your CSS skills. Land your dream job.

Last updated on:

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

Comments

  1. Permalink to comment#

    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;
  2. Permalink to comment#

    If the filename has no extension, then php will complain that $$ext variable is not set.
    You should change this code:

     } else {
    	$name = $filename;
    }
    

    with this:

     } else {
    	 $name = $filename;
             $ext = "";
    }
    
  3. Nadimuthu
    Permalink to comment#

    How to download my file from already uploaded path?. What function i will used.? please help me

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".