PHP Create and Save a txt file to root directory

Php

Php Problem Overview


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?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSatch3000View Question on Stackoverflow
Solution 1 - PhpVigrondView Answer on Stackoverflow
Solution 2 - Phpcb1View Answer on Stackoverflow
Solution 3 - PhpFarrayView Answer on Stackoverflow
Solution 4 - PhpGazmend SahitiView Answer on Stackoverflow