2 /* $Id: socket.php,v 1.3 2002/09/08 19:25:02 shaggy Exp $ */
5 Copyright (c) 2001, 2002 by Martin Tsachev. All rights reserved.
8 Redistribution and use in source and binary forms,
9 with or without modification, are permitted provided
10 that the conditions available at
11 http://www.opensource.org/licenses/bsd-license.html
15 // From http://www.mtdev.com/download/2002/09/http-keep-alive-connections-in-php/socket.phps
24 var $accept = 'text/plain'; // MIME types to accept
25 var $lang = 'en'; // Language to accept
27 var $headers; // response headers
28 var $body; // response body
30 var $status; // HTTP status
31 var $connection; // Connection type: close/keep-alive
32 var $te; // Transfer encoding
33 var $type; // returned MIME type
36 function Socket($host, $ssl=false) {
42 function setAccept($types) {
43 $this->accept
= $types;
51 $host = "ssl://$host";
54 $this->fp
= fsockopen($host, $port, $errno, $errstr, $this->timeout
);
57 return "Network error: $errstr ($errno)";
64 function disconnect() {
71 "GET $uri HTTP/1.1\r\n" .
72 "Host: $this->host\r\n" .
73 "Connection: Keep-Alive\r\n" .
74 //"Accept: $this->accept\r\n" .
75 //"Accept-Language: $this->lang\r\n" .
76 //"Accept-Encoding: chunked\r\n" .
77 //"User-Agent: PHP/4.2.1\r\n" .
80 fputs($this->fp
, $request);
82 $this->headers
= fgets($this->fp
, $this->maxlen
);
83 if (!$this->headers
) { // if disconnected meanwhile
85 fputs($this->fp
, $request);
86 $this->headers
= fgets($this->fp
, $this->maxlen
);
89 preg_match('|^HTTP.+? (\d+?) |', $this->headers
, $matches);
90 $this->status
= $matches[1];
93 $this->connection
= '';
96 while ($line = fgets($this->fp
, $this->maxlen
)) {
97 if ($line == "\r\n") { break; }
99 if (preg_match('/^Content-Length: (.+)/', $line, $matches)) {
100 $length = (int) trim($matches[1]);
103 if (preg_match('/^Content-Type: (.+)/', $line, $matches)) {
104 $this->type
= strtolower(trim($matches[1]));
107 if (preg_match('/^Connection: (.+)/', $line, $matches)) {
108 $this->connection
= strtolower(trim($matches[1]));
111 if (preg_match('/^Transfer-Encoding: (.+)/', $line, $matches)) {
112 $this->te
= strtolower(trim($matches[1]));
115 $this->headers
.= $line;
119 if ($this->connection
== 'close') {
120 while (!feof($this->fp
)) {
121 $this->body
.= fread($this->fp
, $this->maxlen
);
126 if (isset($length) and strpos($this->te
, 'chunked') === false) {
128 while ($length > 0) {
129 $str = fread($this->fp
, $length);
131 $length -= strlen($str);
137 $length = rtrim(fgets($this->fp
, $this->maxlen
));
138 $length = hexdec($length);
141 if ($length < 1) { break; }
142 $this->body
.= fread($this->fp
, $length);
144 fgets($this->fp
, $this->maxlen
);
145 $length = rtrim(fgets($this->fp
, $this->maxlen
));
146 $length = hexdec($length);
149 fgets($this->fp
, $this->maxlen
);