无法在 php 中打开文件
代码在 fopen() 处卡住:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$fp = fopen("/path/to/file/some_file.txt","a") or die("can't open file");
fwrite($fp,"some text");
fclose($fp);
?>
生成的网页显示:
“警告:fopen(/path/to/file/some_file.txt) [function.fopen]: 无法打开流:/var/www/ 中的权限被拒绝html/test.php 第 5 行 无法打开文件”
我尝试使用文件权限,但无济于事。我使用 chown apache:apache some_file.txt 更改了用户/组,并使用 chmod 755 更改了权限some_file.txt 以下是 ls -l /path/to/file/ 的相关结果:
-rwxr-xr-x 1 apache apache 0 Apr 12 04:16 some_file.txt
The code chokes at fopen():
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$fp = fopen("/path/to/file/some_file.txt","a") or die("can't open file");
fwrite($fp,"some text");
fclose($fp);
?>
And the resulting web page says:
"Warning: fopen(/path/to/file/some_file.txt) [function.fopen]: failed to open stream: Permission denied in /var/www/html/test.php on line 5
can't open file"
I tried to play with the file permissions, but to no avail. I changed the user/group with chown apache:apache some_file.txt
and changed permissions with chmod 755 some_file.txt
. Here is the relevant result of ls -l /path/to/file/
:
-rwxr-xr-x 1 apache apache 0 Apr 12 04:16 some_file.txt
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要忘记,即使 Apache 已被授予读取该文件的权限,您也必须授予 Apache 对所有父目录的访问权限。
都需要至少授予 Apache '读取' 权限。
Don't forget that even if Apache's been granted permissions to read the file, you also have to grant Apache access to ALL of the parent directories.
all need to grant Apache at least 'Read' permission.
您确定
apache
是实际运行 PHP 的用户吗?`并且:确保
apache
用户可以访问some_file.txt
文件系统,并且它没有被some_file.txt
上面目录的某些访问限制阻止。You're sure that
apache
is the user actually running your PHP?`And: make sure that the
apache
user can reachsome_file.txt
in the file system and that it isn't blocked by some access restriction on directories abovesome_file.txt
.在修复错误之前,最好知道要修复哪个错误。
在脚本顶部添加这些行,然后重试
PHP 会告诉你,问题是什么
Before you go to fix an error, it would be nice to know, which error to fix.
Add these lines at the top of your script and then try again
PHP will tell you, what is the problem
"a"
表示要追加,需要与写入相同的权限。每个人至少需要 666 的写入权限。或者将文件所有者更改为服务器组(Ubuntu 上的 www-data)。并设置所需的权限。
这是权限计算器
如果这没有帮助,请检查
安全模式也是如此。
"a"
means you want to append, the same permissions as for write are needed.You need at least 666 permissions to write by everybody. Or change file owner to server group (www-data on Ubuntu). And set the required permission.
Here is Permission calculator
If this does not helps, check the
safe_mode
too.