apache fopen 创建不存在的新文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2557133/
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 create new file that not exists
提问by VolkerK
I am trying to either create a file that doesn't exist or write to a file that already does.
我正在尝试创建一个不存在的文件或写入一个已经存在的文件。
within a php file I am trying this:
在一个 php 文件中,我正在尝试这个:
$file = fopen("data.txt", "a");
fwrite($file, "\n" . $name); fwrite($file, "," . $lastname);
fwrite($file, "," . $email);
fclose($file);
$file = fopen("data.txt", "a");
fwrite($file, "\n" . $name); fwrite($file, "," . $lastname);
fwrite($file, "," . $email);
fclose($file);
I am running Apache under windows Xp and have no luck that the file "data.txt" is being created. The docs say that adding the a parameter should create a file with a name mentioned in the fist parameter (data.txt). what am I doing wring here?
我在 Windows Xp 下运行 Apache 并且没有运气创建文件“data.txt”。文档说添加 a 参数应该创建一个文件,其名称在 fist 参数 (data.txt) 中提到。我在这里干什么呢?
Thanks in advance undersound
提前致谢
回答by VolkerK
Let's add some tests and debug output to your code
让我们向您的代码添加一些测试和调试输出
echo 'cwd is: ', getcwd(), "<br />\n";
echo 'target should be: ', getcwd(), "/data.txt <br />\n";
echo 'file already exists: ', file_exists('data.txt') ? 'yes':'no', "<br />\n";
$file = fopen("data.txt", "a");
if ( !$file ) {
die('fopen failed');
}
$c = fwrite($file, "\n$name,$lastname,$email");
fclose($file);
echo $c, ' bytes written';
回答by Konrad Neuwirth
Are you looking into that directory the script also considers it's current one? Does your apache process have write permission there? Does the error log mention any failing command in this?
您是否正在查看该脚本还认为它是当前目录的目录?你的 apache 进程在那里有写权限吗?错误日志中是否提到了任何失败的命令?
回答by Ben
Remember that the file is created in the directory where the main thread of the process is running. This meas that if the "main" program is in A/ and it includes a functions file from B/ a function in B that creates a file in "." creates it in A/ not in B/
请记住,该文件是在进程的主线程运行的目录中创建的。这意味着如果“主”程序在 A/ 中,并且它包含来自 B/ 的函数文件,则 B 中的函数在“.”中创建文件。在 A/ 中创建它而不是在 B/
Also, there's no need to call the fwrite function 3 times, you can do
此外,没有必要调用 fwrite 函数 3 次,你可以这样做
fwrite($file, "\n" . $name . ", " . $lastname . ", " . $email);
回答by red
If appending to an already existing data.txt works, but not creating a file that does not yet exist, it would most likely mean that the files permissions allow writing into it, but the folder the file resides in is not owned by Apache, and as such, it cannot create files there.
如果附加到已经存在的 data.txt 有效,但不能创建尚不存在的文件,则很可能意味着文件权限允许写入其中,但文件所在的文件夹不归 Apache 所有,并且因此,它无法在那里创建文件。

