文章列表
 
您正在查看 "Php" 分类下的文章

2009-02-01 10:52
为了跨平台的兼容,有时候需要知道当前运行平台,PHP提供了三种方式来获取当前平台信息:
1. PHP_OS
2. getenv('OS')
3. php_uname()

以我的winxp为例,在上面运行代码:
echo PHP_OS . "\n";
echo getenv('OS') . "\n";
echo php_uname() . "\n";

得到的输出是:
WINNT
Windows_NT
Windows NT colinli-nw 5.1 build 2600

这里面当然php_uname()功能最为强大,具体情况可以参见手册。
如果要判断是否是windows平台,这个是由只需要使用上述任何一个方法,然后判断是否以‘win’打头就是了。
 
2008-06-13 17:59
为php设定错误的代码如下:
ini_set('html_errors', 1); #使用html格式的错误输出内容,比较重要,否则在页面上就乱了 ini_set('error_reporting', E_ALL); #打开所有的错误级别
ini_set('display_errors', 1); #显示错误
ini_set('display_startup_errors', 1); #显示启动错误 推荐在各个业务的入口php文件中设置,而不要在php.ini中设置。 同时对于各个业务,至少分为两个版本:debug(打开错误警告)和release(关闭错误警告)
 
2008-06-02 9:31

#! /bin/sh

if [ -z $1 ]; then
language=php
else
language=$1
fi

echo 'remove old tags file...'
rm -f tags TAGS
rm -f cscope.*

case $language in
'php')
find . -type d \( -name "compile" -o -name ".svn" -o -name "sql" \) -prune -o -name "*.${language}" -print >files
ctags -L files \
   --exclude="\.svn" \
   --totals=yes \
   --tag-relative=yes \
   --PHP-kinds=+cfd-vj

cscope -bkq -i files
rm files
;;
esac
echo 'generate completed...'

 
2008-01-22 15:25

function backtrace($basePath=BASE_DIR)
{
    $bt = debug_backtrace();
    array_shift($bt);
    $data = '';
    foreach ($bt as $i=>$point)
    {  
        $func = isset($point['function'])?$point['function']:'';
        $file = isset($point['file'])?substr($point['file'], strlen($basePath)):'';
        $line = isset($point['line'])?$point['line']:'';
        $args = isset($point['args'])?$point['args']:'';
        $class = isset($point['class'])?$point['class']:'';
        if ($class)
            $data .= "#$i ${class}->${func} at [$file:$line]\n";
        else
            $data .= "#$i $func at [$file:$line]\n";
    }  
    return $data;
}

$dblog = "";
foreach (explode(',', Zend_Registry::get('db_all')) as $db)
{
    $dblog .= "----------------- $db ------------------\n";
    $profiler     = Zend_Registry::get($db)->getProfiler();
    $totalTime    = $profiler->getTotalElapsedSecs();
    $queryCount   = $profiler->getTotalNumQueries();
    $longestTime = 0;
    $longestQuery = null;
    if (false === $profiler->getQueryProfiles()) continue;
    foreach ($profiler->getQueryProfiles() as $query)
    {   
        $elapsed = $query->getElapsedSecs();
        $sql = strtr($query->getQuery(), array("\r\n"=>' ', "\r"=>' ', "\n"=>' ', "\t"=>''));
        if ($elapsed > $longestTime)
        {   
            $longestTime = $elapsed;
            $longestQuery = $sql;
        }  
        $dblog .= "$elapsed seconds: --> $sql.\n" . $query->getStack() . "\n";
    }  
    $dblog .= 'Executed ' . $queryCount . ' queries in ' . $totalTime . ' seconds' . "\n";
    $dblog .= 'Average query length: ' . $totalTime / $queryCount . ' seconds' . "\n";
    $dblog .= 'Queries per second: ' . $queryCount / $totalTime . "\n";
    $dblog .= 'Longest query length: ' . $longestTime . "\n";
    $dblog .= "Longest query: " . $longestQuery . "\n";
}
if ($dblog) Zend_Log()->debug("$dblog\n\n");

 
2008-01-21 10:35

<?php
/**
* Use PHP's socket API to get data from one or more servers. It has such features:
* 1. fine-grined timeout controll
* 2. if given many servers, when cannot connect to one, it will try remainer
* 3. get data in sequence indicated by $continue parameter
* 4. get data end with $delimiter, or in $length bytes, or unknown $length
*
*/
class SocketClient
{
protected $_timeout;
protected $_servers;
protected $_defaultPort = 80;
private $_host;
private $_port;
private $_sock = false;
private $_connected = false;
private $_errMsg = '';

/**
* Construct one socket client
*
* @param array or String $svr
* @param array $timeout
*/
public function __construct($svr, $timeout=array())
{
   if (is_string($svr)) $this->_servers[] = array('host'=>$svr);
   elseif (isset($svr['host'])) $this->_servers[] = $svr;
   else $this->_servers = $svr;

   $this->_timeout = array('conn'=>1, 'send'=>1, 'recv'=>1);
   if (!empty($timeout)) $this->_timeout = array_merge($this->_timeout, $timeout);
}

/**
* connect to many servers, when cannot connect to one, it will try remainer
*
* @return Boolean, if connected to server then TRUE, other FALSE
*/
protected function sconn()
{
   if ($this->_connected) return true;

   foreach ($this->_servers as $svr)
   {
    $this->_host = $svr['host'];
    $this->_port = isset($svr['port']) ? intval($svr['port']) : $this->_defaultPort;
    if ('' == $this->_host || $this->_port < 0) continue;

    $this->_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (false === $this->_sock) return false;
    socket_set_option($this->_sock, SOL_SOCKET, SO_RCVTIMEO, array("sec" => $this->_timeout['recv'], "usec" => 0));
    socket_set_option($this->_sock, SOL_SOCKET, SO_SNDTIMEO, array("sec" => $this->_timeout['send'], "usec" => 0));

    socket_set_nonblock($this->_sock);
    @socket_connect($this->_sock, $this->_host, $this->_port);
    $r = $w = $e = array($this->_sock);
    if (socket_select($r, $w, $e, $this->_timeout['conn']) == 1)
    {
     socket_set_block($this->_sock);
     $this->_connected = true;
     return true;
    }
    else
    {
     $this->_errMsg = 'Cannot connect to '.$this->_host.':'.$this->_port.', '.socket_strerror(socket_last_error($this->_sock));
     socket_close($this->_sock);
     return false;
    }
   }
   return false;
}

/**
* Add servers to Client
*
* @param array $svrs = array(0=>array('host'=>$host1, 'port'=>$port1),...)
*/
public function addServer($svrs)
{
   $this->_servers = array_merge($this->_servers, $svrs);
}

/**
* get certain length data from server
*
* @param String $request
* @param Integer $length, 0 indicates unknown length
* @param Boolean $continue
* @return if error happens then FALSE, other will retrun data that fetched from server
*/
public function get($request, $length=0, $continue=false)
{
   if ('' != $this->getErrorMessage()) return false;
   if (!$this->_sock && !$this->_connected)
   {
    if (empty($request)) return false;

    // connect to server
    if (false === $this->sconn()) return false;

    // send data to server
    if (socket_write($this->_sock, $request) != strlen($request))
    {
     socket_close($this->_sock);
     $this->_errMsg = 'Sending to '.$this->_host.':'.$this->_port.', '.socket_strerror(socket_last_error($this->_sock));
     return false;
    }
   }

   // get data from server
   if (!is_resource($this->_sock)) return false;
   $data = '';
   $length = intval($length);
   if ($length > 0)
   {
    $size = socket_recv($this->_sock, $data, $length, 0x100);
    if ($size !== $length)
    {
     socket_close($this->_sock);
     $this->_errMsg ='Receving from '.$this->_host.':'.$this->_port.', '.socket_strerror(socket_last_error($this->_sock));
     return false;
    }
   }
   else
   {
    $trySize = 16384;
    for(;;)
    {
     $tail = '';
     $size = socket_recv($this->_sock, $tail, $trySize, 0x100);
     if (false === $size)
     {
      $this->_errMsg ='Receving from '.$this->_host.':'.$this->_port.', '.socket_strerror(socket_last_error($this->_sock));
      socket_close($this->_sock);
      return false;
     }
     $data .= $tail;
     if ($size < $trySize) break;
    }
   }

   if (!$continue) socket_close($this->_sock);
   return $data;
}

/**
* get one line end with $delimiter
*
* @param String $request
* @param String $delimiter
* @param Boolean $continue
* @return if error happens then FALSE, other will retrun data that fetched from server
*/
public function getLine($request, $delimiter="\r\n", $continue=false)
{
   if ('' != $this->getErrorMessage()) return false;
   if (!$this->_sock && !$this->_connected)
   {
    if (empty($request)) return false;

    // connect to server
    if (false === $this->sconn()) return false;

    // send data to server
    if (socket_write($this->_sock, $request) != strlen($request))
    {
     socket_close($this->_sock);
     $this->_errMsg = 'Sending to '.$this->_host.':'.$this->_port.', '.socket_strerror(socket_last_error($this->_sock));
     return false;
    }
   }

   // get data from server
   if (!is_resource($this->_sock)) return false;
   $header = '';
   $pos = 0;
   $maxpos = strlen($delimiter) - 1;
   for (;;)
   {
    $ch = '';
    $size = socket_recv($this->_sock, $ch, 1, 0x100);
    if ($size === false)
    {
     socket_close($this->_sock);
     $this->_errMsg ='Receving from '.$this->_host.':'.$this->_port.', '.socket_strerror(socket_last_error($this->_sock));
     return false;
    }
    $header .= $ch;
    if ($ch == $delimiter{$pos})
    {
     if ($pos == $maxpos) break;
     $pos ++;
    }
    else if ($pos > 0)
    {
     $pos = 0;
    }
   }
   if (!$continue) socket_close($this->_sock);
   return $header;
}

public function getErrorMessage()
{
   return $this->_errMsg;
}
}

 
2008-01-18 15:29

ob_start();  
debug_print_backtrace();
$x=ob_get_contents();
ob_end_clean();
echo "$x";

function backtrace($basePath=BASE_DIR)
{
    $bt = debug_backtrace();
    array_shift($bt);
    $data = '';
    foreach ($bt as $i=>$point)
    {  
        $func = isset($point['function'])?$point['function']:'';
        $file = isset($point['file'])?substr($point['file'], strlen($basePath)):'';
        $line = isset($point['line'])?$point['line']:'';
        $args = isset($point['args'])?$point['args']:'';
        $class = isset($point['class'])?$point['class']:'';
        if ($class)
            $data .= "#$i ${class}->${func} at [$file:$line]\n";
        else
            $data .= "#$i $func at [$file:$line]\n";
    }  
    return $data;
}

 
2007-12-29 9:59
调试php的时候,有时候要调试不同的东西,这里给出一个简单的函数,用来调试输出某个变量的值。
它的使用方法为 debug_print($object, [$object_type, [$output_label]]),这里后两个参数是可选的。
当没有传递$output_label的时候,就是用$object_type的变量名作为label。
注意:这里只能够取得全局变量的变量名
<?php
/*
   s -- string
   d -- date
   t -- time
   o -- object
   a -- array
 */
function debug_print(&$msg, $type='s', $label='')
{
    $refection = new ReflectionFunction(__METHOD__);
    $params = $refection->getParameters();
    if (!$params[0]->isPassedByReference() && ''==$label)
    {
        echo 'The first parameter must be passed by REFERENCE when no label was given!',"\n";
        return;
    }
    if ('' == $label)
    {   #get any variable's name as its label
        //存储当前变量值
        $save = $msg;
        //存储所有变量值
        $allvar = $GLOBALS;
        //在函数中不要直拉遍历$GLOBALS,会出现堆栈问题
        foreach($allvar  as $k=>$v)
        {
            //变量值相同,可能不是相同变量,因多个变量的值可能相同
            if ($msg === $v)
            {
                //改变当前变量$msg的值
                $msg = 'x379xc.,945@#^&xk3(@,d(545fd';
                //如果$GLOBALS[$k]也跟着改变,那就是同一个变量。
                if ($msg === $GLOBALS[$k])
                {
                    $label = $k;
                    break;
                }
            }
        }
        //还原变量值
        $msg = $save;
    }

    switch ($type)
    {
        case 'a':
        case 'o':
            echo sprintf("%-20s: %s\n", $label, print_r($msg, true)); break;
        case 'd':
            echo sprintf("%-20s: %s\n", $label, date("Ymd H:i:s", $msg)); break;
        case 's':
        case 't':
        default:
            echo sprintf("%-20s: %s\n", $label, $msg);
    }
}

?>
 
2007-12-28 17:23

设置xdebug

一、命令行模式下

1)设置配置文件

配置命令行使用的php配置文件,多为php-cli.ini
zend_extension="/usr/local/php-5.2.2/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so"

[xdebug]
; Remote settings
xdebug.remote_autostart=off
xdebug.remote_enable=on
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=localhost
xdebug.remote_port=9000

; General
xdebug.auto_trace=off
xdebug.collect_includes=on
xdebug.collect_params=off
xdebug.collect_return=off
xdebug.default_enable=on
xdebug.extended_info=1
xdebug.manual_url=http://www.php.net
xdebug.show_local_vars=0
xdebug.show_mem_delta=0
xdebug.max_nesting_level=100
xdebug.idekey=colin

; Trace options
xdebug.trace_format=0
xdebug.trace_output_dir=/tmp
xdebug.trace_options=0
xdebug.trace_output_name=crc32

; Profiling
xdebug.profiler_append=0
xdebug.profiler_enable=0
xdebug.profiler_enable_trigger=0
xdebug.profiler_output_dir=/tmp
xdebug.profiler_output_name=crc32

配置idekey为你想要的名字

2) 为你的vim添加扩展

http://www.vim.org/scripts/script.php?script_id=1152

3)新开两个shell,在其中要运行php脚本的地方,设定环境变量

shell1> export XDEBUG_CONFIG="idekey=colin"

在shell2中打开vim,使用F5键在9000端口开始侦听链接,默认侦听5秒

shell2> vim

这个时候在shell1中运行php

shell1> php test.php

切换到shell1中,看vim中就有新的连接了,接收连接就可以开始调试了

 
 
   
 
 
文章分类
 
   
 
文章存档
 
     
 
最新文章评论
  

debug hacks(中文版)里166页有一段脚本就是用来设置一些调试操作的。 脚本写在debu
 

tags.sh: line 22: cscope: command not found 这个是什么情况?
 

回复chy:我记得reverse.put.as 的作者写了个.gdbinit的脚本 很强大 你可以参考一
 

谢谢!写的不错,很受益。
 

大哥,应该加工已下呀,你这东西连主函数也没有,怎么看呀
   
帮助中心 | 空间客服 | 投诉中心 | 空间协议
©2012 Baidu