Search code examples
phpapacherhelselinux

PHP file_put_contents returning 'Permission Denied' (Due to SELinux setting)


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:

<?php
$id=$_GET['id'];
$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


Solution

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

    The chcon command changes the SELinux context for files. However, changes made with the chcon command are not persistent across file-system relabels, or the execution of the restorecon command.

    -Rt are to change the type of the directory and its contents, httpd_sys_content_rw_t is to give apache write access

    source: https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/7/html/selinux_users_and_administrators_guide/sect-security-enhanced_linux-working_with_selinux-selinux_contexts_labeling_files

    Additional note

    ls -alZ *
    

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