无法写入文件

I would net your help concerning an issue I'm currently having with PHP

Here is the Code:

<?php

$ics_file   = 'schedule.ics';

if (is_writable($ics_file)) {
    if (!$handle = fopen($ics_file, 'w')) {
        echo "Cannot open file ($ics_file)

";
        exit;
    }

    # Write $ics_contents to opened file
    if (fwrite($handle, "foobar") === FALSE) {
        echo "Cannot write to file ($ics_file)

";
        exit;
    }

    # echo "Success, wrote to <b>schedule.ics</b><br>

";
    fclose($handle);
} else {
    echo "The file <b>$ics_file</b> is not writable

";
}
?>

On my Webpage I always receive "The file schedule.ics is not writable" so it can't access the File. Could you kindly give me a hint into the right direction?

  1. If file does not exists, is_writable causes your error. You can simply omit this condition and try to write to file and check the result of fopen:

    if ($handle = fopen($ics_file, 'w')) {
        if (fwrite($handle, $ics_contents) === FALSE)
            echo "Cannot write to file ($ics_file)
    
    ";
        else {
            # echo "Success, wrote to <b>schedule.ics</b><br>
    
    ";
        }
    
        fclose($handle);
        exit;
    }
    else {
        echo "Cannot write to file ($ics_file)
    
    ";
        exit;
    }
    
  2. If previous solution does not help, check directory/file permissions. File access depends on server configuration. Try to create file by your own, and set up permission to 777 (for testing). Then script should have access to write into it.

  3. You are reading whole file content to memory. In such case, if you don't need to have the file on disk, you can just send the content to the client using something like this PHP - send file to user.