title: How to delete an old upload file and upload a new file for an entry in PHP?
body: <p>I am making an edit form where the user can edit item details and change the item image. The item details get updated in the database fine but the item image does now change. Below is my code...</p>
  
  <pre><code>if($_POST['item_img']){
      $old_img = "img/items/$item_id.jpg";
      $default_img = "img/items/default.jpg";
      if (file_exists($old_img)) {
          unlink($old_img);
          $filename = $item_id.'.jpg';
          move_uploaded_file ($_FILES["item_img"]["tmp_name"],"img/items/".$filename)
      }elseif(file_exists($default_img)) {
          unlink($default_img);
          $filename = $item_id.'.jpg';
          move_uploaded_file ($_FILES["item_img"]["tmp_name"], "img/items/".$filename);
      }
  }
  </code></pre>
  
  <p>I think it is my <code>if($_POST['item_img'])</code> statement that is causing this issue. What could I change the loop to.</p>
  
  <p>The first nested if statement checks if there is an image attached, and the second if statement checks if a default image is attached. In both cases it deletes the old image and sets a new image with the "item_id" as its name.</p>
  
  <p>Below is the code for my for upload field:</p>
  
  <pre><code>&lt;form class="stock" method="post" enctype="multipart/form-data" action=""&gt;'
       &lt;input type="file" name="item_img"&gt;
  &lt;/form&gt;
  </code></pre>