Get meaningful information when fopen() fails (PHP/suPHP)

时间秒杀一切 提交于 2019-12-18 07:43:08

问题


How do I get something more meaningful than 'FALSE' when I can't open a file.

$myFile = "/home/user/testFile.txt"; 
$fh = fopen($myFile, 'w') or die("can't open file");

When I use the die statement, can't open file is returned to the client, and it is almost useless. If I remove it, no error is raised. If I return $fh it is FALSE. I tried both local file name and absolute file name. My index.html file is in one of the sub folders of my hole folder. Furthermore, I am using suPHP with the folder I am trying to write to having a permission of 0755 (suPHP requires this for all folders).

How do I figure out why there was a problem, or at least query it before trying to open the file.


回答1:


fopen should raise an E_WARNING if it fails. See error_get_last or set_error_handler(*) to catch it. Other than that you can use file_exists and is_readable to check whether the file is missing or there's another (probably permission-related) problem.

(*) I consider it good practice to always set an error handler that turns all PHP errors into exceptions.




回答2:


Use error_get_last() to catch the (supressed) errors in php:

$f = @fopen("x", "r") or die(print_r(error_get_last(),true));


来源:https://stackoverflow.com/questions/8018693/get-meaningful-information-when-fopen-fails-php-suphp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!