Php can open file error

PHP: fopen() Permission denied

where is the problem? Thanks a lot!I have found the problem,I use FC13,because of the protect of SELinux,some action is denied.So, I just need to get rid of the protect.

Is php running as jt user? If the file you want to open is owned by some other user, that might be a problem, too.

oh. I found the problem. I use FC13,because of the protect of SELinux, some action is denied. Thanks! 🙂

10 Answers 10

This issue can also be a result of having SELinux enabled. This can be solved using:

chown -R apache:apache /var/www/html/directory_to_write chcon -R -t httpd_sys_content_t /var/www/html/directory_to_write chcon -R -t httpd_sys_rw_content_t /var/www/html/directory_to_write 

is most likely looking in another directory

I have been receiving the same error «failed to open stream. permission denied»when trying to write a file on the server using PHP. I tried everything on the internet to fix the error. I changed ownership of the files,directories and sub-directories on the server to «apache», I did a chmod 777 on all the files, directories, sub-directories, I ran restorecon -R , I ran chcon unconfined_u:object_r:httpd_user_content_t:s0 on all the files, but the only thing that seemed to work is turning SELinux off completely.

I finally resolved the issue. The problem lay in the boolean parameters used by SELinux. I performed the following command to get a list of all the booleans related to httpd.

This gave a list of about 36 parameters.

I painfully went and turned on every boolean using the setsebool command until the «failed to open stream. permission denied» error went away.

When I turned «on» the httpd_unified boolean, the error went away!! When I turned it «off», the error came back!!

Источник

PHP: fopen error handling

and then the method gives it back as image. But when fopen() fails, because the file did not exists, it throws an error:

This is coming back as json, obviously. The Question is now: How can i catch the error and prevent the method from throwing this error directly to the client?

i tried something like this if($fp = fopen(‘uploads/Team/img/’.$team_id.’.png’, «rb»))< throw this->createNotFoundException(‘No image found for id ‘.$team_id); > but it didnt worked.

4 Answers 4

You should first test the existence of a file by file_exists().

try < $fileName = 'uploads/Team/img/'.$team_id.'.png'; if ( !file_exists($fileName) ) < throw new Exception('File not found.'); >$fp = fopen($fileName, "rb"); if ( !$fp ) < throw new Exception('File open failed.'); >$str = stream_get_contents($fp); fclose($fp); // send success JSON > catch ( Exception $e ) < // send error message if you can >

or simple solution without exceptions:

$fileName = 'uploads/Team/img/'.$team_id.'.png'; if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ) < $str = stream_get_contents($fp); fclose($fp); // send success JSON >else < // send error message if you can >

FWIW This can still throw OP’s original warning if by chance $fileName is deleted in the nanosecond between fopen . Which is predominantly reproducible on high-traffic sites. Probably the only scenario where I’d be ok with silencing anything: $fp = @fopen(. ); if (!$fp) throw.

Читайте также:  ProgressLoader

Also, file_exists is not usable when using non-file resources. If all is required is hiding the error, prefixing fopen with @ ( @fopen ) already helps, but it does not give you the error.

You can use the file_exists() function before calling fopen().

if(file_exists('uploads/Team/img/'.$team_id.'.png') < $fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb"); $str = stream_get_contents($fp); fclose($fp); >

Generically — This is probably the best way to do file-io in php (as mentioned by @Cendak here)

$fileName = 'uploads/Team/img/'.$team_id.'.png'; if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false )< $str = stream_get_contents($fp); fclose($fp); // send success JSON >else < // send an error message if you can >

But it does not work with PHP 7.3, these modifications do,

if(file_exists($filename) && ($fp = fopen($filename,"r") !== false))< $fp = fopen($filename,"r"); $filedata = fread($fp,filesize($filename)); fclose($fp); >else

the error is clear: you’ve put the wrong directory, you can try what you whant but it’ll not work. you can make it work with this:

  1. take your file and put it in the same folder of your php file (you’ll be able to move it after don’t worry, it’s about your error) or on a folder «higher» of your script (just not outside of your www folder)
  2. change the fopen to (‘./$team_id.’png’,»rb»);
  3. rerun your script file

don’t forget this : you can’t access a file that is’nt in your «www» folder (he doesn’t found your file because he give you her name: the name come from the $team_id variable)

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

PHP fopen can’t open file but still writes to it

This is driving me crazy. I have a standard routine to write log files that has worked so well that I have almost forgotten what was in the code. Transferred it into a new project, made one change and it is behaving really weirdly. The error messages say that fopen() is failing to open the log file, however the entries are still being written in the log file. I don’t like having errors or warnings of any description so I do not intend to ignore this error just because it appears to be working despite the error. The change I made was in the way $_SESSION[‘base_dir_prefix’] was set. In previous projects, that had been set in the context of the home page, and set to the absolute path to that directory. This had a weakness where you couldn’t go straight to a page without going through index.php. I couldn’t do that in this project, so I set it to a relative path — e.g. $_SESSION[‘base_dir_prefix’] = «../» ; As far as I can see, the prefix is set correctly. In fact, as far as I can see, everything is set correctly, but there is obviously a needle in there somewhere that will need another pair of eyes to see! One of my biggest questions is, if fopen() is failing to open the file, then why is is being written to? Exhibit 1 — source code of the actual writelog function. Note that the echo statements are purely for debug purposes and are not part of normal execution.

function writelog($str=" ") < if (isset($_SESSION['base_dir_prefix'])) < $prepend = $_SESSION['base_dir_prefix'] ; >else < $prepend = $_SERVER['DOCUMENT_ROOT'] ; >if ( substr($prepend, -1, 1) <> DIRECTORY_SEPARATOR ) < $prepend .= DIRECTORY_SEPARATOR ; >$fname = $prepend."log/log.txt" ; $mode = "a" ; echo getcwd(). "\n" ; // debug code echo $fname." Files exists?:".file_exists($fname) ."\n"; echo $str."\n" ; $fp = fopen($fname, $mode) ; fwrite( $fp, date("Y-m-d H:i:s").": " ) ; fwrite( $fp, $str."\n" ) ; fclose( $fp ) ; > 
 $u->writelog ("SA OLU entering Option List Users function") ; $u->writelog ("Current dir:".getcwd()." ") ; $usr_list = array(array( "None", "None") ); $sc->user_list($usr_list) ; $i = 0 ; $res = "" ; $actv_flag = strtoupper($active) ; if ($usr_list[0][0] != "None" ) < while ($i < count($usr_list)) < if ((bool)$usr_list[$i][2] == true && $actv_flag == "YES") //only active users < $i++ ; continue ; >$res .= sprintf( "  \n", $usr_list[$i][0], $usr_list[$i][1], $usr_list[$i][0] ); $i++ ; > > else < $res = sprintf( " \n" ) ; > $u->writelog ("SA OLU leaving Option List Users function") ; 

Exhibit 3 — the log file itself. Entries created by exhibit 1. Note that the timestamp on this file is 1 hour later than actual time. Not sure why and since I am the only person who looks at this file, I have not been overly concerned.

2014-11-21 16:29:58: SA OLU entering Option List Users function 2014-11-21 16:29:58: Current dir:/srv/www/dev/gillies/security 2014-11-21 16:29:58: SA OLU leaving Option List Users function 2014-11-21 16:29:58: SA OLU entering Option List Users function 2014-11-21 16:29:58: Current dir:/srv/www/dev/gillies/security 2014-11-21 16:29:58: SA OLU leaving Option List Users function 2014-11-21 16:29:58: SA OLU entering Option List Users function 2014-11-21 16:29:58: Current dir:/srv/www/dev/gillies/security 2014-11-21 16:29:58: SA OLU leaving Option List Users function 
[Fri Nov 21 15:29:25.047732 2014] [:error] [pid 20588] [client 192.168.0.19:62116] PHP Warning: fwrite() expects parameter 1 to be resource, boolean given in /srv/www/dev/gillies/php/utilities.php on line 72 [Fri Nov 21 15:29:25.047746 2014] [:error] [pid 20588] [client 192.168.0.19:62116] PHP Warning: fclose() expects parameter 1 to be resource, boolean given in /srv/www/dev/gillies/php/utilities.php on line 73 [Fri Nov 21 15:29:58.721627 2014] [:error] [pid 17084] [client 192.168.0.19:62141] PHP Warning: fopen(../log/log.txt): failed to open stream: No such file or directory in /srv/www/dev/gillies/php/utilities.php on line 69 [Fri Nov 21 15:29:58.721698 2014] [:error] [pid 17084] [client 192.168.0.19:62141] PHP Warning: fwrite() expects parameter 1 to be resource, boolean given in /srv/www/dev/gillies/php/utilities.php on line 71 [Fri Nov 21 15:29:58.721711 2014] [:error] [pid 17084] [client 192.168.0.19:62141] PHP Warning: fwrite() expects parameter 1 to be resource, boolean given in /srv/www/dev/gillies/php/utilities.php on line 72 [Fri Nov 21 15:29:58.721720 2014] [:error] [pid 17084] [client 192.168.0.19:62141] PHP Warning: fclose() expects parameter 1 to be resource, boolean given in /srv/www/dev/gillies/php/utilities.php on line 73 

Exhibit 5 — a snippet of the generated html code showing the results of the echo. Entries created by Exhibit 2. Again this is only for diagnostic purposes and is not part of the production file.

 /srv/www/dev/gillies/security ../log/log.txt Files exists?:1 SA OLU entering Option List Users function /srv/www/dev/gillies/security ../log/log.txt Files exists?:1 Current dir:/srv/www/dev/gillies/security /srv/www/dev/gillies/security ../log/log.txt Files exists?:1 SA OLU leaving Option List Users function  
darryl@thedoctor:/srv/www/dev/gillies/log$ pwd /srv/www/dev/gillies/log darryl@thedoctor:/srv/www/dev/gillies/log$ ls -l total 8 -rw-rw-rw- 1 www-data www-data 4743 Nov 21 15:33 log.txt 

Источник

Читайте также:  Матрица двумерный массив python

Cannot open file for reading PHP

I am trying to open a file but for some reason I cannot even though the file is there and even has 777 permission. The code is the following:

$fileatt = "/opt/lampp/htdocs/a.pdf"; echo "File size is ".filesize($fileatt)."
"; if (file_exists($fileatt)) < echo "The file ".$fileatt." exist
"; $file = fopen($fileatt, ‘rb’); if ($file == false) < echo "Could not open the file !"; >> else < echo "The file ".$fileatt." does NOT exist
"; >
File size is 1252121 The file /opt/lampp/htdocs/a.pdf exist Could not open the file ! 

What’s the file permissions on the file? if its not an overly importany file try chmod 0777 a.pdf and failing that, check to see if fopen can actually open a pdf 😛

Lesson: don’t copy-paste random code from the web into your app, especially if the page author uses fancy quotation marks.

1 Answer 1

You don’t have error reporting properly set. there are 2 things to remember.

  1. error reporting level. set by error_reporting ini directive or error_reporting() function. should ALWAYS be at E_ALL or higher.
  2. error messages destination.
    • on a development server it should be display
    • on a live server it should be a log file

Thus, for a quick solution, put these 2 lines at the top of your script

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

but later set up these settings as a permanent ones for the whole site (according to the server state)

once you done it, you will have an answer to your question.
Note that you will have not a mere guess from the fellow stackoverflowers, but exact explanation of the matter from the system itself.

Читайте также:  Java initialize arraylist with one element

Источник

Оцените статью