Check if File Exists / Append Number to Name

Last updated on:

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;

    return $newname;

Example returns:



  1. Anton
    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
        $randomnumber = mt_rand(1, 10);
        //Suffix = $tag mit dem . entfernen
        //nur wenn in filename enthalten
          $filename = substr($filename,0,strlen($filename)-strlen($tag)-1);
        //Neuer Filename
        if($filecounter == NULL)
          $newfilename = $filename.'_'.$filedate.'.'.$tag;
          $newfilename = $filename.'_'.$filecounter.'_'.$filedate.'_'.$tag;
        return $newfilename;
  2. Gianluca
    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

  4. Bhumi
    Permalink to comment#

    Thanks for sharing. useful to me.

Leave a Comment

Posting Code

We highly encourage you to post problematic HTML/CSS/JavaScript over on CodePen and include the link in your post. It's much easier to see, understand, and help with when you do that.

Markdown is supported, so you can write inline code like `<div>this</div>` or multiline blocks of code in in triple backtick fences like this:

  function example() {
    element.innerHTML = "<div>code</div>";

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed