An HTTP message class based on Tor SOCKS5

Source: Internet
Author: User
Tags fread http post pack php tutorial unpack port number

try{
$tor = new Torhttp (' 127.0.0.1 ', 9050);
$data = Array (' username ' => ' Liujun ');
$headers = Array (' Cookie ' => ' php tutorial 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
{
/**
* Socks server provided by Tor
*
* @var <string
*/
Private $_host;

/**
* Connection to the SOCKS service
*
* @var <stream>
*/
Private $_sock;

/**
* Constructor
*
* @param <string> $host Socks server address
* @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 (' Cannot connect proxy server ');
}

Establish a connection to the application tier
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 (' Proxy server unavailable or need to connect password ');
}
}

/**
* Connect to target host
*
* @param <type> $host
* @param <type> $port
*/
Private Function _connect ($host, $port)
{
IP and Domain name description of the server in a different message format
$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 ("Requested service [$host: $port] Temporarily unavailable, or Tor cannot arrive, and if it happens repeatedly, try restarting Tor, 9999;
       }
   }

/**
* Initiate an HTTP GET request
*
* @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;
}

/**
* Initiate an HTTP POST request
*
* @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;
   }

   /**
     * Update Tor's identity
     *
      * @param <type> $password
     * @param <type> $port
  & nbsp;  * @return <type>
     */
    Public Function newId ($ Password = ', $port = 9051)
    {
        if!empty ($ Password) && $password [0]!= ' "') {
            $ Password = ' "'. $password. '"';
       }

Create a connection to the Tor control terminal
@ $sock = Fsockopen ($this->_host, $port, $errorCode, $error, 5);
if ($errorCode) {
throw new Exception (' Cannot connect to Proxy server control, please check port number ');
}

Fwrite ($sock, "Authenticate {$password}n");
$resp = Fread ($sock, 1024);
if (!preg_match ('/^250/', $resp)) {
throw new Exception (' Tor control authentication failed, please confirm correct password ');
}

        fwrite ($sock, "SIGNAL newnymn");
        $resp = fread ($sock, 1024);
        if (!preg_match ('/^250/', $resp)) {
             throw new Exception (' Update identity failed, please try again ');
       }
        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;
   }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.