title: PHP Rename file if exists
body: <p>I've been working with image uploading and am wondering why this isn't working correctly? It doesn't move/upload the file with the new name if it already exists.</p>
  
  <pre><code>if(isset($_REQUEST['submit'])){
       $filename=  $_FILES["imgfile"]["name"];
          if ((($_FILES["imgfile"]["type"] == "image/gif")|| ($_FILES["imgfile"]["type"] == "image/jpeg") || ($_FILES["imgfile"]["type"] == "image/png")  || ($_FILES["imgfile"]["type"] == "image/pjpeg")) &amp;&amp; ($_FILES["imgfile"]["size"] &lt; 20000000)){
      $loc = "userpics/$filename";
      if(file_exists($loc)){
          $increment = 0;
          list($name, $ext) = explode('.', $loc);
          while(file_exists($loc)) {
              $increment++;
              $loc = $name. $increment . '.' . $ext;
              $filename = $name. $increment . '.' . $ext;
          }
        move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$loc");
  
      }
      else{
        move_uploaded_file($_FILES["imgfile"]["tmp_name"],"userpics/$filename");
  
      }
       }
       else{
      echo "invalid file.";
       }
  }
  </code></pre>