PHP 创建一个txt文件并保存到根目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9265274/
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
PHP Create and Save a txt file to root directory
提问by Satch3000
I am trying to create and save a file to the root directory of my site, but I don't know where its creating the file as I cannot see any. And, I need the file to be overwritten every time, if possible.
我正在尝试创建一个文件并将其保存到我网站的根目录,但我不知道它在哪里创建文件,因为我看不到任何文件。而且,如果可能的话,我每次都需要覆盖该文件。
Here is my code:
这是我的代码:
$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
How can I set it to save on the root?
如何将其设置为保存在根目录上?
回答by Vigrond
It's creating the file in the same directory as your script. Try this instead.
它在与脚本相同的目录中创建文件。试试这个。
$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
回答by cb1
If you are running PHP on Apache then you can use the enviroment variable called DOCUMENT_ROOT
. This means that the path is dynamic, and can be moved between servers without messing about with the code.
如果您在 Apache 上运行 PHP,那么您可以使用名为DOCUMENT_ROOT
. 这意味着路径是动态的,可以在服务器之间移动而不会弄乱代码。
<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>
回答by Farray
fopen()
will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.
fopen()
将在与执行命令的文件相同的目录中打开一个资源。换句话说,如果您只是运行文件 ~/test.php,您的脚本将创建 ~/myText.txt。
This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.
如果您使用任何 URL 重写(例如在 MVC 框架中),这可能会有点令人困惑,因为它可能会在包含根 index.php 文件的任何目录中创建新文件。
Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:
此外,您必须设置正确的权限,并且可能需要在写入文件之前进行测试。以下将帮助您调试:
$fp = fopen("myText.txt","wb");
if( $fp == false ){
//do debugging or logging here
}else{
fwrite($fp,$content);
fclose($fp);
}