开发者

Cannot get PHP to write to a file

开发者 https://www.devze.com 2022-12-17 19:13 出处:网络
Below is a simple database class, well its part of a class, I stripped everything out except the parts related to my question.

Below is a simple database class, well its part of a class, I stripped everything out except the parts related to my question.

Basicly it will allow me to build a file with all the queries that were ran on a page load with the time they took, the order they are in, the total count, and then also the actual SQL that was ran. It is very nice but I am having trouble. I can开发者_C百科not get it to write to the file, you can see below that I print to screen the value of $sss which is the value that should be written to file. In PHP I have error reporting set to show everything and I get no write errors or anything, it just doesn't write to the file, possibly I may have the file on the wrong folder but I am not sure.

So what would be a good way to set a filepath to the log file and also to make it write? IF it cannot find the file now, should I see some sort of error?

<?PHP
class Database
{
    public $debug = true;
    public $query_count = 0;
    public $debug_file = "debug.sql";

    public function query($sql){
        //start timer stuff for debug logger
        list($usec, $sec) = explode(" ",microtime());
        $time_start  = ((float)$usec + (float)$sec);

        //run mysql query
        $result = mysql_query($sql);


        ///debug    
        list($usec, $sec) = explode(" ",microtime());
        $time_end  =  ((float)$usec + (float)$sec);
        $time = $time_end - $time_start;
        if($this->debug){
            $this->query_count ++;
            $f = fopen($this->debug_file, "a");
            $sss = "# ".$this->query_count."\n ".$time." sec \n\n".$sql."\n#-------------------------------------------------------------------------\n\n";

            // I print to screen just for test to see what should be wrriten to the file
            echo $sss;

            fputs($f, $sss, strlen($sss));
            fclose($f);
        }
        //end debug
    }
}
?>


First of all, I would use file_put_contents (http://php.net/manual/en/function.file-put-contents.php), it essentially bundles all those calls into one and can help avoid errors.

If the echo statement is truly working, I would check for any errors being written to the php log file, and double check your settings in php.ini and make you are logging warnings.

Also, check the return value of the fopen() call (it should not be false) ... maybe its failing?

0

精彩评论

暂无评论...
验证码 换一张
取 消