Search code examples
phpmamp

PHP Copy() is only working some of the time


(essentially a copy of this question, which has no responses)

I have an app that is trying to take a picture using the phone camera, and send that image to our server. Here is the PHP code behind it:

    <?php

  if (isset($_FILES['idimage'])) {
    $img = $_FILES['idimage']['name'];
    $tmpimg = $_FILES['idimage']['tmp_name'];

    copy($tmpimg, "C:/MAMP/htdocs/ids/" . "id.png");
    exit();
  } else {
    echo "there is no data with name [idimage]";
  }

 ?>

I have followed 3 different tutorials and all of them used the method you are seeing above. This code works sometimes, from testing it works 3/22 times (~14%). Why is this? What is causing the file to only upload some of the time?


Solution

  • The tutorials you found seem to omit relevant information.

    1. You absolutely need to verify the upload status:

      if ($_FILES['idimage']['error'] === UPLOAD_ERR_OK) {
          // Successful upload
      } else {
          // Everything else
      }
      
    2. The recommended function to copy the file is the move_uploaded_file() function, although it shouldn't make any difference from the functionality standpoint, it's mainly a security mechanism.

    Last but not least, double-check that your app has full error reporting set and sends stuff to a log file you can check.