Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Create and Save a txt file to root directory

Tags:

php

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?

like image 928
Satch3000 Avatar asked Feb 13 '12 17:02

Satch3000


People also ask

How do I create a text file in root directory?

To do so, type cd followed by the path to the directory you want to create a file in and press Enter.. For example, you could type cd /home/username/Documents to navigate to your Documents folder. Alternatively, you can type cd / to navigate to the Root directory, or type cd ~ to navigate to your Home/User directory.

How can save file in specific folder in PHP?

php $target_Path = "images/"; $target_Path = $target_Path. basename( $_FILES['userFile']['name'] ); move_uploaded_file( $_FILES['userFile']['tmp_name'], $target_Path ); ?> when the file(image) is saved at the specified path...

Can PHP create a file?

PHP Create File - fopen()The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files. If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).


2 Answers

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); 
like image 122
Vigrond Avatar answered Oct 02 '22 10:10

Vigrond


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); ?> 
like image 24
cb1 Avatar answered Oct 02 '22 10:10

cb1