用PHP创建文本文件?

hay*_*isa 3 php text fopen fwrite chmod

我正在尝试使用PHP来创建文本文件,但我不断收到"无法打开文件"错误.谁能告诉我我做错了什么?

chmod('text.txt', 0777);

$textFile = "text.txt";
$fileHandle = fopen($textFile, 'w') or die("can't open file");
$stringData = "Hello!";
fwrite($fileHandle, $stringData);
fclose($fileHandle);
Run Code Online (Sandbox Code Playgroud)

Sam*_*ook 10

您将无法找到chmod()不存在的文件.您必须对父文件夹具有写权限才能允许Apache(如果您正在运行Apache,否则允许您编写文件的用户)作为用户在该文件夹内写入(无论是根目录还是子文件夹) .

此外,您应该在文件写入时执行一些错误处理:

<?php
if($fh = fopen('text.txt','w')){
    $stringData = "Hello!";
    fwrite($fh, $stringData,1024);
    fclose($fh);
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!