0

I am learning PHP through w3schools and the upload file php code does not seem to work. At first, there are warning shown that said "unable to open stream" but as I refreshed multiple times (trying to debug) the warning stopped showing but it still failed to upload the file.

Thus I decided to simplify the code (omitting all the features) and focus on uploading only. Some basic information, I am using an apache server on my localhost device. Below are the simplified code

<html>
<head><title>File upload test page</title></head>

<body>
    <form action="upload_test.php" method="POST" enctype="multipart/form-data">
        <input type="file" name="uploadedfile">
        <input type="submit" value="Upload File">
    </form>
</body>
</html>
<?php

$target = "uploads/";
$target = $target . basename($_FILES["uploadedfile"]["name"]);

if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]["name"])). " has been uploaded. <br>";
} else {
    echo "Sorry, there was an error uploading your file. <br>";
}
?>

The error keeps persisting. I am very new to php so any help would be much appreciated. Thank you!

  • This usually indicates PHP isn't able to access the directory you're trying to access. As a test, I'd suggest using `/tmp/` as your `$target`. – prieber May 26 '21 at 15:29
  • @prieber I tried it and it works, but may I know how to allow php access the directory I assign? – deadly-pants May 26 '21 at 15:37

1 Answers1

0

"unable to open stream", means process user of apache have no write permission for dir "uploads/", try to change user of "uploads/" (such as "chown apache.apache uploads") or change permission of the dir (such as "chmod 777 uploads"). And if u can not get useful message next time, try this to catch exception maybe u can get some useful messages

<?php
  $target = "uploads/";
  $target = $target . basename($_FILES["uploadedfile"]["name"]);
  try{
     if (move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], $target)) {
          echo "The file ". htmlspecialchars( basename( $_FILES["uploadedfile"]. ["name"])). " has been uploaded. <br>";
      } else {
      echo "Sorry, there was an error uploading your file. <br>";
      }
  }catch(Exception $e){
      var_dump($e->getMessage());
  }
  • `chmod 777` may fix a small permissions issue, but it introduces a whole new class of problems. Use with caution - https://stackoverflow.com/questions/2338641/in-a-php-apache-linux-context-why-exactly-is-chmod-777-dangerous – prieber May 26 '21 at 15:46
  • Thanks for your help!! – deadly-pants May 26 '21 at 15:56
  • @prieber Yes, chmod 777 is very dangerous, so I recommend chown at first, but for some beginners, i think we can fix problems one by one. – just like before May 27 '21 at 03:40