Search code examples
phpapachefile-uploadpermissionsmamp

PHP Unable To Move Uploaded Files Despite Having Full Permissions?


I'm coding a blog-like website with functions like posting and displaying posts correctly. Currently, I'm trying to add an option to include an image in posts by uploading it to a folder in my project folder using PHP's move_uploaded_file function.

I've given the Apache user, _www, read, write and execute permissions via chmod. I've also ensured that it has permissions to write, read and execute in the parent directories leading up to the uploads folder itself.

I've even tried transferring full ownership of the project folder to the said user using chown. Yet, I'm getting a PHP Warning that says:

PHP Warning: move_uploaded_file(/Users/MyUser/Desktop/Project/assets/php/../uploads/2.jpg): failed to open stream: Permission denied in /Users/MyUser/Desktop/Project/assets/php/upload.php

PHP

$target_dir = __DIR__ . "/../uploads/";
var_dump($target_dir);
$file = basename($_FILES["file"]["name"]);
$target_file = $target_dir . $file;
$allowed_extensions = array("jpeg", "jpg", "png");
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));


if(isset($_POST["upload"])) {
  echo $target_file;

  $stmt = $pdo->prepare("INSERT INTO images (imgTitle, imgLocation) VALUES (:imgTitle, :imgLocation)");
  $stmt->execute(array(
    ":imgTitle" => basename($_FILES["file"]["name"]),
    ":imgLocation" => $target_file
  ));

  if ($imageFileType = in_array($imageFileType, $allowed_extensions)) {
    move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
  }
}

HTML

<form action="" method="post" enctype="multipart/form-data">
    Select Image File to Upload:
    <p><input type="file" name="file"></p>
    <input type="submit" name="upload" value="Upload">
</form>

Why is this happening and how can I solve this without changing the _www user to my user?


Solution

  • After some troubleshooting myself I finally found out the cause of the error. Going to answer my own question as a note and future reference to those who may end of doing the same error as I did.

    The macOS Apache user is NOT the Apache user MAMP uses.

    The Apache user of MAMP differs from the user that macOS has built-in, which is _www. Do NOT use _www if you're running MAMP, but rather go to /Applications/MAMP/conf/apache/httpd.conf, this is where the user details for MAMP's Apache user is located at.

    The user will most likely be your user's username, which is unchangeable. The only setting you can change is the group of that Apache user. I suggest that you use this for building on your localhost, but remember to change to the new Apache user details when you switch to a web host other than localhost.

    I hope my mistake can save you hours of confusion and some degree of frustration. Have fun coding!