0

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
kpp
  • 800
  • 2
  • 11
  • 27

1 Answers1

2

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/.

smassey
  • 5,875
  • 24
  • 37
  • 1
    allowing a guest to write to a folder is usually a serious sevurity breach. if the coder does not know this, then chances are that he/she will not be able to create a secure environment and should not open write permissions to guest user. – tony gil Apr 18 '14 at 11:31
  • 1
    @tonygil please advise on how to setup an environment with the OPs given requirements (writing files to disk) *without* giving write permissions to the directory? This is not a security flaw, it's the only way. – smassey Apr 18 '14 at 12:24
  • well since it is disadviced to change these settings and its supposed to be public i've decided to use the mailserver instead and mail the data. – kpp Apr 22 '14 at 06:52