клас за HTTP connect

  • Автор Автор cnoko
  • Начална дата Начална дата

cnoko

Registered
Здравейте ето един код и от мене :)
с него можете да разлиствате, триете, свързвате с прокси, задавате post заявка и т.н.
Код:
<?php
class open
{
var $connection = false;
var $url;
var $server = false;
var $port = 80;
var $local = false;
var $filesize = 0;
var $headers = false;
var $SendHeaders;
var $timeout = 5;
var $default_method = 'GET';
var $protocolVersion = '1.1';
var $ssl;
var $default_HTTPMethod;
var $MyHeaders;
	function tell()
	{
		return @ftell($this->connection);
	}
	
	function seek($size,$mode = SEEK_SET)
	{
		if($this->local !== false)
		{
			@fseek($this->connection,$size);
			return true;
		}
		$fwrite = $this->SendHeaders;
		switch($mode)
		{
			case SEEK_SET:
				$size -= strlen($this->MyHeaders);
				break;
			case SEEK_END:
				$size = $this->size() - $size;
				break;
			case SEEK_CUR:
					$size = $this->tell() - strlen($this->MyHeaders) + $size;
				break;
		}
	
		$this->SendHeaders['range'] = "Range: bytes=$size-{$this->size()}\r\n";
		$this->close();
	    $this->sockopen();
	}
	function ip($server)
	{
		$url = @parse_url($server);
		if(!$url)
		{
			return false;
		}
		$url['port'] = (@$url['port']) ? ':'.$url['port'] : ((@$url['scheme'] == 'https')  ? ':443' : '');
		return gethostbyname($url['host'] . $url['port']);
	}
	function ping($server)
	{
		if(function_exists("exec"))
		{
			$str = @exec("Ping $server",$a);
			$a['str'] = $str;
			return $a;
		}
		if(function_exists("shell_exec"))
		{
			 return @explode("\n",shell_exec("Ping $server"));
		}
		return false;
	}
	
	function connect($url, $parrams = array())
	{
		if(file_exists($url))
		{
			$this->local = true;
			
			$this->url = $url;
			
			if( !($this->connection = @fopen($url, "r+b") ) )
			{
				return false;
			}
			return $this->connection;
		}
		$this->url 		 = $url;		
		if(!$this->headers)
		{
			if(!($this->headers = @get_headers($url,1)))
			{
				return false;
			}
			if(isset($this->headers['Location']))
			{
				$this->url = (is_array($this->headers['Location'])) ? 
							$this->location_uri($this->headers['Location'][sizeof($this->headers['Location'])-1]) 
							: $this->location_uri($this->headers['Location']);
			}
		}
		$url_info 		 = @parse_url($this->url);
		if(!$url_info)
		{
			return false;
		}
		$this->default_HTTPMethod = $this->default_method . " %s HTTP/" . $this->protocolVersion . "\r\n";
		$this->port 	 = (isset($url_info['scheme']) 
					&& $url_info['scheme'] == "https") ? 443 		 		 		 : 
							 (isset($url_info['port']) ? $url_info['port']  		 : 80);
		$this->server = $url_info['host'];
		$this->sll = ((isset($url_info['scheme']) && $url_info['scheme'] == "https") || $url_info['port'] == 443) ? 'ssl://' : '';
		$this->path  	 = (isset($url_info['path']))  ? $url_info['path']  	 : '';
		$this->query 	 = (isset($url_info['query'])) ? "?{$url_info['query']}" 	 : '';
		if($this->ssl == "ssl://" && $this->port == 5222)
		{
			$this->port = 5223;
		}
		if(is_array($parrams))
		{
			while(list($key,$value) = @each($parrams))
			{
				if(method_exists($this,$key))
				{
					$this->$key($value);
				}
			}
		}
		$this->SendHeaders['HTTPMethod'] = ((!@$this->SendHeaders['HTTPMethod']) ? 
											$this->default_HTTPMethod : $this->SendHeaders['HTTPMethod']);
		$this->SendHeaders['HTTPMethod'] = sprintf($this->SendHeaders['HTTPMethod'],
														 $this->path . $this->query,
														 $this->protocolVersion);
		$this->SendHeaders['host'] = "Host: " . $this->server . "\r\n";
		return $this->sockopen();
	}
	
	function setTimeOut($time)
	{
		if($time < 1)
		{
			return;
		}
		$this->timeout = $time;
	}
	
	function setSize($size)
	{
		$this->SendHeaders['range'] = "Accept-Ranges: bytes\r\nAccept-Range: bytes=".$size."\r\n";
	}
	
	function login($value)
	{
		$this->SendHeaders['Authorization'] = "Authorization: Basic ".base64_decode($value['username'] .':'. $value['password']);
	}
	
	function setReferer($value)
	{
		$this->SendHeaders['referer'] = $value;
	}
	
	function setUserAgent($value)
	{
		$this->SendHeaders['UserAgent'] = $value;
	}
	
	function setCharset($charset)
	{
		$charset = strtolower($charset);
		switch ($charset)
		{
			case                          'asmo-708':
			case                           'dos-720':
			case                        'iso-8859-6':
			case                      'x-mac-arabic':
			case                      'windows-1256':
			case                            'ibm775':
			case                        'iso-8859-4':
			case                      'windows-1257':
			case                            'ibm852':
			case                        'iso-8859-2':
			case                          'x-mac-ce':
			case                      'windows-1250':
			case                            'euc-cn':
			case                            'gb2312':
			case                        'hz-gb-2312':
			case                 'x-mac-chinesesimp':
			case                              'big5':
			case                     'x-chinese-cns':
			case                    'x-chinese-eten':
			case                               '950':
			case                             'cp866':
			case                        'iso-8859-5':
			case                            'koi8-r':
			case                            'koi8-u':
			case                    'x-mac-cyrillic':
			case                      'windows-1251':
			case                          'x-europa':
			case                      'x-ia5-german':
			case                            'ibm737':
			case                        'iso-8859-7':
			case                       'x-mac-greek':
			case                      'windows-1253':
			case                            'ibm869':
			case                           'dos-862':
			case                      'iso-8859-8-i':
			case                        'iso-8859-8':
			case                      'x-mac-hebrew':
			case                      'windows-1255':
			case                   'x-ebcdic-arabic':
			case          'x-ebcdic-cyrillicrussian':
			case 'x-ebcdic-cyrillicserbianbulgarian':
			case            'x-ebcdic-denmarknorway':
			case       'x-ebcdic-denmarknorway-euro':
			case            'x-ebcdic-finlandsweden':
			case       'x-ebcdic-finlandsweden-euro':
			case       'x-ebcdic-finlandsweden-euro':
			case              'x-ebcdic-france-euro':
			case                  'x-ebcdic-germany':
			case             'x-ebcdic-germany-euro':
			case              'x-ebcdic-greekmodern':
			case                    'x-ebcdic-greek':
			case                   'x-ebcdic-hebrew':
			case                'x-ebcdic-icelandic':
			case           'x-ebcdic-icelandic-euro':
			case       'x-ebcdic-international-euro':
			case                    'x-ebcdic-italy':
			case               'x-ebcdic-italy-euro':
			case          'x-ebcdic-japaneseandkana':
			case 'x-ebcdic-japaneseandjapaneselatin':
			case      'x-ebcdic-japaneseanduscanada':
			case         'x-ebcdic-japanesekatakana':
			case  'x-ebcdic-koreanandkoreanextended':
			case           'x-ebcdic-koreanextended':
			case                             'cp870':
			case        'x-ebcdic-simplifiedchinese':
			case                    'x-ebcdic-spain':
			case               'x-ebcdic-spain-euro':
			case                     'x-ebcdic-thai':
			case       'x-ebcdic-traditionalchinese':
			case                            'cp1026':
			case                  'x-ebcdic-turkish':
			case                       'x-ebcdic-uk':
			case                  'x-ebcdic-uk-euro':
			case                      'ebcdic-cp-us':
			case               'x-ebcdic-cp-us-euro':
			case                            'ibm861':
			case                   'x-mac-icelandic':
			case                        'x-iscii-as':
			case                        'x-iscii-be':
			case                        'x-iscii-de':
			case                        'x-iscii-gu':
			case                        'x-iscii-ka':
			case                        'x-iscii-ma':
			case                        'x-iscii-or':
			case                        'x-iscii-pa':
			case                        'x-iscii-ta':
			case                        'x-iscii-te':
			case                          'x-euc-jp':
			case                       'iso-2022-jp':
			case                       'iso-2022-jp':
			case                       'csiso2022jp':
			case                    'x-mac-japanese':
			case                         'shift_jis':
			case                    'ks_c_5601-1987':
			case                            'euc-kr':
			case                       'iso-2022-kr':
			case                             'johab':
			case                      'x-mac-korean':
			case                        'iso-8859-3':
			case                       'iso-8859-15':
			case                   'x-ia5-norwegian':
			case                            'ibm437':
			case                     'x-ia5-swedish':
			case                       'windows-874':
			case                            'ibm857':
			case                        'iso-8859-9':
			case                     'x-mac-turkish':
			case                      'windows-1254':
			case                           'unicode':
			case                       'unicodefffe':
			case                             'utf-7':
			case                             'utf-8':
			case                          'us-ascii':
			case                      'windows-1258':
			case                            'ibm850':
			case                             'x-ia5':
			case                        'iso-8859-1':
			case                         'macintosh':
			case                      'windows-1252':
				$this->SendHeaders['charset'] = "Accept-Charset: $charset";
				break;
			default:
				return false;
			break;
		}
	}
	function setEncoding($value)
	{
		$this->SendHeaders['encoding'] = "Content-Encoding: gzip\r\n";
	}
	function unlock($locked)
	{
		$this->SendHeaders['Lock-Token'] = $locked;
	}
	
	function lock($lock)
	{
		$this->SendHeaders[] = "<?xml version=\"1.0\" encoding=\"". @$lock['encoding']."\" ?>
<D:lockinfo xmlns:D='DAV:'>
<D:lockscope><D:".@$lock['Scope']."/></D:lockscope>\n<D:locktype><D:".$lock['Type'].'/></D:locktype>
	<D:owner><D:href>'.@$lock['Owner']."</D:href></D:owner>
</D:lockinfo>\n";
	}
	function post($value)
	{
		while(list($name,$value) = @each($value))
		{
			$PostArray[] = urlencode($name) . "=" . urlencode($value);
		}
		$this->SendHeaders['Content-Type'] = "application/x-www-form-urlencoded";
		$this->SendHeaders['POST'] = implode("&",$PostArray);
	}
	function method($method)
	{
		static $headers;
		if(empty($arrays))
		{
			$methods = array(
				"GET" 	  => true,
				"POST"    => true,
				"DELETE"  => true,
				//"COPY"    => true,
				"LOCK"    => true,
				"UNLOCK"  => true,
				"MKCOL"   => true,
				"MOVE"    => true,
				"HEAD"    => true,
				"PUT"     => true,
				"OPTIONS" => true,
			);
		}
		$method = strtoupper($method);
		$method = ((@$methods[$method]) ? $method : $this->default_method);
		$this->SendHeaders['HTTPMethod'] = $method . " %s HTTP/%s\r\n";
	}
	function location_uri($uri)
	{
		if(strpos($uri,"://") === false)
		{
			$url    = @parse_url($this->url);
			if(!$url)
			{
				die("Failed Connection in" . $this->url);
			}
			$scheme = (!@$url['scheme']) ? 'http://' : $url['scheme'] . '://';
			$port   = (isset($url['port']) && $url['port'] <> 80) ? ':'.$url['port'] : '';
			$path   = (isset($url['path'])) ? $url['path'] : '';
			return str_replace("//","/",($scheme . $url['host'].$url['port'] . '/' . $path . '/' . $uri));
		}
		return $uri;
	}
	function sockopen()
	{
		if(!$this->connection = fsockopen($this->ssl . $this->server,$this->port,$errmo,$errstr,$this->timeout))
		{
			return false;
		}
		$SendHeaders = $this->SendHeaders;
		$out = @$SendHeaders['HTTPMethod'] . $SendHeaders['host'];
		unset($SendHeaders['HTTPMethod'],$SendHeaders['host']);
		$out .= implode("",$SendHeaders);
		$this->write($out. "Keep-Alive: 300\r\nConnection: keep-alive\r\n\r\n");
		$this->clean_headers();
		return $this->connection;
	}
	
	function write($send)
	{	
		 @fwrite($this->connection,$send);
	}
	
	function clean_headers()
	{
       do
        {
            $this->MyHeaders .= $this->read(1);
        } while (!preg_match('/\\r\\n\\r\\n$/', $this->MyHeaders));
		//preg_replace("/(.*?)\:(.*?)[\r\n]/e",'$this->MyHeaders[\'$1\'] = \'$2\'',$headers);
	}
	
	function read($size)
	{
		$r = '';
		if ($size > 8192 && !$this->local)
		{
		  do
			{
				$size        -= 8192;
				$r .= fread($this->connection,8192);
			} while(!$this->eof() && $size > 8192 && !$this->status());
		}
		if ($size < 1 || !$this->status())
		{
			return $r;
		}
		$r 			   .= fread($this->connection,$size);
		return ($r);
	}
	function status()
	{
		return @socket_get_status($this->connection);
	}
	function size()
	{
		if($this->filesize)
		{
			return $this->filesize;
		}
		if($this->local)
		{
			$this->filesize = filesize($this->url);
			return $this->filesize;
		}
		if(@$this->headers['Content-Type'])
		{
			$this->filesize = ((!is_array($this->headers['Content-Length'])) ? $this->headers['Content-Length'] : $this->headers['Content-Length'][sizeof($this->headers['Content-Length'])-1]);
			return $this->filesize;
		}
		if(!$this->headers)
		{
			$this->headers = @get_headers($this->url,1);
			return $this->size();
		}
		return 0;
	}
	
		function close()
		{
			if($this->connection)
			{
				 @fclose($this->connection);
				 $this->connection = false;
				 return true;
			}
			
			return false;
		}
		
		function eof()
		{
			return @feof($this->connection);
		}
}
?>
ето как може да се ползва
//този масив не е задължителен зависи от него как ще направи connect-a използва се само когато се свързва с сайтове
Код:
<?php
$parrams = array(
	"setCharset"  => "windows-1251", //какъв чарсет да зададе за приемане от сървъра 
	"setEncoding" => true, //Връща еncoding gzip
	"method"      => "post/get/unlock/lock/delete/head/move/mkcol/put/options", //По кой метод ще се свържа със сървъра
	"post" 		  => array( //Трябва да сте задали метод post за да стане
	   "username" => "ludiamaniak :D",
	   "password" => "***********", //Изпраща post заявка към даден сървър
		),
	"unlock"      => "ne6to", // В случей че сте задали unclock метод
	"lock"		  => array(
				"Scope"=>"ne6to",
				"Owner"=>"sdrugo",
				"encoding" => "utf-8"
				),//В случай че сте задали метод lock
	"setReferer"  => "idvamotfaila.php", //:D
   "setUserAgent" => "Mozilla (blqblq/blqblq) Fifox 11.3", //novata versia
	"login" 	  => array( //Логване до прокси сървър 
	   "username" => "*****",
	   "password" => "*****",
		),
	"setSize" 	  => 19239132, //От кой байт да почне
	"setTimeOut"  => 5, //Колко пъти да повтори connecta  в случей че не може да се свърже
	);

$fsock = new open;
if($fsock->connect('http://sitename/.../',$parrams)
{
 echo "НЯма такъв url";
}
echo $fsock->read(50); //сеедно fread(50);
$fsock->seek($fsock->tell() + 50,SEEK_SET); //Сеедно fseek(ftell()+50,SEEK_SET);
$fsock->close();
echo $fsock->ping('web-tourist.net'); //:)
echo $fsock->ip('web-tourist.net');
lock,unlock,login и post не са тествани
 

Back
Горе