PHP Create and Save a txt file to root directory

后端 未结 3 555
情书的邮戳
情书的邮戳 2020-11-28 04:47

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 overwri

相关标签:
3条回答
  • 2020-11-28 05:03

    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);
    }
    
    0 讨论(0)
  • 2020-11-28 05:07

    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);
    ?>
    
    0 讨论(0)
  • 2020-11-28 05:10

    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);
    
    0 讨论(0)
提交回复
热议问题