首页 > 解决方案 > 创建文本文件失败,错误:无法打开流:没有这样的文件或目录

问题描述

我试图在我的 xampp 目录上创建文件:

path : D:\ProgramFile\xampp\htdocs\pg_api

我已经创建了一个 php 文件,create.php

这是代码:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

我运行了代码并成功生成了文件,现在我想要创建一个名称来自变量的文本文件:

这是我尝试过的:

<?php

$currentdate = date('d/m/Y_H:i:s');
$id = 1;
$filename = "id_".$id."_".$currentdate.".txt";

$myfile = fopen($filename, "w") or die("Unable to open file!");

$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

?>

我希望该文件以$filename文件名创建,但浏览器页面上的错误显示:

警告:fopen(id_1_29/10/2019_05:59:57.txt):无法打开流:D:\ProgramFile\xampp\htdocs\pg_api\create_1.php 中没有这样的文件或目录

(我的错误:这里

谁能告诉我我的代码有什么问题?

标签: phpfopen

解决方案


Windows 不允许像/文件名这样的特殊字符(即使在 linux 中也不安全)。不仅如此,我宁愿使用像这样的文件名id_1_29-10-2019_05-59-57.txt

实现上述文件名:

$currentdate = date('d-m-Y_H-i-s');
$id = 1;
$filename = "id_".$id."_".$currentdate.".txt";

$myfile = fopen($filename, "w") or die("Unable to open file!");

$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);

推荐阅读