PHP fread没有返回字符串

时间:2012-11-28 15:06:42

标签: php logging fread

    log_email("email to: " . $to . " at: " . $time);
}

function log_email($message){
    $dir = dirname(__FILE__);
    $filename = $dir . "/logs/email_log.txt";       
        echo $filename;

    if(is_readable($filename)){        
        $handle = fopen($filename, "w+");
        $contents = fread($handle, filesize($filename));
        fwrite($handle, $message . "\n" . $contents);
        fclose($handle); 
    }else{
        echo 'The file is not readable.';
    }
}

该文件具有777访问权限,该文件包含一些文本。 我收到警告说:警告:fread():长度参数必须大于0 ...

$ contents变量最终什么都没有?有任何想法吗? 该目录必须正确,因为如果我删除该文件,我的is_readable将返回false。

1 个答案:

答案 0 :(得分:4)

当您最初使用此行打开文件时,该文件为truncating

$handle = fopen($filename, "w+");

因此,触发该警告时,此大小将为零。

你应该做这样的事情:

function log_email($message){
    $dir = dirname(__FILE__);
    $filename = $dir . "/logs/email_log.txt";       
        echo $filename;

    if(is_readable($filename)){        
        // This will append to the file without destroying its contents
        $handle = fopen($filename, "a+"); 
        fwrite($handle, $message . "\n");
        fclose($handle); 
    }else{
        echo 'The file is not readable.';
    }
}