Home  >  Article  >  php教程  >  php 获取qq用户昵称和在线状态实例

php 获取qq用户昵称和在线状态实例

WBOY
WBOYOriginal
2016-06-02 09:14:411085browse

如果我们利用php获取QQ用户名与在线状态QQ并未给我们提供api接口了,如果要获取我们可以通过QQ空间或QQ网页版聊天来实现。

QQ通过返回不同的图片,来表示在线或离线,图标也随之变换

既然图片不同,那么,返回的HTTP头信息中的Content-Length 也一定不同,而且,彩色图片一定会比同样子的暗色图片要大,于是,找出某个样式的彩色与暗色图片的中间值,就能达到通过判断头部返回长度的方法来获取QQ在线状态

以下是代码

<?php
function get_qq_status($uin) {
    error_reporting(0);
    $f = file_get_contents(&#39;http://wpa.qq.com/pa?p=1:&#39; . $uin . &#39;:4&#39;);
    if (!$f) return (true);
    foreach ($http_response_header as $val) {
        if (strpos($val, &#39;Content-Length&#39;) !== false) {
            return (intval(substr($val, 16, 50)) > 1000);
        }
    }
}
?>

上面比较简单,下面来个更好的

<?php
function tphp_qq_online($uin) {
    $reques = "GET /pa?p=1:" . $uin . ":1 HTTP/1.1rn";
    $reques.= "Host: wpa.qq.comrn";
    $reques.= "User-Agent: PHP_QQ_SPYrnrn";
    if (!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) return (-1);
    if (!(socket_connect($socket, "wpa.qq.com", 80))) return (-1);
    if (!(socket_write($socket, $reques))) return (-1);
    if (!($respon = socket_read($socket, 1024, PHP_BINARY_READ))) return (-1);;
    socket_close($socket);
    $field = explode("rn", $respon);
    for ($i = 0; $i < count($field); $i++) {
        if (strncasecmp($field[$i], "Location:", 9) == 0) {
            if (strpos($field[$i], "online")) {
                $ret = 1;
            } else if (strpos($field[$i], "offline")) {
                $ret = 0;
            } else {
                $ret = - 1;
            } // if
            break;
        } // if
        
    } // for
    return ($ret);
}
/* }}} */
echo tphp_qq_online(561272831);
?>

例,qq用户昵称和在线状态

<?php
//获取QQ状态
function getQQState($qq) {
    $url = &#39;http://wpa.qq.com/pa?p=2:&#39; . $qq . &#39;:41&r=&#39; . time();
    $headInfo = get_headers($url, 1);
    $length = $headInfo[&#39;Content-Length&#39;];
    if ($length == 1243) {
        return true;
    } else {
        return false;
    }
}
//获取QQ昵称
function getQQNick($qq) {
    $str = file_get_contents(&#39;http://r.qzone.qq.com/cgi-bin/user/cgi_personal_card?uin=&#39; . $qq);
    $pattern = &#39;/&#39; . preg_quote(&#39;"nickname":"&#39;, &#39;/&#39;) . &#39;(.*?)&#39; . preg_quote(&#39;",&#39;, &#39;/&#39;) . &#39;/i&#39;;
    preg_match($pattern, $str, $result);
    return $result[1];
}
//获取QQ姓名
function getQQName($qq) {
    //$qqArr = include &#39;friendArr.php&#39;;//预先设置的
    //$username = $qqArr[$qq];
    if (!$username) {
        $username = getQQNick($qq);
    }
    return $username;
}
?>


本文地址:

转载随意,但请附上文章地址:-)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn