php won't create file

2019-08-27 17:41发布

问题:

So I tried creating a file with php using fopen(file, w). but it returns an error. However this is only on the server side, it works fine on when I run it on localhost(XAMPP)

Code is as follows

function createdatafile(){
//Rolls a random number which will be the file name.
$x = rand(0, 9999999);
$file = "Datafiles/".$x.".csv";
if(!file_exists($file)){
    $nfile = fopen($file, "w") or die("cannot create file: $file ");//fails 
    //createdata() just returns a string. However this doesnt even get executed.
    fwrite($nfile, createdata());
    fclose($nfile);
}else{
    //calls itself for another roll if the file already existed.
    $this->createdatafile();
}}

This piece of code runs on localhost but not on the server. I tried a lot of different things and solutions given by previous questions like this, which all didnt work. But after trying to append to an existing file instead it was quite clear it could find the file so it wasn't the filepath that was wrong. It simply refuses to open the file. So my folder structure is as follows.

/phpscripts.php
/Datafiles/Data.csv
/files/images.png <--- tried moving the file here didn't work either.

The only conclusion I can draw from this is that the server doesnt allow php to write and open files, but I dont know why or how to change this. So does anyone know how to solve this problem.

回答1:

I'd assume this is a user permissions error. Make sure your httpd user has write permission to the file/directory you're trying to write to. To be certain though, you should enable logging and check the warning php throws when attempting to open($f, 'w').

Again assuming this is a permission error and that this is a linux server, you should do a chown httpduser:httpduser /Datafiles/ and then a chmod u+w /Datafiles/ or chmod g+w /Datafiles/.



标签: php file fopen