login  Naam:   Wachtwoord: 
Registreer je!
 Scripts:

Scripts > PHP > Handige scripts > HTTP Socket

HTTP Socket

Auteur: Phi1 'l0rdphi1' Stier - 24 maart 2007 - 12:01 - Gekeurd door: Ibrahim - Hits: 5841 - Aantal punten: 5.00 (1 stem)



Deze socket vond ik op het internet, ik heb het ook al op een ander forum geplaatst maar ik dacht misschien kan hij hier ook 

ik gebruik deze socket voor de DirectAdmin API's maar hij kan eigenlijk als socket gebruikt worden voor vanalles. (als het te doen valt met een http-socket uiteraard ;))

Een voorbeeld van het gebruik is wel voor de api's van DA.

VOORBEELD:

  1. <?php
  2. include("socket.class.php");
  3.  
  4. # gebruikersnaam voor DA
  5. $username = '';
  6.  
  7. # wachtwoord voor DA
  8. $pass = '';
  9.  
  10. # domein waar DA op draait.
  11. $domein = '';
  12.  
  13. //nou de socket is geinclude kunnen we hem starten
  14. $sock = new HTTPSocket;
  15.  
  16. //nu gaan we inloggen in Direct Admin (verander wel de gegevens)
  17. $sock->connect($domein, 2222);
  18. $sock->set_login($username, $pass);
  19.  
  20. $sock->set_method('POST');
  21.  
  22. $sock->query('/CMD_API_POP', array( 'action' => 'create', 'domain' => $domein, 'user' => 'apidemo', 'passwd' => 'test', 'quota' => 0), 1);
  23.  
  24. $result = $sock->fetch_body();
  25. echo $result;
  26.  
  27. ?>


de download komt binnenkort, ik ben bezig m'n open source library bij te werken.

Code:
--{ SOCKET.CLASS.PHP }--
  1. <?php
  2.  
  3. /**
  4.  * Socket communication class.
  5.  *
  6.  * Originally designed for use with DirectAdmin's API, this class will fill any HTTP socket need.
  7.  *
  8.  * Very, very basic usage:
  9.  * $Socket = new HTTPSocket;
  10.  * echo $Socket->get('http://user:pass@somesite.com/somedir/some.file?query=string&this=that');
  11.  *
  12.  * @author Phi1 'l0rdphi1' Stier <l0rdphi1@liquenox.net>
  13.  * @package HTTPSocket
  14.  * @version 2.6
  15.  */
  16. class HTTPSocket {
  17.  
  18. var $version = '2.6';
  19.  
  20. /* all vars are private except $error, $query_cache, and $doFollowLocationHeader */
  21.  
  22. var $method = 'GET';
  23.  
  24. var $remote_host;
  25. var $remote_port;
  26. var $remote_uname;
  27. var $remote_passwd;
  28.  
  29. var $result;
  30. var $result_header;
  31. var $result_body;
  32. var $result_status_code;
  33.  
  34. var $lastTransferSpeed;
  35.  
  36. var $bind_host;
  37.  
  38. var $error = array();
  39. var $warn = array();
  40. var $query_cache = array();
  41.  
  42. var $doFollowLocationHeader = TRUE;
  43. var $redirectURL;
  44.  
  45. var $extra_headers = array();
  46.  
  47. /**
  48.   * Create server "connection".
  49.   *
  50.   */
  51. function connect($host, $port = '' )
  52. {
  53. if (!is_numeric($port))
  54. {
  55. $port = 80;
  56. }
  57.  
  58. $this->remote_host = $host;
  59. $this->remote_port = $port;
  60. }
  61.  
  62. function bind( $ip = '' )
  63. {
  64. if ( $ip == '' )
  65. {
  66. $ip = $_SERVER['SERVER_ADDR'];
  67. }
  68.  
  69. $this->bind_host = $ip;
  70. }
  71.  
  72. /**
  73.   * Change the method being used to communicate.
  74.   *
  75.   * @param string|null request method. supports GET, POST, and HEAD. default is GET
  76.   */
  77. function set_method( $method = 'GET' )
  78. {
  79. $this->method = strtoupper($method);
  80. }
  81.  
  82. /**
  83.   * Specify a username and password.
  84.   *
  85.   * @param string|null username. defualt is null
  86.   * @param string|null password. defualt is null
  87.   */
  88. function set_login( $uname = '', $passwd = '' )
  89. {
  90. if ( strlen($uname) > 0 )
  91. {
  92. $this->remote_uname = $uname;
  93. }
  94.  
  95. if ( strlen($passwd) > 0 )
  96. {
  97. $this->remote_passwd = $passwd;
  98. }
  99.  
  100. }
  101.  
  102. /**
  103.   * Query the server
  104.   *
  105.   * @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too.
  106.   * @param string|array query to pass to url
  107.   * @param int if connection KB/s drops below value here, will drop connection
  108.   */
  109. function query( $request, $content = '', $doSpeedCheck = 0 )
  110. {
  111. $this->error = $this->warn = array();
  112. $this->result_status_code = NULL;
  113.  
  114. // is our request a http:// ... ?
  115. if (preg_match('!^http://!i',$request))
  116. {
  117. $location = parse_url($request);
  118. $this->connect($location['host'],$location['port']);
  119. $this->set_login($location['user'],$location['pass']);
  120.  
  121. $request = $location['path'];
  122. $content = $location['query'];
  123.  
  124. if ( strlen($request) < 1 )
  125. {
  126. $request = '/';
  127. }
  128.  
  129. }
  130.  
  131. $array_headers = array(
  132. 'User-Agent' => "HTTPSocket/$this->version",
  133. 'Host' => ( $this->remote_port == 80 ? $this->remote_host : "$this->remote_host:$this->remote_port" ),
  134. 'Accept' => '*/*',
  135. 'Connection' => 'Close' );
  136.  
  137. foreach ( $this->extra_headers as $key => $value )
  138. {
  139. $array_headers[$key] = $value;
  140. }
  141.  
  142. $this->result = $this->result_header = $this->result_body = '';
  143.  
  144. // was content sent as an array? if so, turn it into a string
  145. if (is_array($content))
  146. {
  147. $pairs = array();
  148.  
  149. foreach ( $content as $key => $value )
  150. {
  151. $pairs[] = "$key=".urlencode($value);
  152. }
  153.  
  154. $content = join('&',$pairs);
  155. unset($pairs);
  156. }
  157.  
  158. $OK = TRUE;
  159.  
  160. // instance connection
  161. if ($this->bind_host)
  162. {
  163. $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
  164. socket_bind($socket,$this->bind_host);
  165.  
  166. if (!@socket_connect($socket,$this->remote_host,$this->remote_port))
  167. {
  168. $OK = FALSE;
  169. }
  170.  
  171. }
  172. else
  173. {
  174. $socket = @fsockopen( $this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10 );
  175. }
  176.  
  177. if ( !$socket || !$OK )
  178. {
  179. $this->error[] = "Can't create socket connection to $this->remote_host:$this->remote_port.";
  180. return 0;
  181. }
  182.  
  183. // if we have a username and password, add the header
  184. if ( isset($this->remote_uname) && isset($this->remote_passwd) )
  185. {
  186. $array_headers['Authorization'] = 'Basic '.base64_encode("$this->remote_uname:$this->remote_passwd");
  187. }
  188.  
  189. // for DA skins: if $this->remote_passwd is NULL, try to use the login key system
  190. if ( isset($this->remote_uname) && $this->remote_passwd == NULL )
  191. {
  192. $array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}";
  193. }
  194.  
  195. // if method is POST, add content length & type headers
  196. if ( $this->method == 'POST' )
  197. {
  198. $array_headers['Content-type'] = 'application/x-www-form-urlencoded';
  199. $array_headers['Content-length'] = strlen($content);
  200. }
  201. // else method is GET or HEAD. we don't support anything else right now.
  202. else
  203. {
  204. if ($content)
  205. {
  206. $request .= "?$content";
  207. }
  208. }
  209.  
  210. // prepare query
  211. $query = "$this->method $request HTTP/1.0\r\n";
  212. foreach ( $array_headers as $key => $value )
  213. {
  214. $query .= "$key: $value\r\n";
  215. }
  216. $query .= "\r\n";
  217.  
  218. // if POST we need to append our content
  219. if ( $this->method == 'POST' && $content )
  220. {
  221. $query .= "$content\r\n\r\n";
  222. }
  223.  
  224. // query connection
  225. if ($this->bind_host)
  226. {
  227. socket_write($socket,$query);
  228.  
  229. // now load results
  230. while ( $out = socket_read($socket,2048) )
  231. {
  232. $this->result .= $out;
  233. }
  234. }
  235. else
  236. {
  237. fwrite( $socket, $query, strlen($query) );
  238.  
  239. // now load results
  240. $this->lastTransferSpeed = 0;
  241. $status = socket_get_status($socket);
  242. $startTime = time();
  243. $length = 0;
  244. $prevSecond = 0;
  245. while ( !feof($socket) && !$status['timed_out'] )
  246. {
  247. $chunk = fgets($socket,1024);
  248. $length += strlen($chunk);
  249. $this->result .= $chunk;
  250.  
  251. $elapsedTime = time() - $startTime;
  252.  
  253. if ( $elapsedTime > 0 )
  254. {
  255. $this->lastTransferSpeed = ($length/1024)/$elapsedTime;
  256. }
  257.  
  258. if ( $doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck )
  259. {
  260. $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~".( ($length/1024)/$elapsedTime )."), dropping connection...";
  261. $this->result_status_code = 503;
  262. break;
  263. }
  264.  
  265. }
  266.  
  267. if ( $this->lastTransferSpeed == 0 )
  268. {
  269. $this->lastTransferSpeed = $length/1024;
  270. }
  271.  
  272. }
  273.  
  274. list($this->result_header,$this->result_body) = split("\r\n\r\n",$this->result,2);
  275.  
  276. if ($this->bind_host)
  277. {
  278. socket_close($socket);
  279. }
  280. else
  281. {
  282. fclose($socket);
  283. }
  284.  
  285. $this->query_cache[] = $query;
  286.  
  287.  
  288. $headers = $this->fetch_header();
  289.  
  290. // what return status did we get?
  291. if (!$this->result_status_code)
  292. {
  293. preg_match("#HTTP/1\.. (\d+)#",$headers[0],$matches);
  294. $this->result_status_code = $matches[1];
  295. }
  296.  
  297. // did we get the full file?
  298. if ( !empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body) )
  299. {
  300. $this->result_status_code = 206;
  301. }
  302.  
  303. // now, if we're being passed a location header, should we follow it?
  304. if ($this->doFollowLocationHeader)
  305. {
  306. if ($headers['location'])
  307. {
  308. $this->redirectURL = $headers['location'];
  309. $this->query($headers['location']);
  310. }
  311. }
  312.  
  313. }
  314.  
  315. function getTransferSpeed()
  316. {
  317. return $this->lastTransferSpeed;
  318. }
  319.  
  320. /**
  321.   * The quick way to get a URL's content :)
  322.   *
  323.   * @param string URL
  324.   * @param boolean return as array? (like PHP's file() command)
  325.   * @return string result body
  326.   */
  327. function get($location, $asArray = FALSE )
  328. {
  329. $this->query($location);
  330.  
  331. if ( $this->get_status_code() == 200 )
  332. {
  333. if ($asArray)
  334. {
  335. return split("\n",$this->fetch_body());
  336. }
  337.  
  338. return $this->fetch_body();
  339. }
  340.  
  341. return FALSE;
  342. }
  343.  
  344. /**
  345.   * Returns the last status code.
  346.   * 200 = OK;
  347.   * 403 = FORBIDDEN;
  348.   * etc.
  349.   *
  350.   * @return int status code
  351.   */
  352. function get_status_code()
  353. {
  354. return $this->result_status_code;
  355. }
  356.  
  357. /**
  358.   * Adds a header, sent with the next query.
  359.   *
  360.   * @param string header name
  361.   * @param string header value
  362.   */
  363. function add_header($key,$value)
  364. {
  365. $this->extra_headers[$key] = $value;
  366. }
  367.  
  368. /**
  369.   * Clears any extra headers.
  370.   *
  371.   */
  372. function clear_headers()
  373. {
  374. $this->extra_headers = array();
  375. }
  376.  
  377. /**
  378.   * Return the result of a query.
  379.   *
  380.   * @return string result
  381.   */
  382. function fetch_result()
  383. {
  384. return $this->result;
  385. }
  386.  
  387. /**
  388.   * Return the header of result (stuff before body).
  389.   *
  390.   * @param string (optional) header to return
  391.   * @return array result header
  392.   */
  393. function fetch_header( $header = '' )
  394. {
  395. $array_headers = split("\r\n",$this->result_header);
  396.  
  397. $array_return = array( 0 => $array_headers[0] );
  398. unset($array_headers[0]);
  399.  
  400. foreach ( $array_headers as $pair )
  401. {
  402. list($key,$value) = split(": ",$pair,2);
  403. $array_return[strtolower($key)] = $value;
  404. }
  405.  
  406. if ( $header != '' )
  407. {
  408. return $array_return[strtolower($header)];
  409. }
  410.  
  411. return $array_return;
  412. }
  413.  
  414. /**
  415.   * Return the body of result (stuff after header).
  416.   *
  417.   * @return string result body
  418.   */
  419. function fetch_body()
  420. {
  421. return $this->result_body;
  422. }
  423.  
  424. /**
  425.   * Return parsed body in array format.
  426.   *
  427.   * @return array result parsed
  428.   */
  429. function fetch_parsed_body()
  430. {
  431. parse_str($this->result_body,$x);
  432. return $x;
  433. }
  434.  
  435. }
  436.  
  437. ?>
Download code! Download code (.txt)

 Stemmen
Niet ingelogd.

 Reacties
Post een reactie
Lees de reacties (5)
© 2002-2024 Sitemasters.be - Regels - Laadtijd: 0.058s