phppermissionsuploadapache2

Upload file to server. Ubuntu, Apache2, PHP


This code should upload files, but it doesn't.

<form name="submit" action="#" method="post" enctype="multipart/form-data">
    <input type="file" value="Choose file" id="pic" name="pic">
    <input type="submit" value="Upload" name="submit">
</form>

<?php
ini_set('display_startup_errors', 1).'<br>';
ini_set('display_errors', 1).'<br>';
error_reporting(-1).'<br>';



    session_start();
    $pic = $_FILES["pic"]["name"];
    $folder = 'projects';
    $path = $folder.'/'.$pic; 


    if (!is_writeable($path)) {
       die("Cannot write to destination file");
    }
    else{
      move_uploaded_file($_FILES["pic"]["tmp_name"], $path);
      
      echo $path.'<br>';
      echo 'DONE';
    }
    
    print_r($_FILES);
    
    
?>

Files on server are owned by www-data. Target folder is owned by www-data and has 0777 permissions. No major errors. And yet it says "Cannot write to destination file".

Any ideas how to resolve this, would be appreciated.


Solution

  • is_writeable()** will return true if the file exists and is writeable. (See PHP manual).

    If you're uploading a new file then the file you're checking for won't exist and is_writeable() will return false.

    Don't overthink this. Just use move_uploaded_file() and handle an error there if move_uploaded_file() returns false.

    Note: move_uploaded_file() will emit a warning if it can't move the file. You may want to adjust your error settings to suppress that in production

    ** is_writeable() is an alias of is_writable()