PHP 创建并保存一个 txt 文件到根目录

我试图创建并保存一个文件到我的网站的根目录,但我不知道它在哪里创建的文件,因为我看不到任何。而且,如果可能的话,我需要每次都覆盖这个文件。

这是我的代码:

$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);

如何将其设置为保存在根目录中?

305151 次浏览

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.

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.

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);
}

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);

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.

<?php
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation,"w");
$content = "Your text here";
fwrite($file,$content);
fclose($file);
?>

This question has been asked years ago but here is a modern approach using PHP5 or newer versions.

  $filename = 'myfile.txt'
if(!file_put_contents($filename, 'Some text here')){
// overwriting the file failed (permission problem maybe), debug or log here
}

If the file doesn't exist in that directory it will be created, otherwise it will be overwritten unless FILE_APPEND flag is set. file_put_contents is a built in function that has been available since PHP5.

Documentation for file_put_contents