基于Tor socks5的http消息类

 更新时间:2016年11月25日 15:56  点击:1713

try{
    $tor = new TorHttp('127.0.0.1', 9050);
    $data = array('username' => 'liujun');
    $headers = array('Cookie' => 'php教程id=123456; xx=v');
    echo $tor->get('http://host.com/testsocks.php', $headers);
    $tor->newId('123456');
}catch(Exception $e){
    if($e->getCode() == 9999){
        $tor->newId('123456');
    }
    echo $e->getMessage() . "n";
}
*/

class Tool_TorHttp
{
    /**
     * Tor提供的socks服务器
     *
     * @var <string
     */
    private $_host;

    /**
     * socks服务的连接
     *
     * @var <stream>
     */
    private $_sock;

    /**
     * 构造函数
     *
     * @param <string> $host socks服务器地址
     * @param <int> $port
     */
    public function __construct($host = '127.0.0.1', $port = 9050)
    {
        $this->_host = $host;
        @ $this->_sock = fsockopen($host, $port, $errorCode, $error, 5);

        if($errorCode){
           throw new Exception('不能连接代理服务器');
        }

        //建立应用层的连接
        fwrite($this->_sock, pack('C3', 5, 1, 0));
        $resp = fread($this->_sock, 1024);
        $resp = unpack('Cversion/Cmethod', $resp);
        if($resp['version'] != 5 || $resp['method'] != 0){
            $this->_sock = null;
            throw new Exception('代理服务器不可用或者需要连接密码');
        }
    }

    /**
     * 连接目标主机
     *
     * @param <type> $host
     * @param <type> $port
     */
    private function _connect($host, $port)
    {
        //ip和域名描述的服务器用不同的报文格式
        $lip = ip2long($host);
        if(empty($lip)){
            $pack = pack('C5', 5, 1, 0, 3, strlen($host)) . $host . pack('n', intval($port));
        }else{
            $pack = pack('C4Nn', 5, 1, 0, 1, $lip, $port);
        }
        fwrite($this->_sock, $pack);
        $resp = '';
        $counter = 0;
        while(true){
            if(feof($this->_sock)){
                break;
            }
            $resp .= fread($this->_sock, 1024);
            if(!empty($resp) || $counter == 50){
                break;
            }
            $counter += 1;
        }

        $resp = unpack('Cversion/Crep', $resp);
        if(($resp['version'] != 5) || ($resp['rep'] != 0)){
            throw new Exception("请求的服务[$host:$port]暂时不可用,或者Tor不能到达,如果反复发生,请尝试重启Tor", 9999);
        }
    }

    /**
     * 发起一次http的get请求
     *
     * @param <type> $url
     * @return <string>
     */
    public function get($url, $headers = array())
    {
        $ua = parse_url($url);
        if(empty($ua['port'])){
            $ua['port'] = 80;
        }

        $this->_connect($ua['host'], $ua['port']);

        $requestUri = $ua['path'];

        if(!empty($ua['query'])){
                $requestUri .= '?' . $ua['query'];
        }

        $headers['Host'] = $ua['host'];
        if(!isset($headers['User-Agent'])){
            $headers['User-Agent'] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 GTB5";
        }
        $headers['Connection'] = 'close';

        fwrite($this->_sock, "GET {$requestUri} HTTP/1.1n");
        foreach ($headers as $key => $val){
            fwrite($this->_sock, "{$key}: {$val}n");
        }
        fwrite($this->_sock, "n");

        $resp = '';
        while(!feof($this->_sock)){
            $resp .= fread($this->_sock, 1024);
        }
        return $resp;
    }

    /**
     * 发起一次http的post请求
     *
     * @param <type> $url
     * @param <type> $data
     * @param <type> $headers
     * @return <type>
     */
    public function post($url, $data, $headers = array())
    {
        $ua = parse_url($url);

        if(empty($ua['port'])){
            $ua['port'] = 80;
        }

        $this->_connect($ua['host'], $ua['port']);

        if(isset($ua['path']) && !empty($ua['path'])){
            $requestUri = $ua['path'];
        }else{
            $requestUri = '/';
        }

        if(!empty($ua['query'])){
            $requestUri .= '?' . $ua['query'];
        }

        if(!isset($headers['User-Agent'])){
            $headers['User-Agent'] = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 GTB5";
        }
        $headers['Connection'] = 'close';

        $data = $this->_parseData($data);

        fwrite($this->_sock, "POST {$requestUri} HTTP/1.1n");
        fwrite($this->_sock, "Host: {$ua['host']}n");
        fwrite($this->_sock, "Content-Type: application/x-www-form-urlencodedn");
        fwrite($this->_sock, "Content-Length: " . strlen($data) . "n");
        foreach ($headers as $key => $val){
            fwrite($this->_sock, "{$key}: {$val}n");
        }
        fwrite($this->_sock, "n");
        fwrite($this->_sock, $data . "n");

        $resp = '';
        while(!feof($this->_sock)){
            $resp .= fread($this->_sock, 1024);
        }
        return $resp;
    }

    /**
     * 更新Tor的身份
     *
     * @param <type> $password
     * @param <type> $port
     * @return <type>
     */
    public function newId($password = '', $port = 9051)
    {
        if(!empty($password) && $password[0] != '"'){
            $password = '"' . $password . '"';
        }

        //创建到tor控终端的连接
        @ $sock = fsockopen($this->_host, $port, $errorCode, $error, 5);
        if($errorCode){
           throw new Exception('不能连接代理服务器控制端,请检查端口号');
        }

        fwrite($sock, "AUTHENTICATE {$password}n");
        $resp = fread($sock, 1024);
        if(!preg_match('/^250/', $resp)){
            throw new Exception('Tor控制认证失败,请确认密码正确');
        }

        fwrite($sock, "SIGNAL NEWNYMn");
        $resp = fread($sock, 1024);
        if(!preg_match('/^250/', $resp)){
            throw new Exception('更新身份失败,请重试');
        }
        return true;
    }

    private function _parseData($data)
    {
        if(empty($data) || !is_array($data)){
                return $data;
        }
        $encoded = '';
        while (list($k, $v) = each($data)) {
            $encoded .= $k . "=" . $v . '&';
        }
        return substr($encoded, 0, -1);
    }

    public function  __destruct()
    {
        fclose($this->_sock);
        $this->_sock = null;
    }
}

方法一
<?php教程
echo strtotime('last Monday');
echo '<br />';
echo strtotime('next Sunday');
?>

方法二
<? 

02 function getMonSun(){ 

03     $curTime=time(); 

04         

05     $curWeekday = date('w'); 

06   

07      //为0是 就是 星期七 

08     $curWeekday = $curWeekday?$curWeekday:7; 

09   

10   

11     $curMon = $curTime - ($curWeekday-1)*86400; 

12     $curSun = $curTime + (7 - $curWeekday)*86400; 

13        

14     $cur['Mon'] = $curMon; 

15     $cur['Sun'] = $curSun; 

16   

17     return $cur; 

18 } 

19     $cur = getMonSun(); 

20   

21     echo date('Y-m-d',$cur['Mon']); 

22     echo "rn"; 

23     echo date('Y-m-d',$cur['Sun']); 

24 ?>


方法三

<? 

02 function getMonSun(){ 

03      $curTime=time(); 

04         

05      //求出当前是星期几: 

06      $curWeekday = date('w'); 

07         

08      //如果是周一则减上7*86400周二减上6*86400,依此类推得到周一的时间戳: 

09      switch ($curWeekday) { 

10      case 0: 

11      $curMon = $curTime-7*86400; 

12          $curSun = $curTime; 

13      break; 

14      case 1: 

15      $curMon = $curTime; 

16           $curSun = $curTime+6*86400; 

17      break; 

18      case 2: 

19      $curMon = $curTime-1*86400; 

20          $curSun = $curTime+5*86400; 

21      break; 

22      case 3: 

23      $curMon = $curTime-2*86400; 

24          $curSun = $curTime+4*86400; 

25      break; 

26      case 4: 

27      $curMon = $curTime-3*86400; 

28          $curSun = $curTime+3*86400; 

29      break; 

30      case 5: 

31      $curMon = $curTime-4*86400; 

32          $curSun = $curTime+2*86400; 

33      break; 

34      case 6: 

35      $curMon = $curTime-5*86400; 

36          $curSun = $curTime+1*86400; 

37      break; 

38     } 

39     $cur['Mon'] = $curMon; 

40     $cur['Sun'] = $curSun; 

41   

42     return $cur; 

43 } 

44 $cur = getMonSun(); 

45          echo date('Y-m-d',$cur['Mon']); 

46          echo "rn"; 

47      echo date('Y-m-d',$cur['Sun']); 

48 ?>

 

其实于php file_exists 函数与 file_exists语法我们早就讲过了,下面我们来看看一下关于它的使用方法与实例吧

bool file_exists ( string filename )

如果由 filename 指定的文件或目录存在则返回 TRUE,否则返回 FALSE

其实于php教程 file_exists 函数与 file_exists语法我们早就讲过了,下面我们来看看一下关于它的使用方法与实例吧

路径的文件或目录。

在Windows上,使用/ /计算机名/共享/文件名或 计算机名共享文件名,以检查网络共享文件。

这是一个很简单的实例一

<?php
$filename = '/www.111cn.net/aa/to/foo.txt';

if (file_exists($filename)) {
    echo "文件$filename exists";
} else {
    echo "文件$filename 不存在";
}
?>

输出结果为:

文件/www.111cn.net/aa/to/foo.txt己存在

再来看看实例二

<?php
echo file_exists("www.111cn.net.txt");
?>

这个我们就直接用file_exists来返回ture or false

 

PHP程序的缓冲,而不论PHP执行在何种情况下(CGI ,web服务器等等)。该函数将当前为止程序的所有输出发送到用户的浏览器。
flush() 函数不会对服务器或客户端浏览器的缓存模式产生影响。因此,必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
个别web服务器程序,特别是Win32下的web服务器程序,在发送结果到浏览器之前,仍然会缓存脚本的输出,直到程序结束为止

 */
for ($i=10; $i>0; $i--)
{
 echo $i;
 ob_flush();
 flush();
 sleep(1);
}

// Microsoft Internet Explorer 只有当接受到的256个字节以后才开始显示该页面,所以必须发送一些额外的空格来让这些浏览器显示页面内容

//正常用法

ob_start();
ob_end_flush();
for($i = 1; $i <= 300; $i++ )echo ' www.111cn.net';

$i = 0;
while(1) {
echo $i;
sleep(1);
$i++;
}

 

for($i=0;$i<10;$i++) {
    echo $i;
    flush();
    sleep(1);
}

//这段代码,应该隔一秒钟输出一次$i,但是实际中却不一定是这样,IE浏览器下有可能是等了10秒钟后,所有的输出同时呈现出来

//ob_end_flush();//IE8下没起作用
echo str_pad(" ", 256);//IE需要接受到256个字节之后才开始显示

for($i=0;$i<18;$i++) {
    echo $i;
    flush();
    sleep(1);
}


<?xml version="1.0" encoding="gb2312"?>
<rss version="2.0">
<channel>
<title>javascript教程</title>
<link>http://blog.111cn.net/zhongmao/category/29515.asp教程x</link>
<description>javascript</description>
<language>zh-chs</language>
<generator>.text version 0.958.2004.2001</generator>
<item>
<creator>zhongmao</creator>
<title orderby="1">out put excel used javascript</title>
<link>http://blog.111cn.net/zhongmao/archive/2004/09/15/105385.aspx</link>
<pubdate>wed, 15 sep 2004 13:32:00 gmt</pubdate>
<guid>http://blog.111cn.net/zhongmao/archive/2004/09/15/105385.aspx</guid>
<comment>http://blog.111cn.net/zhongmao/comments/105385.aspx</comment>
<comments>http://blog.111cn.net/zhongmao/archive/2004/09/15/105385.aspx#feedback</comments>
<comments>2</comments>
<commentrss>http://blog.111cn.net/zhongmao/comments/commentrss/105385.aspx</commentrss>
<ping>http://blog.111cn.net/zhongmao/services/trackbacks/105385.aspx</ping>
<description>test description</description>
</item>
<item>
<creator>zhongmao</creator>
<title orderby="2">out put word used javascript</title>
<link>http://blog.111cn.net/zhongmao/archive/2004/08/06/67161.aspx</link>
<pubdate>fri, 06 aug 2004 16:33:00 gmt</pubdate>
<guid>http://blog.111cn.net/zhongmao/archive/2004/08/06/67161.aspx</guid>
<comment>http://blog.111cn.net/zhongmao/comments/67161.aspx</comment>
<comments>http://blog.111cn.net/zhongmao/archive/2004/08/06/67161.aspx#feedback</comments>
<comments>0</comments>
<commentrss>http://blog.111cn.net/zhongmao/comments/commentrss/67161.aspx</commentrss>
<ping>http://blog.111cn.net/zhongmao/services/trackbacks/67161.aspx</ping>
<description>test word description</description>
</item>
<item>
<creator>zhongmao</creator>
<title orderby="3">xmlhttp</title>
<link>http://blog.111cn.net/zhongmao/archive/2004/08/02/58417.aspx</link>
<pubdate>mon, 02 aug 2004 10:11:00 gmt</pubdate>
<guid>http://blog.111cn.net/zhongmao/archive/2004/08/02/58417.aspx</guid>
<comment>http://blog.111cn.net/zhongmao/comments/58417.aspx</comment>
<comments>http://blog.111cn.net/zhongmao/archive/2004/08/02/58417.aspx#feedback</comments>
<comments>0</comments>
<commentrss>http://blog.111cn.net/zhongmao/comments/commentrss/58417.aspx</commentrss>
<ping>http://blog.111cn.net/zhongmao/services/trackbacks/58417.aspx</ping>
<description>xmlhttpaaa asd bb cc dd</description>
</item>
</channel>
</rss>
<?

//首先要创建一个DOMDocument对象
$dom = new DomDocument();
//然后载入XML文件
$dom -> load("test.xml");

//输出XML文件
//header("Content-type: text/xml;charset=gb2312");
//echo $dom -> saveXML();

//保存XML文件,返回值为int(文件大小,以字节为单位)
//$dom -> save("newfile.xml");

echo "<hr/>取得所有的title元素:<hr/>";
$titles = $dom -> getElementsByTagName("title");
foreach ($titles as $node){
echo $node -> textContent . "<br/>";
//这样也可以
//echo $node->firstChild->data . "<br/>";
}

/*
echo "<hr/>从根结点遍历所有结点:<br/>";
foreach ($dom->documentElement->childNodes as $items) {
//如果节点是一个元素(nodeType == 1)并且名字是item就继续循环
if ($items->nodeType == 1 && $items->nodeName == "item") {
foreach ($items->childNodes as $titles) {
//如果节点是一个元素,并且名字是title就打印它.
if ($titles->nodeType == 1 && $titles->nodeName == "title") {
print $titles->textContent . "n";
}
}
}
}
*/

//使用XPath查询数据
echo "<hr/>使用XPath查询的title节点结果:<hr/>";
$xpath = new domxpath($dom);
$titles = $xpath->query("/rss/channel/item/title");
foreach ($titles as $node){
echo $node->textContent."<br/>";
}
/*
这样和使用getElementsByTagName()方法差不多,但是Xpath要强大的多
深入一点可能是这样:
/rss/channel/item[position() = 1]/title 返回第一个item元素的所有
/rss/channel/item/title[@id = '23'] 返回所有含有id属性并且值为23的title
/rss/channel/&folder&/title 返回所有articles元素下面的title(译者注:&folder&代表目录深度)
*/


//向DOM中写入新数据
$item = $dom->createElement("item");
$title = $dom->createElement("title");
$titleText = $dom->createTextNode("title text");
$title->appendChild($titleText);
$item->appendChild($title);
$dom->documentElement->getElementsByTagName('channel')->item(0)->appendChild($item);

//从DOM中删除节点
//$dom->documentElement->RemoveChild($dom->documentElement->getElementsByTagName("channel")->item(0));
//或者使用xpath查询出节点再删除
//$dom->documentElement->RemoveChild($xpath->query("/rss/channel")->item(0));
//$dom->save("newfile.xml");

//从DOM中修改节点数据
//修改第一个title的文件
//这个地方比较笨,新创建一个节点,然后替换旧的节点。如果哪位朋友有其他好的方法请一定要告诉我
$firstTitle = $xpath->query("/rss/channel/item/title")->item(0);
$newTitle = $dom->createElement("title");
$newTitle->appendChild(new DOMText("This's the new title text!!!"));
$firstTitle->parentNode->replaceChild($newTitle, $firstTitle);
//修改属性
//$firstTitle = $xpath->query("/rss/channel/item/title")->item(0);
//$firstTitle->setAttribute("orderby", "4");
$dom->save("newfile.xml");

echo "<hr/><a href="newfile.xml">查看newfile.xml</a>";

//下面的代码获得并解析111cn.net的首页,将返第一个title元素的内容。
/*
$dom->loadHTMLFile("http://www.111cn.net/");
$title = $dom->getElementsByTagName("title");
print $title->item(0)->textContent;
*/
?>

[!--infotagslink--]

相关文章