PHP Create and save txt file to root directory

I am trying to create and save a file in the root directory of my site, but I do not know where it creates the file, since I do not 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 to set up root saving?

+65
php
Feb 13 '12 at 17:45
source share
3 answers

Creates a 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); 
+119
Feb 13 2018-12-12T00:
source share

If you use PHP on Apache, you can use an environment variable called DOCUMENT_ROOT . This means that the path is dynamic and can move between servers without delving into the code.

 <?php $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt"; $file = fopen($fileLocation,"w"); $content = "Your text here"; fwrite($file,$content); fclose($file); ?> 
+14
Feb 13 '12 at 17:56
source share

fopen() will open the resource in the same directory as the file executing the command. In other words, if you just run the ~ / test.php file, your script will create the ~ / myText.txt file.

This can be a bit confusing if you use URL rewriting (for example, in MVC), as this will most likely create a new file in any directory that contains the root.php file.

In addition, you must have the correct permissions set and you can test them before writing to a file. The following will help you debug:

 $fp = fopen("myText.txt","wb"); if( $fp == false ){ //do debugging or logging here }else{ fwrite($fp,$content); fclose($fp); } 
0
Feb 13 '12 at 17:53
source share



All Articles