fwrite not writing

半腔热情 提交于 2019-12-04 04:13:37

问题


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


回答1:


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




回答2:


https://bugs.php.net/bug.php?id=48607 there is a php bug with fwrite and ftp which means the last chunks of files sometimes dont get written when fclose is called directly after fwrite putting a sleep(1); before fclose fixes the issue, or in your case logging to a file before fclose can also stop it

posting for future reference!




回答3:


 <?php
    $filename = 'log.txt';
    $somecontent = "Missing gallery image for: ";
    if($row['toolbar_id'] != "") 
    { 
        $somecontent .= $row['toolbar_id'];
    }

   if (is_writable($filename)) {


        if (!$handle = fopen($filename, 'a')) {
             echo "Cannot open file ($filename)";
             exit;
        }


        if (fwrite($handle, $somecontent) === FALSE) {
            echo "Cannot write to file ($filename)";
            exit;
        }

        echo "Success, wrote ($somecontent) to file ($filename)";

        fclose($handle);

    } else {
        echo "The file $filename is not writable";
    }
    ?>

Try this code... !!



来源:https://stackoverflow.com/questions/7578350/fwrite-not-writing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!