Search code examples
phpfopenfwrite

PHP version: 5.1.6: Cannot write to file


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 :)


Solution

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