Search code examples
phpfilefile-ioio

PHP: move_uploaded_file doesn't work


I just want to move a temporary file to a specified folder. Here is my code.

        $uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/upload';
        $name = basename($_FILES["csv"]["name"]);
        $tmp_name = $_FILES["csv"]["tmp_name"];
        chmod("{$uploads_dir}/{$name}", 0755);

        if (!move_uploaded_file($tmp_name, "{$uploads_dir}/{$name}")):
            array_push($fileErrArr, "fail to move uploaded file");
        endif;

This is the error message from the httpd log. It doesn't even mention the "permission" stuff.

[error] [client XXX] PHP Warning: move_uploaded_file(/var/www/html/upload/XXX.csv): failed to open stream: \xe8\xa8\xb1\xe5\x8f\xaf\xe3\x81\x8c\xe3\x81\x82\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x9b\xe3\x82\x93 in /var/www/html/XXX/action.php on line 115, referer: https://XXX/

[error] [client XXX] PHP Warning: move_uploaded_file(): Unable to move '/tmp/php40tPEO' to '/var/www/html/upload/XXX.csv' in /var/www/html/XXX/action.php on line 115, referer: https://XXX/

Any help is appreciated. Thanks!


Solution

  • I think you can use this <?php echo exec('whoami'); ?> to check your PHP script runner.

    Then use ls -l to check the target direction who is the owner.

    Make sure the runner and the owner is the same.

    Eg: the php runner may be www-data and the target folder owner may be admin. Use:

    chown www-data /var/www/xxx/upload
    chmod 755 /var/www/xxx/upload
    

    It may work.