> php教程 > PHP源码 > webqq机器人实现

webqq机器人实现

PHP中文网
풀어 주다: 2016-05-25 17:12:07
원래의
7542명이 탐색했습니다.

webqq机器人,实现支持虚拟空间,异步后台执行,使用了fsockopen 函数模拟浏览器请求,并把相关cookie保存,在下一次请求时再发送到原始的header头里,目前代码还未很完善,也需要web登陆窗口的支持。 
webQQ登陆流程:QQ登陆窗口  输入QQ号后验证QQ相关信息,查看是否需要返回验证码,如果需要则返回验证码,输入密码后提交登陆时生成相关的加密串,并提交到腾讯的网站用户登陆验证接口,此时仅仅是登陆到了腾讯网站,再提交一次到webqq登陆网关实现QQ的登录,返回登录成功后就获取相关的cookie。 

异步挂起实现:使用fsockopen访问启动qq在线的web地址,无需等待直接返回,qq在线的web地址就使用while来获取qq返回的聊天信息(qq.class.php  main 方法) 

1.qq.class.php

<?php
set_time_limit(0);
ignore_user_abort(true);
require_once(&#39;./common.php&#39;);
require_once(&#39;./db.class.php&#39;);
define(&#39;IN_QQ&#39;,true);
 
class qqclient{
 
    private $setopt = array(
        &#39;port&#39;=>80,
        &#39;host&#39;=>&#39;d.web2.qq.com&#39;,
        &#39;userAgent&#39;=>&#39;Mozilla/5.0 (Windows NT 6.1; rv:10.0) Gecko/20100101 Firefox/10.0&#39;,
        &#39;timeOut&#39;=>16,
        &#39;useCookie&#39;=>true,
        &#39;getmsg&#39;=>&#39;/channel/poll2&#39;,
        &#39;putmsg&#39;=>&#39;&#39;,
        &#39;uid&#39;=>&#39;&#39;,
        &#39;pwd&#39;=>&#39;&#39;,
        &#39;checkhost&#39;=>&#39;ptlogin2.qq.com&#39;,
        &#39;runTime&#39;=>300,
    );
 
    public function __set($property,$value){ 
        $this->$property = $value; 
        if($property == &#39;u&#39;)$this->setopt[&#39;uid&#39;] = $this->u;
    } 
    public function __get($property){ 
        return $this->$property;
    } 
     
    function __construct($setopt=array()){
        $this->setopt = array_merge($this->setopt,$setopt);   
        if(@$setopt[&#39;uid&#39;])$this->u = $setopt[&#39;uid&#39;];
    }
     
    public function check($host = null , $url = null , $port = 80){
        $host = isset($host) ? $host : $this->setopt[&#39;checkhost&#39;];
        $url = isset($url) ? $url : &#39;/check?uin=&#39; . $this->setopt[&#39;uid&#39;] . &#39;&appid=1003903&r=&#39;.rand();
        $port = $port ? $port : $this->setopt[&#39;port&#39;];
        $this->check = $this->get( $host , $url , $port );
        return $this;
    }
     
    public function verify(){
        $out = $this->_parsmResult($this->body);
        $this->verify = array();
        $this->verify[&#39;state&#39;] = $out[1][0]; 
        $this->verify[&#39;code&#39;] = $out[1][1]; 
        return $this;
    }
     
    public function verifycode(){
        $t = $this->get(&#39;captcha.qq.com&#39;,&#39;/getimage?aid=1003903&r=&#39;. rand() .&#39;&uin=&#39;. $this->setopt[&#39;uid&#39;] .&#39;&vc_type=&#39;.$this->setopt[&#39;code&#39;]);
        if($t){
            header(&#39;Content-Type: image/jpeg&#39;);
            echo $this->body;
        }
    }
     
    public function login(){
        $this->info = array();
        if(getCache(&#39;live&#39;.$this->u,time()+86400)){
            $this->info[&#39;statusCode&#39;] = &#39;300&#39;;
            $this->info[&#39;message&#39;] = &#39;QQ已经登录了!请勿反复登录&#39;;
        }else{
            $url  = "/login?u={$this->u}&p={$this->p}&verifycode={$this->v}&remember_uin=1&aid=1003903&u1=http%3A%2F%2Fweb2.qq.com%2";
            $url .= "Floginproxy.html%3Fstrong%3Dtrue&h=1&ptredirect=0&ptlang=2052&from_ui=1&pttype=1&dumy=&fp=loginerroralert";
            $this->setclientid()->get(&#39;ptlogin2.qq.com&#39;,$url);
            $msg = $this->_parsmResult($this->body);
            if($msg[1][0]==0){
                $this->loginqq();
            }else{
                $this->info[&#39;statusCode&#39;] = &#39;300&#39;;
                $this->info[&#39;message&#39;] = $msg[1][count($msg[1])-1];
            }
        }
        return $this->info;
    }
     
    public function progress($host,$url,$port = 80){
        $this->get($host,$url,$port,&#39;&#39;,true);
    }
     
    public function main(){
        $clientid = $this->getclientid();
        $psessionid = $this->getResult(&#39;psessionid&#39;);
        $data = array(
            &#39;r&#39;=>&#39;{"clientid":"&#39;.$clientid.&#39;","psessionid":"&#39;.$psessionid.&#39;","key":0,"ids":[]}&#39;,
            &#39;clientid&#39;=>$clientid,
            &#39;psessionid&#39;=>$psessionid,
        );
        writeCache(&#39;live&#39;.$this->u,time());
        $this->msgid = $this->generateCode(7);
        $this->rc = $this->generateCode(5);
        $time = time();
        while(true){
            $this->flushmsg();
            try{
                if(!getCache(&#39;live&#39;.$this->u,time()+86400))exit;
                $msg = $this->post(&#39;d.web2.qq.com&#39;,&#39;/channel/poll2&#39;,80,$data);
                if($msg){
                    $header = split("\r\n\r\n",$msg);$this->header = $header[0];unset($header[0]);$msg = join(&#39;&#39;,$header); 
                    $msg = json_decode($msg);
                    if(@$msg->retcode == 0){
                        $this->putmsg($msg);
                    }elseif(@$msg->retcode == 103){
                        purgeCache(&#39;live&#39;.$this->u);
                        exit;
                    }
                }
            }catch(Exception $e){
                 
            }
            if( (time() - $time ) > $this->setopt[&#39;runTime&#39;] ){
                $this->progress($this->phost,$this->pmain,$this->pport);exit;}
        }   
    }
     
     
    private function putmsg($msg){
        $clientid = $this->getclientid();
        $psessionid = $this->getResult(&#39;psessionid&#39;);
        foreach($msg->result as $value){
            if($value->poll_type == &#39;message&#39;){
                $this->msgid += 1;
                $from_uin = $value->value->from_uin;
                unset($value->value->content[0]);
                $sendmsg = $this->getKeyword(preg_replace("/\[.*?\]/si","",join(&#39;&#39;,$value->value->content)));
                $tmp["to"] = $from_uin;
                $tmp["face"] = 732;
                $tmp["content"] = &#39;["&#39;.addslashes($sendmsg).&#39;",["font",{"name":"微软雅黑","size":"10","style":[0,0,0],"color":"000000"}]]&#39;;
                $tmp["msg_id"] = $this->msgid;
                $tmp["clientid"] = $clientid;
                $tmp["psessionid"] = $psessionid;
                 
                $data[&#39;r&#39;] = json_encode($tmp);;
                $data[&#39;clientid&#39;] = $clientid;
                $data[&#39;psessionid&#39;] = $psessionid;
                 
                $e = $this->post(&#39;d.web2.qq.com&#39;,&#39;/channel/send_buddy_msg2&#39;,80,$data);
            }elseif($value->poll_type == &#39;kick_message&#39;){
                purgeCache(&#39;live&#39;.$this->u);
                exit;
            }
        }       
    }
     
    private function getKeyword($key){
        $key = trim($key);
        $db =   new mysql();
        $preg = array();
         
        if($key){
            if(preg_match_all("/^((\w+):?)([\w\W]*)/i",$key,$preg)){
                $query = $db->findOne(&#39;qqrobot_key&#39;,&#39;files,stype,cotents&#39;,"qq=&#39;{$this->u}&#39; and keyword=&#39;".$preg[2][0]."&#39;");               
            }else{
                $query = $db->findOne(&#39;qqrobot_key&#39;,&#39;files,stype,cotents&#39;,"qq=&#39;{$this->u}&#39; and keyword=&#39;".addslashes($key)."&#39;");
            }       
        }
         
        if(@$query){
            if(@$query[&#39;stype&#39;] == &#39;normal&#39;)
                return $query[&#39;cotents&#39;];
            else{
                if(is_file(dirname(__FILE__).&#39;/plugin/&#39;.$query[&#39;files&#39;])){
                    try{
                        if(@$preg[1][0] == @$preg[2][0]){
                            return $query[&#39;cotents&#39;];
                        }
                        require_once(&#39;./plugin/&#39;.$query[&#39;files&#39;]);
                    }catch(Exception $e){
                         
                    }
                }
                if($query[&#39;cotents&#39;]) return $query[&#39;cotents&#39;];
            }
        }
        $query = $db->findOne(&#39;qqrobot_key&#39;,&#39;files,stype,cotents&#39;,"qq=&#39;{$this->u}&#39; and keyword=&#39;defalut&#39;");
        return @$query[&#39;cotents&#39;] ? $query[&#39;cotents&#39;]:"完了完了...我什么都不知道,怎么办呀!!  ~~~~(>_<)~~~~  ";
    }
     
    private function flushmsg(){
        $this->rc += 1;
        $this->get(&#39;web.qq.com&#39;,&#39;/get_msg_tip?uin=&tp=1&id=0&retype=1&rc=&#39;.$this->rc.&#39;&lv=3&t=&#39;.time());
    }
     
    private function loginqq(){
         
        $cookie = $this->_getCookies();
        list($t,$ptwebqq) = split(&#39;=&#39;,$cookie[&#39;ptwebqq&#39;]);
        $clientid = $this->getclientid();
        $data= array(
            &#39;r&#39; => &#39;{"status":"callme","ptwebqq":"&#39;.$ptwebqq.&#39;","passwd_sig":"","clientid":"&#39;.$clientid.&#39;","psessionid":""}&#39;,
            &#39;clientid&#39;=> $clientid,
            &#39;psessionid&#39; => null,
        );
         
        $data2 = "";
        $this->post(&#39;d.web2.qq.com&#39;,&#39;/channel/login2&#39;,80,$data);
        $body = json_decode($this->body);
        if($body->retcode == 0){
            writeCache(&#39;result&#39;.$this->u,$body);
            $this->progress($this->phost,$this->pmain,$this->pport);
            $this->info[&#39;statusCode&#39;] = &#39;200&#39;;
            $this->info[&#39;message&#39;] = &#39;登录成功!&#39;;
            $this->info[&#39;callbackType&#39;] = &#39;sucessCurrent&#39;;
        }else{
            $this->info[&#39;statusCode&#39;] = &#39;300&#39;;
            $this->info[&#39;message&#39;] = &#39;未知错误!&#39;;
        }
        return $this->info;
    }
     
    private function setclientid($uid = null){
        $uid = $uid ? $uid : $this->setopt[&#39;uid&#39;];
        writeCache(&#39;clientid&#39;.$uid,$this->generateCode(8));
        return $this;
    }
     
    private function getclientid($uid = null){
        $uid = $uid ? $uid : $this->setopt[&#39;uid&#39;];
        return getCache(&#39;clientid&#39;.$uid,time()+86400);
    }
     
    private function getResult($key){
        $data = getCache(&#39;result&#39;.$this->u,time()+86400);    
        if($data && $data->result->$key){
                return $data->result->$key;
        }
        return null;
    }
     
    private function _parsmResult($text){
        if(!$text)return &#39;&#39;;
        preg_match_all("/\&#39;(.*?)\&#39;/",$text,$out);
        return $out;
    }
     
    private function get($host,$url,$port = 80,$content=array(),$quick=false){
        return $this->_request(&#39;get&#39;,$host,$url,$port,$content,$quick);
    }
     
    private function post($host,$url,$port = 80,$content=array(),$quick=false){
        return $this->_request(&#39;post&#39;,$host,$url,$port,$content,$quick);
    }
     
    private function _request($type,$host,$url,$port = 80,$content=array(),$quick=false){
        $type = $type == &#39;get&#39; ? &#39;GET&#39; : &#39;POST&#39;;
        $port = $port ? $port : $this->setopt[&#39;port&#39;];
        $content = $this->_parsmEncode($content);    
        $i = $this->generateCode(&#39;20000&#39;);   
        $fp[$i] = fsockopen($host, $port, $errno, $errstr); 
        if(!$fp[$i]){ 
            $this->errno = $errno ;
            $this->errstr = $errstr ;
            return false;
        } 
        fputs($fp[$i], "$type $url HTTP/1.0\r\n"); 
        fputs($fp[$i], "Host: $host\r\n"); 
        if($type == &#39;POST&#39;){
            fputs($fp[$i], "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n"); 
            fputs($fp[$i], "Content-length: " . strlen($content) . "\r\n"); 
        }
        fputs($fp[$i], "Referer: http://d.web2.qq.com/proxy.html?v=20110331002&callback=2\r\n"); 
        fputs($fp[$i], "Accept-Language: zh-cn,zh;q=0.5\r\n"); 
        fputs($fp[$i], "Cookie: ".$this->getCookies()."\r\n"); 
        fputs($fp[$i], "User-Agent: " . $this->setopt[&#39;userAgent&#39;] . "\r\n"); 
        fputs($fp[$i], "Connection: keep-alive\r\n\r\n"); 
        if($type == &#39;POST&#39;)fputs($fp[$i], "$content\\n");else fputs($fp[$i], "\\n");
        if($type == &#39;POST&#39;)
        stream_set_timeout($fp[$i],$this->setopt[&#39;timeOut&#39;]); 
        if(!$quick){
            $res = &#39;&#39;;
            while (!feof($fp[$i])) 
                $res .= fgets($fp[$i], 128);
             
            $info=stream_get_meta_data($fp[$i]);
            fclose($fp[$i]); 
            if(!$info[&#39;timed_out&#39;]) 
            {         
                $header = split("\r\n\r\n",$res);
                $this->header = $header[0];
                unset($header[0]);
                $this->body = join(&#39;&#39;,$header); 
                $this->parseCookies();
            }else{
                $this->header = null;
                $this->body = null;              
            }
            return $res;
        }else{
            fclose($fp[$i]);
            return true;
        }
    }
     
    private function parseCookies(){
        $header = $this->header ? split("\r\n",$this->header) : array() ;
        $cookie = array();
        foreach($header as $val){
            if(preg_match("/^Set-Cookie/",$val)){
                $t = split(&#39;; &#39;,str_replace("Set-Cookie: ","",$val));
                parse_str($t[0],$t);
                $t2 = array_keys($t);
                $cookie[$t2[0]] = $t2[0].&#39;=&#39;.$t[$t2[0]];
            }
        }
        $cache = getCache($this->setopt[&#39;uid&#39;],time()+850);
        $cache = $cache ? array_merge($cache , $cookie) : $cookie ;     
        writeCache($this->setopt[&#39;uid&#39;],$cache);
        return true;
    }
     
    private function _getCookies(){
        return  getCache($this->setopt[&#39;uid&#39;],time()+850);
    }
     
    private function getCookies(){
        $cookie = $this->_getCookies();
        return $this->cookies = $cookie ? join(&#39;; &#39;,$cookie):&#39;&#39;;
    }
     
    private function _parsmEncode($params,$isRetStr=true,$encode = false){
        if(!is_array($params))return $params;
        $result = $params;
        if($encode){
            foreach($params as $key=>$value){
                $value = urlencode($value);
                $result[$key] = $value;
            }
        }
        return $isRetStr ? http_build_query($result) : $result;
    }
     
    private function generateCode($length=6) {
        $chars = "0123456789";
        $code = "";
        while (strlen($code) < $length) {
            $code .= $chars[rand(0,strlen($chars)-1)];
        }
        return $code;
    }
 
}
?>
로그인 후 복사

2.common.php

<?php
define(&#39;Root&#39;,dirname(__FILE__));
//公共函数
/**
 * safe_file_put_contents() 一次性完成打开文件,写入内容,关闭文件三项工作,并且确保写入时不会造成并发冲突
 *
 * @param string $filename
 * @param string $content
 * @param int $flag
 *
 * @return boolean
 */
function safe_file_put_contents($filename, & $content)
{
    $fp = fopen($filename, &#39;wb&#39;);
    if ($fp) {
        flock($fp, LOCK_EX);
        fwrite($fp, $content);
        flock($fp, LOCK_UN);
        fclose($fp);
        return true;
    } else {
        return false;
    }
}
 
if (!function_exists(&#39;file_put_contents&#39;))
{
    function file_put_contents($filename, & $content)
    {
        return safe_file_put_contents($filename, $content);
    }
}
 
/**
 * safe_file_get_contents() 用共享锁模式打开文件并读取内容,可以避免在并发写入造成的读取不完整问题
 *
 * @param string $filename
 *
 * @return mixed
 */
    function safe_file_get_contents($filename)
    {
        $fp = fopen($filename, &#39;rb&#39;);
        if ($fp) {
            flock($fp, LOCK_SH);
            clearstatcache();
            $filesize = filesize($filename);
            if ($filesize > 0) {
                $data = fread($fp, $filesize);
            } else {
                $data = false;
            }
            flock($fp, LOCK_UN);
            fclose($fp);
            return $data;
        } else {
            return false;
        }
    }
/**
 * 创建一个目录树
 *
 * 用法:
 * <code>
 * mkdirs(&#39;/top/second/3rd&#39;);
 * </code>
 *
 * @param string $dir
 * @param int $mode
 */
    function mkdirs($dir, $mode = 0777)
    {
        if (!is_dir($dir)) {
            mkdirs(dirname($dir), $mode);
            return mkdir($dir, $mode);
        }
        return true;
    }
/**
 * 读取指定缓存的内容,如果缓存内容不存在或失效,则返回 false
 *
 * example:
 * <code>
 * $cacheId = &#39;my_cache_id&#39;;
 * if (!($data = FLEA::getCache($cacheId))) {
 *      $data = &#39;Data&#39;;
 *      FLEA::writeCache($cacheId, $data);
 * }
 * </code>
 *
 * 如果 $cacheIdIsFilename 参数为 true,则生成的缓存文件会以 $cacheId 参数作为文件名。
 * 基于安全原因,尽量不要将 $cacheIdIsFilename 参数设置为 true。
 *
 * $time 参数默认为缓存内容的有效期。其计算依据是以缓存文件的最后更新时间为准(也就是最后一次更新该缓存内容的时间)。
 *
 * 如果 $timeIsLifetime 为 false,则 $time 参数表示用于和缓存文件最更新时间进行比较的依据。
 * 如果 $time 指定的时间早于缓存文件的最后更新时间,则判断缓存内容为有效。
 *
 * @param string $cacheId 缓存ID,不同的缓存内容应该使用不同的ID
 * @param int $time 缓存过期时间或缓存生存周期
 * @param boolean $timeIsLifetime 指示 $time 参数的作用
 * @param boolean $cacheIdIsFilename 指示是否用 $cacheId 作为文件名
 *
 * @return mixed 返回缓存的内容,缓存不存在或失效则返回 false
 */
 
    function getCache($cacheId, $time = 900, $timeIsLifetime = true, $cacheIdIsFilename = false)
    {   $cacheDir =  Root.&#39;/cache/&#39;.substr(md5($cacheId),0,2).&#39;/&#39;.substr(md5($cacheId),1,2).&#39;/&#39;;
        if(!is_dir($cacheDir)){
        mkdirs($cacheDir);}
        if (is_null($cacheDir)) {
            return false;
        }
 
        if ($cacheIdIsFilename) {
            $cacheFile = $cacheDir . &#39;/&#39; . preg_replace(&#39;/[^a-z0-9\-_]/i&#39;, &#39;_&#39;, $cacheId) . &#39;.php&#39;;
        } else {
            $cacheFile = $cacheDir . &#39;/&#39; . md5($cacheId) . &#39;.php&#39;;
        }
        if (!file_exists($cacheFile)) { return false; }
 
        if ($timeIsLifetime && $time == -1) {
            $data = safe_file_get_contents($cacheFile);
            $hash = substr($data, 16, 32);
            $data = substr($data, 48);
            if (crc32($data) != $hash || strlen($hash) != 32) {
                return false;
            }
            return $data !== false ? unserialize($data) : false;
        }
 
        $filetime = filemtime($cacheFile);
        if ($timeIsLifetime) {
            if (time() >= $filetime + $time) { return false; }
        } else {
            if ($time >= $filetime) { return false; }
        }
        $data = safe_file_get_contents($cacheFile);
        $hash = substr($data, 16, 32);
        $data = substr($data, 48);
        if (crc32($data) != $hash || strlen($hash) != 32) {
            return false;
        }
        return $data !== false ? unserialize($data) : false;
    }
 
/**
 * 将变量内容写入缓存
 *
 * example:
 * <code>
 * $data = .....; // 要缓存的数据,可以是任何类型的值
 * // cache id 用于唯一指定一个缓存数据,以便稍后取出缓存数据
 * $cacheId = &#39;data_cahce_1&#39;;
 * FLEA::writeCache($cacheId, $data);
 * </code>
 *
 * @param string $cacheId
 * @param mixed $data
 * @param boolean $cacheIdIsFilename
 *
 * @return boolean
 */
    function writeCache($cacheId, $data, $cacheIdIsFilename = false)
    {
        $cacheDir = Root.&#39;/cache/&#39;.substr(md5($cacheId),0,2).&#39;/&#39;.substr(md5($cacheId),1,2).&#39;/&#39;;
        if(!is_dir($cacheDir)){
        mkdirs($cacheDir);}
         
        if (is_null($cacheDir)) {
            return false;
        }
 
        if ($cacheIdIsFilename) {
            $cacheFile = $cacheDir . &#39;/&#39; . preg_replace(&#39;/[^a-z0-9\-_]/i&#39;, &#39;_&#39;, $cacheId) . &#39;.php&#39;;
        } else {
            $cacheFile = $cacheDir . &#39;/&#39; . md5($cacheId) . &#39;.php&#39;;
        }
 
        $data = serialize($data);
        $prefix = &#39;<?php die(); ?> &#39;;
        $hash = sprintf(&#39;% 32d&#39;, crc32($data));
        $data = $prefix . $hash . $data;
 
        if (!safe_file_put_contents($cacheFile, $data)) {
            return false;
        } else {
            return true;
        }
    }
/**
 * 删除指定的缓存内容
 *
 * @param string $cacheId
 * @param boolean $cacheIdIsFilename
 *
 * @return boolean
 */
    function purgeCache($cacheId, $cacheIdIsFilename = false)
    {
        $cacheDir = Root.&#39;/cache/&#39;.substr(md5($cacheId),0,2).&#39;/&#39;.substr(md5($cacheId),1,2).&#39;/&#39;;
        if(!is_dir($cacheDir)){
        mkdirs($cacheDir);}
 
        if (is_null($cacheDir)) {
            return false;
        }
 
        if ($cacheIdIsFilename) {
            $cacheFile = $cacheDir . &#39;/&#39; . preg_replace(&#39;/[^a-z0-9\-_]/i&#39;, &#39;_&#39;, $cacheId) . &#39;.php&#39;;
        } else {
            $cacheFile = $cacheDir . &#39;/&#39; . md5($cacheId). &#39;.php&#39;;
        }
 
        if (file_exists($cacheFile)) {
            return unlink($cacheFile);
        }
        return true;
    }
?>
로그인 후 복사

3.db.class.php

<?php
define(&#39;db_host&#39;,&#39;数据库服务器&#39;); //数据库服务器  
define(&#39;db_user&#39;,&#39;roto&#39;);      //数据库用户名  
define(&#39;dbpw&#39;,&#39;ubkkE&#39;);    //数据库密码  
define(&#39;dbname&#39;,&#39;snet&#39;);  //数据库名  
define(&#39;dbcharset&#39;,&#39;utf8&#39;);    //数据库编码,不建议修改  
   
   
class mysql {  
       
    var $querynum = 0;        
    var $link;  
    var $sql;
       
    private $dbhost = db_host;  
    private $dbname = dbname;  
    private $dbuser = db_user;  
    private $dbpw = dbpw;  
    private $dbcharset = dbcharset;  
    
       
    function mysql($dbhost=&#39;&#39;, $dbuser=&#39;&#39;, $dbpw=&#39;&#39;, $dbname = &#39;&#39;, $pconnect = 0) {  
    
        $dbhost==&#39;&#39;?$dbhost=$this->dbhost:$dbhost;  
        $dbuser==&#39;&#39;?$dbuser=$this->dbuser:$dbuser;  
        $dbpw==&#39;&#39;?$dbpw=$this->dbpw:$dbpw;  
        $dbname==&#39;&#39;?$dbname=$this->dbname:$dbname;  
    
        if($pconnect) {  
            if(!$this->link = @mysql_pconnect($dbhost, $dbuser, $dbpw)) {  
                $this->halt(&#39;Can not connect to MySQL server&#39;);  
            }  
        } else {  
            if(!$this->link = @mysql_connect($dbhost, $dbuser, $dbpw)) {  
                $this->halt(&#39;Can not connect to MySQL server&#39;);  
            }  
        }  
        if($this->version() > &#39;4.1&#39;) {  
            if($this->dbcharset) {  
                mysql_query("SET character_set_connection=$this->dbcharset, character_set_results=$this->dbcharset, character_set_client=binary", $this->link);  
            }  
    
            if($this->version() > &#39;5.0.1&#39;) {  
                mysql_query("SET sql_mode=&#39;&#39;", $this->link);  
            }  
        }  
    
        if($dbname) {  
            mysql_select_db($dbname, $this->link);  
        }  
    
    }  
       
    function select_db($dbname) {  
        return mysql_select_db($dbname, $this->link);  
    }  
       
    function fetch_array($query, $result_type = MYSQL_ASSOC) {  
        return mysql_fetch_array($query, $result_type);  
    }  
    
       
    function fetch_all($query, $result_type = MYSQL_ASSOC) {  
        $result = array();  
        $num = 0;  
    
        while($ret = mysql_fetch_array($query, $result_type))  
        {  
            $result[$num++] = $ret;  
        }  
        return $result;  
    
    }  
    
       
    function fetch_row($query) {  
        $query = mysql_fetch_row($query);  
        return $query;  
    }  
    
       
    function result($query, $row) {  
        $query = @mysql_result($query, $row);  
        return $query;  
    }  
    
    
       
    function query($sql, $type = &#39;&#39;) {  
    
        $func = $type == &#39;UNBUFFERED&#39; && @function_exists(&#39;mysql_unbuffered_query&#39;) ?  
            &#39;mysql_unbuffered_query&#39; : &#39;mysql_query&#39;;  
        if(!($query = $func($sql, $this->link)) && $type != &#39;SILENT&#39;) {  
            $this->halt(&#39;MySQL Query Error: &#39;, $sql);  
        }  
    
        $this->querynum++;  
        return $query;  
    }  
     
    function insert($table,$row){
        if(!$row)return null;
        $row = $this->_escape($row);
        $tmp = $tmp2 = array();
        foreach($row as $key => $val){
            $tmp[] = $key;
            $tmp2[] = $val;
        }
        $sql = "insert into $table (".join(&#39;,&#39;,$tmp).") values (&#39;".join(&#39;\&#39;,\&#39;&#39;,$tmp2)."&#39;)";
        return $this->query($sql);
    }
     
    function update($table,$row,$where= null){
        if(!$row || !$table)return null;
         
        $row = $this->_escape($row);
        $tmp = array();
        foreach($row as $key => $val){
            $tmp[] = $key."=&#39;$val&#39;";
        }
        $sql = "update $table set ".join(&#39;,&#39;,$tmp)."";
        $sql = $where ? $sql.&#39; where &#39;.$where:$sql;
        return $this->query($sql);
    }
     
    function find($table,$field = &#39;*&#39;,$where=null){
        if(!$table) return null;
        $sql = $this->bulidsql($table,$field,$where);
        $query = $this->query($sql);
        $data = null;
        while($row = $this->fech($query))
            $data[] = $row;         
        return $data;
    }
     
    function findOne($table,$field = &#39;*&#39;,$where=null){
        if(!$table) return null;
        $sql = $this->bulidsql($table,$field,$where);
        return $this->fech($this->query($sql));
    }
     
    function bulidsql($table,$field = &#39;*&#39;,$where=null){
        $sql = &#39;select &#39;.$field.&#39; from &#39;.$table;
        $sql = $where ? $sql.&#39; where &#39;.$where:$sql;
        $this->sql = $sql;
        return $sql;
    }
     
    function fech($query,$type = MYSQL_ASSOC){
        return mysql_fetch_array($query, $type);
    }
     
    function _escape($row){
        if(is_array($row)){
            foreach($row as $key => $val){
                $row[$key] = addslashes($val);
            }
        }
        return $row;
    }
     
    function affected_rows() {  
        return mysql_affected_rows($this->link);  
    }  
       
    function error() {  
        return (($this->link) ? mysql_error($this->link) : mysql_error());  
    }  
       
    function errno() {  
        return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());  
    }  
    
       
    function num_rows($query) {  
        $query = mysql_num_rows($query);  
        return $query;  
    }  
       
    function num_fields($query) {  
        return mysql_num_fields($query);  
    }  
       
    function free_result($query) {  
        return mysql_free_result($query);  
    }  
       
    function insert_id() {  
        return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);  
    }  
    
       
    function fetch_fields($query) {  
        return mysql_fetch_field($query);  
    }  
       
    function version() {  
        return mysql_get_server_info($this->link);  
    }  
       
    function close() {  
        return mysql_close($this->link);  
    }  
       
    function halt($message = &#39;&#39;, $sql = &#39;&#39;) {  
        echo $message . &#39; &#39; . $sql;  
        exit;  
    
    }  
}  
?>
로그인 후 복사
관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 추천
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿