php调试用的函数

function is_cli_mode() {
    $sapi_type = php_sapi_name();
    if (isset($sapi_type) && substr($sapi_type, 0, 3) == 'cli') {
        return true;
    } else {
        return false;
    }
}

/**
 * 调试函数,以文件的形式把变量记录到一个文件里
 * @param var $text 要记录到文件的变量
 * @param bool $save_req_params 是否需要记录request提交的变量
 * @param string $debug_sign 调试的变量标志符,例如'UserModel'.__LINE__
 * */
function debug_dump($text,$save_req_params=false,$debug_sign='')
{
    $logdir=HOME_PATH.'Files/';
    if(!is_dir($logdir))return false;
    if(!is_writeable($logdir))@chmod($logdir,0777);
    if(!is_writeable($logdir))return false;
    $debug_info = debug_backtrace();
    $arr_file_info = pathinfo($debug_info[0]['file']);
    $debug_message = $arr_file_info['filename']. '__'.$debug_info[0]['line'];
    $file_mark = $debug_sign=='' ? $debug_message : $debug_sign;
    $logfilename = $logdir.'dump_' . date('Ymd_').$file_mark . '.txt';
    $_stamp = '';
    if(!is_cli_mode()){
        $_stamp .= "-------------------------------------------------------------".PHP_EOL;
        $_stamp .= $_SERVER['REQUEST_URI'].':'.date('Y-m-d H:i:s').PHP_EOL;
        $_stamp .= $file_mark.PHP_EOL;
        if($save_req_params){
            $_stamp .= json_encode($_REQUEST,JSON_UNESCAPED_UNICODE).PHP_EOL;
        }
        $_stamp .= "-------------------------------------------------------------".PHP_EOL;
    }
    ob_start();
    echo '<pre>';
    print_r($text);
    $str = ob_get_contents();
    $str .= PHP_EOL;
    $str .= $_stamp;
    $str = preg_replace("/^<pre>/",'',$str);
    ob_end_clean();

    file_put_contents($logfilename, $str, FILE_APPEND);
}

/**
 * 调试打印在页面上
 * */
function debug_print($text,$is_exit=true)
{
    $_stamp = '';
    $_stamp .= "-------------------------------------------------------------".PHP_EOL;
    $_stamp .= $_SERVER['REQUEST_URI'].PHP_EOL;
    $_stamp .= "-------------------------------------------------------------".PHP_EOL;
    ob_start();
    echo '<pre>';
    print_r($text);
    $str = ob_get_contents();
    $str .= "\n\n";
    $str .= $_stamp;
    ob_end_clean();
    echo $str;
    if($is_exit)exit;
}

  

posted @ 2023-09-11 11:30  tochenwei  阅读(6)  评论(0编辑  收藏  举报