Search code examples
phpfopen

Create text file failed, error: failed to open stream: No such file or directory


I tried to create file on my xampp directory :

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

I already created one php file, create.php

This is the code :

<?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);
?>

I ran the code and the file generated successfully, now what I want is to create a text file with name from variable :

This is what I tried :

<?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);

?>

I expected the file to be created with $filename as file name but an error on the browser page says:

Warning: fopen(id_1_29/10/2019_05:59:57.txt): failed to open stream: No such file or directory in D:\ProgramFile\xampp\htdocs\pg_api\create_1.php

(My error : here)

Anyone can tell me what's wrong with my code?


Solution

  • Windows do not allow special characters like /as a filename (it is not safe even in linux). Not just that, i will rather go with file name like id_1_29-10-2019_05-59-57.txt

    To achieve the above filename:

    $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);