Search code examples
phpfwrite

fwrite not writing


 $fp = fopen('log.txt', 'w');
 fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . '\n');

The code above is not writing to the file. the $row['toolbar_id'] is a value from a for each loop. Any suggestions? There is no PHP error, as the file does open as I have debugged that part.


Solution

  • Try this for extra surety

    ini_set('display_errors', 'On');
    error_reporting(E_ALL);
    
    $fp = fopen('log.txt', 'ab');
    if (false === $fp) {
        throw new RuntimeException('Unable to open log file for writing');
    }
    
    $bytes = fwrite($fp, 'Missing gallery image for: ' . $row['toolbar_id'] . PHP_EOL);
    printf('Wrote %d bytes to %s', $bytes, realpath('log.txt'));
    fclose($fp);
    

    Edit: Changed the "write" flag (w) to "append" (a) as truncating a log file doesn't sound like a great idea