我试图在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
任何人都可以告诉我我的代码有什么问题吗?
答案 0 :(得分:0)
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);