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?
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.
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...
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).
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); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With