duanhuchang5056 2017-05-28 14:56
浏览 104
已采纳

PHP move_uploaded_file失败,没有错误

On LEMP (Linux CentOS, Nginx, MariaDB, PHP) server, /etc/php.ini file has the following.

file_uploads = on
upload_tmp_dir = /tmp

Stage1.html has the following markup, which is used to select an image file, and post the image to Stage2.php.

<form action="Stage2.php" method="post" enctype="multipart/form-data">
    <input type="file" name="upload">
    <input type="submit">
</form>

Stage2.php has the following.

<?php
    $original_name = $_FILES["upload"]["name"];
    $temporary_name = $_FILES["upload"]["tmp_name"];
    $target = "/var/www/html/images/" . $original_name;

    if(move_uploaded_file($temporary_name, $target)) {echo "Success";}
    else{echo "Failed";}
?>

Original File, Temporary File, and Target are properly set. However, Failed is returned.

enter image description here

Adding the following to Stage2.php returns 0. To quote the PHP Manual, 0 means "There is no error, the file uploaded with success."

$_FILES["upload"]["error"];

Adding the following to Stage2.php does not display any errors. This leads me to suspect that PHP thinks that everything is OK, and perhaps the problem is some issue with CentOS or Nginx. Is this the logical assumption?

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For debugging, in CentOS, I've set the permissions of /tmp and /var/www/html/images to 777 (read, write, execute for everybody). Still no errors are returned.

enter image description here

  • 写回答

1条回答 默认 最新

  • dsfhe34889 2017-05-30 01:19
    关注

    Just in case others run into this problem, I want to share what I discovered. I was able to conclude this was an issue with Linux CentOS, and not a PHP issue.

    Typically, open_basedir will be set to /var/www in /etc/php.ini. In this scenario, upload_tmp_dir must be somewhere below /var/www. I set upload_tmp_dir to /var/www/html/images/tmp.

    upload_tmp_dir = /var/www/html/images/tmp
    

    I then set the temporary uploads directory permission is 755.

    [john.doe@server1 ~]# chmod 755 /var/www/html/uploads/tmp
    

    I then used the following PHP to determine what user PHP uses to upload the file. In my scenario, the user was apache.

    <?php
        echo exec('whoami'); 
    ?>
    

    Once I had determined the user was apache, I set the owner of the temporary uploads directory to apache.

    [john.doe@server1 ~]# chown apache:root /var/www/html/uploads/tmp
    

    Lastly, I had to set the SELinux context of the temporary and permanent uploads directory to httpd_sys_rw_content_t.

    [john.doe@server1 ~]# chcon --type httpd_sys_rw_content_t /var/www/html/uploads
    [john.doe@server1 ~]# chcon --type httpd_sys_rw_content_t /var/www/html/uploads/tmp
    

    After doing these things, I was then able to upload files using PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?