title: Using move_uploaded_file To Rename File BEFORE Being Placed In uploads/ Folder
body: <p>I've seen questions similar to this but no one seems to have the problem I do.</p>
  
  <p>I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. <code>Test.PDF</code> becomes <code>Test-19:25:36</code> if it's a duplicate), thus negating any database conflicts.</p>
  
  <p>My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.</p>
  
  <p>I've seen you can use <code>move_uploaded_file</code> to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:</p>
  
  <pre><code>&lt;?php
  include_once 'dbconnect.php';
  
  //check if form is submitted
  if (isset($_POST['submit'])) {
  
  // START OF PRE-EXISTING FILE CHECK
      $filename = $_FILES['file1']['name'];
      $dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
  
      if ($output = mysqli_query($con, $dupeCheck)) {
          if (mysqli_num_rows($output) &gt; 0) {
              $fileArray = pathinfo($filename);
              $timeStamp = "-" . date("H:i:s");
              $filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
  
          }
      }
  // END OF PRE-EXISTING FILE CHECK
  
      if($filename != '')
      {
          $trueCheck = true;
  
          if ($trueCheck == true) {
  
              $sql = 'select max(id) as id from tbl_files';
              $result = mysqli_query($con, $sql);
  
              //set target directory
              $path = 'uploads/';
  
              $created = @date('Y-m-d H-i-s');
  
              $moveTargetVar = "uploads/" . $filename;
  
              move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
  
              // insert file details into database
              $sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
              mysqli_query($con, $sql);
              header("Location: index.php?st=success");
          }
          else
          {
              header("Location: index.php?st=error");
          }
      }
      else
          header("Location: index.php");
  }
  ?&gt;
  </code></pre>
  
  <p>Any advice on how to rename a file before it's written to the uploads folder?</p>