2

In a PHP script , am getting below error when checked if a file is writable or not.

fopen(test.txt): failed to open stream: Permission denied 

Please see blow details:

  1. Apache service is running as user:apache, checked with:

    ps aux | egrep '(apache|httpd)'

2.Ownership of the file to be written and php script is changed to apache.

chown apache:apache test.txt chown apache:apache test.php 

3.File permissions changed to:777

chmod 777 test.txt chmod 777 test.php 

4.Tried setting: Already tried solutions provided in:fopen Permission denied on a file with 777 permissions

OS:Redhat Enterprise

Code:

<?php echo getmyuid().':'.getmygid(); echo "<br/>"; echo exec('whoami'); echo "<br/>"; $dst = 'test.txt'; echo $dst, file_exists($dst) ? ' exists' : ' does not exist<br/>', "<br/>\n"; echo $dst, is_readable($dst) ? ' is readable' : ' is NOT readable', "<br/>\n"; echo $dst, is_writable($dst) ? ' is writable' : ' is NOT writable<br/>', "<br/>\n"; $fh = fopen($dst, 'w'); if ( !$fh ) { echo ' last error: '; var_dump(error_get_last()); } 

Output:

33:33 apache test.txt exists test.txt is readable test.txt is NOT writable last error: array(4) { ["type"]=> int(2) ["message"]=> string(57) "fopen(test.txt): failed to open stream: Permission denied" ["file"]=> string(34) "/var/www/data/test2.php" ["line"]=> int(10) } 
5
  • is your folder in which these files are present ownd by apache too? Commented Mar 7, 2018 at 8:45
  • Write permissions are needed on the files / folders you wish to modify, read access is also required all the way to /. Without more info, can't say much more. Commented Mar 7, 2018 at 8:45
  • Permissions exists:chmod 777 test.txt chmod 777 test.php Commented Mar 7, 2018 at 8:47
  • 1
    Or perhaps your PHP isn't trying to open the file you think it's trying to open. Commented Mar 7, 2018 at 8:47
  • On some configurations 777 permissions actually block you from accessing or writing to the files. Are you able to read test.txt at all? (i.e. with wget/browser) Commented Mar 7, 2018 at 8:51

1 Answer 1

5

At last reached the answer myself! I had to modify the SELinux configuration with chon command and apply permission as:httpd_sys_rw_content_t

chcon -R -h -t httpd_sys_rw_content_t /var/www/data/ 

along with:

chown -R apache:apache/var/www/data/ chmod -R a+rX /var/www/data/ 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.