PHP创建并将txt文件保存到根目录

Sat*_*000 66 php

我正在尝试创建并将文件保存到我的网站的根目录,但我不知道它在哪里创建文件,因为我看不到任何...我需要提交文件,如果可能的话每次都被覆盖

这是代码:

$content = "some text here";
$fp = fopen("myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

如何将其设置为保存在根目录上?

Vig*_*ond 120

它在与脚本相同的目录中创建文件.试试这个.

$content = "some text here";
$fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
fwrite($fp,$content);
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

  • 请注意:这需要您正在写入的目录的写权限. (5认同)

cb1*_*cb1 14

如果您在Apache上运行PHP,那么您可以使用名为的环境变量DOCUMENT_ROOT.这意味着该路径是动态的,可以在服务器之间移动而不会弄乱代码.

<?php
  $fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
  $file = fopen($fileLocation,"w");
  $content = "Your text here";
  fwrite($file,$content);
  fclose($file);
?>
Run Code Online (Sandbox Code Playgroud)