2017-02-16 21:44 阅读 91

PHP file_put_contents返回'Permission Denied'(由于SELinux设置)

I know this is a common issue but I haven't been able to single out the problem for my specific use case, so bear with me.

I have a simple PHP script send_id which simply sends an ID number and saves it to a TXT file on my RHEL server running Apache 2.4.6 with PHP 5.4.

The error message: Warning: file_put_contents(/var/www/html/id.txt): failed to open stream: Permission denied in /var/www/html/send_id.php on line 6 '1' written to server

The PHP script itself:

$stringData = "$id";
$file = file_put_contents('/var/www/html/id.txt', $stringData.PHP_EOL , FILE_APPEND |LOCK_EX);
echo "'$stringData' written to server";

chmodding to 777 didn't do anything. Additionally, I checked to see ownership rights and noticed that the id.txt file is owned by the root user at both user/group level, and PHP is being run at root level.

Anyone have any suggestions? If its any help, this seems to have happened after a yum update

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douju1280 douju1280 2017-02-16 22:09

    I resolved this issue by simply running chcon -Rt httpd_sys_content_rw_t on the directory where my troubled PHP script lived in.

    Additional note

    ls -alZ *

    The -Z switch will work with most utilities to show SELinux security contexts

    点赞 评论 复制链接分享
  • drr25281 drr25281 2017-02-16 21:46

    Try changing the owner of the folder and the file to (chown) to "www-data" or to "www-data:www-data" and see if it changes anything...

    点赞 评论 复制链接分享
  • doutuo7126 doutuo7126 2017-02-17 01:19

    Use a relative file path from, Apache's "DOCUMENT ROOT" to reference files in PHP. It's Apache's permissions that matter, and for security reasons it is coded to inhibit access to files outside of DOCUMENT_ROOT.. (yes even though your path leads within it, Apache is blocked as soon as it sees the path starts with "/VAR" ..

    Assuming this PHP script is in the same directory as id.txt file , just use

    $file = file_put_contents('./id.txt', $str...      

    Or if the txt file was in a sub-directory

    file_put_contents('./sub-dir/id.txt', $str... 

    Not only is it secure, it's a lot shorter to type too.

    点赞 评论 复制链接分享