无法使用php创建文本文件

无法使用php创建文本文件,php,Php,我对php非常陌生。我正在尝试编写一个小脚本,它编写一个小文本文件,然后读取同一个文件并在屏幕上显示其内容。但是脚本总是会死掉,我会收到错误消息“error:cannotcreatefile!” 我正在我的家庭CentOS沙箱中运行此代码 <?php ////////////////////////////////////////////////////////////// // http://inpics.net/tutorials/php/files3.html // PHP Date

我对php非常陌生。我正在尝试编写一个小脚本,它编写一个小文本文件,然后读取同一个文件并在屏幕上显示其内容。但是脚本总是会死掉,我会收到错误消息“error:cannotcreatefile!”

我正在我的家庭CentOS沙箱中运行此代码

<?php
//////////////////////////////////////////////////////////////
// http://inpics.net/tutorials/php/files3.html
// PHP Date function:
// http://www.w3schools.com/php/func_date_date.asp
// date("d/m/Y H:i:s")
//////////////////////////////////////////////////////////////
// Define filename
$myfilename = (date("dMY").".txt");
print "<p>Filename: '<b>$myfilename</b>'</p>";
// Define text
$MyText = 'Some text... blah, blah, blah...';
print "<p>This text should be on the file:'<b>$MyText</b>'</p>";
//////////////////////////////////////////////////////////////
// Open file for write:
//
$handle = fopen($myfilename, 'w') or die('ERROR: Can not create file!');
fwrite($handle,$MyText,2048);
fclose ($handle);
//////////////////////////////////////////////////////////////
// The code below works, following this example:
// http://stackoverflow.com/a/9861638/4321334
$handle = fopen($myfilename, 'r') or die('ERROR: Can not open file!');
print "<p>Now, let's read the file: <b>$myfilename</b> </p>";
$FileContents = fread($handle,filesize($myfilename));
fclose ($handle);
print "<p>The file <b>'$myfilename'</b> have the following text on it:</p>";
print "<p>$FileContents</p>";
print "<p>Happy ending!</p>";
exit;
?>

我建议使用
file\u put\u contents
,它实现了类似的目标,它只是
fwrite
的包装器

file_put_contents($myfilename, $MyText);

…是否允许脚本写入正在运行的目录?首先检查您的操作系统的目录权限。您还可以提供一个完整的限定路径,而不仅仅是一个文件名,来指定文件的创建位置。哦,不需要括号<代码>$myfilename=date(“dMY”).“.txt”可以。在我的windows xampp中工作正常,请在CentOS中检查应用程序根目录/文件权限(可能是应用程序的注销权限)。您可以使用“ls-la”通过终端/命令行进行检查,或者您可以添加完整的文件权限来进行测试,如chmod-R 777目录_name@xph:该脚本正在/var/www/html/文件夹中运行,该脚本将由网页调用。@xph:感谢方括号建议。出于某些疏远的原因,您建议的行仅创建一个“空”文件,无论文件或文件夹权限如何。从控制台运行也会执行相同的操作。@Marco LuisSALCEDOTOVAR检查此项