简体   繁体   中英

Error while writing to a file in php

While testing the following code on my local machine, no error was reported. But after testing it on our server at work, I got the following strange error: php is not writing files on the server.

code I am using :

 $myfile = fopen( "results/co".$a[$i].".txt", "w") or die("Unable to open file!");
 fwrite($myfile,"some text");
 fclose($myfile);

So no file is created in this case. when I try to replace the file name "results/co".$a[$i].".txt" with its value : "results/co00112test.txt" :

 $myfile = fopen( "results/co00112test.txt", "w") or die("Unable to open file!");
 fwrite($myfile,"some text");
 fclose($myfile);

it works just fine.

I also tried the following:

 $name = "results/co".$a[$i].".txt";
 $myfile = fopen( $name, "w") or die("Unable to open file!");
 fwrite($myfile,"some text");
 fclose($myfile);

yet with no hope.

What could be the reason for this error ?

If your code works fine when you're putting some static filename, it's obvious that your variable $a[$i] is wrong.

You can proceed that way to debug it :

$name = "results/co".$a[$i].".txt";
var_dump($name);

The name should show something weird, and will tell you what's happening to your file.

it might be all because of permissions. Your php user don't have permission to folder, where you want to create file or don't have permission to file, which you are trying to edit (if file is already there).

You can read full article about permissions here (it's about ubuntu, but it doesn't really matter which OS): https://help.ubuntu.com/community/FilePermissions

you can try permission 644 or if it's not working you can use 777. 644 is more safe, because only the owner of the file will be able to edit it, not any user of your OS.

you can change permissions to folder and all files/folders in it like this:

chmod -R 644 /path/to/folder/

I think 644 is standard for files and 755 for directories.

you can change owner of the file/folder like this:

chown name_of_user:name_of_group /path/to/folder

Your file name is starting with double zero char so it might be an issue.

this will not work :

$number = 112;
$file_name = "results/co".$number."test.txt";

this should work :

$number = 112;
$number_pad = str_pad($number, 5, '0', STR_PAD_LEFT);
$file_name = "results/co".$number_pad."test.txt";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM