0

I am using version 5.1.6 and am observing a strange issue. I cannot create and write to a file from the script whereas if I explicitly create a file and then run the script it writes data.

Am I missing something obvious in here?

The test code I am trying is:

$message = "Test";
$myFile = "testFile.txt";
if (file_exists($myFile)) {
  $fh = fopen($myFile, 'a');
  fwrite($fh, $message."\n");
} else {
  chmod("/path/to/dir/*", 0755); //updated code
  $fh = fopen($myFile, 'w')  or die("Cannot open file \"$myFile\"...\n");
  fwrite($fh, $message) ;
}
fclose($fh);

CONCLUSION: Thanks for the responses everybody. It is a permission issue. I changed the directory path and it works :)

hakre
  • 193,403
  • 52
  • 435
  • 836
iDev
  • 2,163
  • 10
  • 39
  • 64

2 Answers2

2

I had a similar problem and solved it by changing the owner of the folder to the apache user. This should give your php script needed permissions for making files and writing to the files in that folder. I guess you won't be able to chown the folder from php script, only through server access (ssh or ftp). At least, that was the path I had to go.

6opko
  • 1,718
  • 2
  • 20
  • 28
2

Your code is fine. Only the line where chmod resides, is not required.

Commented out chmod("/path/to/dir/*", 0755); this will chmod all files within the set folder.

Consult the PHP manual on chmod at http://php.net/manual/en/function.chmod.php

$message = "Test";
$myFile = "testFile.txt";
if (file_exists($myFile)) {
  $fh = fopen($myFile, 'a');
  fwrite($fh, $message."\n");
} else {

//chmod("/path/to/dir/*", 0755);
  $fh = fopen($myFile, 'w')  or die("Cannot open file \"$myFile\"...\n");
  fwrite($fh, $message) ;
}
fclose($fh);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141