php fopen() 不工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7317114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fopen() not working
提问by Tim Specht
I'm want to read a simple string from a text file which is around 3-4 mb but fopen() fails ("can't open file" from die() is called). Here's the code:
我想从大约 3-4 mb 的文本文件中读取一个简单的字符串,但 fopen() 失败(调用 die() 中的“无法打开文件”)。这是代码:
clearstatcache();
$fh = fopen("/my/path/to/file.txt", "r") or die("can't open file");
$sql = fread($fh,filesize("/my/path/to/file.txt"));
回答by pb149
Have you firstly checked to see if the file exists?
你有没有先检查文件是否存在?
if (!file_exists("/my/path/to/file.txt") {
die('File does not exist');
}
clearstatcache();
$fh = fopen("/my/path/to/file.txt", "r") or die("can't open file");
$sql = fread($fh,filesize("/my/path/to/file.txt"));
回答by Your Common Sense
you have to add to your code this line
您必须将此行添加到您的代码中
error_reporting(E_ALL);
and ALWAYS keep this line in ALL your codes
并始终在您的所有代码中保留这一行
and also this line
还有这条线
ini_set('display_errors',1);
and keep this line only on development server.
while on the production it should be changed to
并仅在开发服务器上保留此行。
而在生产中,它应该改为
ini_set('display_errors',0);
ini_set('log_errors',1);
By doing this you will not need Stackoverflow assistance in reading the now obvious error messages.
通过这样做,您将不需要 Stackoverflow 帮助来阅读现在明显的错误消息。
回答by John
In your FTP file permissionstend to need to be 646
(or -rw-r--rw-
), not777
(always ignore those kind of comments). You want to give a key to someone you trust, setting permissions to 777
is like giving a copy of your key to everyone.
在您的 FTP文件中,权限往往需要是646
(或-rw-r--rw-
),而不是777
(总是忽略那些注释)。你想给你信任的人一把钥匙,设置权限777
就像给每个人一份你的钥匙。
回答by YuS
Try to output system errors in die or try use try…catch. Also turn on php errors while development. Also check if file is readable before open it.
尝试在 die 中输出系统错误或尝试使用 try...catch。还要在开发时打开 php 错误。在打开文件之前还要检查文件是否可读。
Most common issues are: file does not exists (or just incorrect path provided?), there is not enough permissions to read this file.
最常见的问题是:文件不存在(或只是提供的路径不正确?),没有足够的权限来读取此文件。
回答by paxdiablo
Change that second line to:
将第二行更改为:
$fh = fopen("/my/path/to/file.txt", "r") or die($php_errormsg);
and see what it outputs as the cause.
并查看它输出的原因。