【问题标题】:PHP Dynamic text file creationPHP 动态文本文件创建
【发布时间】:2013-05-17 01:48:27
【问题描述】:

我有这个代码

$ext = ".txt";
$filename = $namef.$ext;
if(!file_exists($filename))
{
$file = fopen($filename,"w");
fwrite($file, $privatekey);
fclose($file);
chmod($file,0777);
}

$namef 是输入到此程序中的任何名称。 但是,当我运行它时,我不断得到:

Unable to access (name_of_file).txt in something.php
Warning: fopen(name_of_file.txt) [function.fopen]: failed to open stream: No such file      or directory in something.php 
Warning: fwrite(): supplied argument is not a valid stream resource in ./something.php on line 79

Warning: fclose(): supplied argument is not a valid stream resource in ./something.php on line 80

Warning: chmod() [function.chmod]: Unable to access in ./something.php on line 81

我可以知道是否可以创建动态文本文件名吗?

谢谢

【问题讨论】:

  • 你在写文件夹里把cdmod设置为777了吗?
  • 请检查路径或至少提供您的代码和结构的真实数据以帮助其他人帮助您

标签: php file chmod


【解决方案1】:

回答您的问题。是的,可以使用“动态”文件名创建文件。

创建文件可以使用file_put_contents();

这个函数等同于依次调用fopen()、fwrite()和fclose()将数据写入文件。

如果文件名不存在,则创建文件。否则,现有文件将被覆盖,除非设置了 FILE_APPEND 标志。

如果您想将文本附加到已存在的文件中,请使用 FILE_APPEND 标志

FILE_APPEND如果文件filename已经存在,将数据追加到文件而不是覆盖它。

示例:

 $ext = ".txt";
 $filename = $namef.$ext;
 file_put_contents($filename, $privatekey, FILE_APPEND);

如果您想创建不存在或被覆盖的文件,请不要使用 FILE_APPEND 标志

示例:

 $ext = ".txt";
 $filename = $namef.$ext;
 file_put_contents($filename, $privatekey);

还要确保您在要执行文件操作的目录中拥有适当的权限。

【讨论】:

    【解决方案2】:

    编写这个简单的代码不需要 if 语句。它将以读写模式打开文件,如果文件不存在则自动创建,如果文件已存在则打开文件。

    $ext = ".txt";
    $filename = $namef.$ext;
    $file = fopen($filename,"w+");
    fwrite($file, $privatekey);
    fclose($file);
    chmod($file,0777);

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-24
    • 2014-06-21
    • 2013-11-12
    • 2018-01-23
    • 2020-01-16
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多