9 The HttpRequest class can be used to execute any HTTP request method.
10 The following example shows a simple GET request where a few query
11 parameters are supplied. Additionally potential cookies will be
12 read from and written to a file.
15 $r = new HttpRequest('http://www.google.com/search');
17 // store Googles cookies in a dedicated file
20 array( 'cookiestore' => 'google.txt',
25 array( 'q' => '+"pecl_http" -msg -cvs -list',
30 // HttpRequest::send() returns an HttpMessage object
31 // of type HttpMessage::TYPE_RESPONSE or throws an exception
33 print $r->send()->getBody();
34 } catch (HttpException $e) {
41 The following example shows an multipart POST request, with two form
42 fields and an image that's supposed to be uploaded to the server.
43 It's a bad habit as well as common practice to issue a redirect after
44 an received POST request, so we'll allow a redirect by enabling the
48 $r = new HttpRequest('http://dev.iworks.at/.print_request.php', HTTP_METH_POST);
50 // if redirects is set to true, a single redirect is allowed;
51 // one can set any reasonable count of allowed redirects
53 array( 'cookies' => array('MyCookie' => 'has a value'),
60 array( 'name' => 'Mike',
61 'mail' => 'mike@php.net',
64 // add the file to post (form name, file name, file type)
66 $r->addPostFile('image', 'profile.jpg', 'image/jpeg');
69 print $r->send()->getBody();
70 } catch (HttpException $e) {
77 It's possible to execute several HttpRequests in parallel with the
78 HttpRequestPool class. HttpRequests to send, do not need to perform
79 the same request method, but can only be attached to one HttpRequestPool
84 $p = new HttpRequestPool;
85 // if you want to set _any_ options of the HttpRequest object,
86 // you need to do so *prior attaching* to the request pool!
87 $p->attach(new HttpRequest('http://pear.php.net', HTTP_METH_HEAD));
88 $p->attach(new HttpRequest('http://pecl.php.net', HTTP_METH_HEAD));
89 } catch (HttpException $e) {
96 // HttpRequestPool implements an iterator over attached HttpRequest objects
98 echo "Checking ", $r->getUrl(), " reported ", $r->getResponseCode(), "\n";
100 } catch (HttpException $e) {
107 You can use a more advanced approach by using the protected interface of
108 the HttpRequestPool class. This allows you to perform some other tasks
109 while the requests are executed.
112 class Pool extends HttpRequestPool
114 public function __construct()
117 new HttpRequest('http://pear.php.net', HTTP_METH_HEAD),
118 new HttpRequest('http://pecl.php.net', HTTP_METH_HEAD)
121 // HttpRequestPool methods socketPerform() and socketSelect() are
122 // protected; one could use this approach to do something else
123 // while the requests are being executed
124 print "Executing requests";
125 for ($i = 0; $this->socketPerform(); $i++) {
126 $i % 10 or print ".";
127 if (!$this->socketSelect()) {
128 throw new HttpException("Socket error!");
136 foreach (new Pool as $r) {
137 echo "Checking ", $r->getUrl(), " reported ", $r->getResponseCode(), "\n";
139 } catch (HttpException $ex) {
146 One of the main key features of HttpResponse is HTTP caching. HttpResponse
147 will calculate an ETag based on the http.etag_mode INI setting as well as
148 it will determine the last modification time of the sent entity. It uses
149 those two indicators to decide if the cache entry on the client side is
150 still valid and will emit an "304 Not Modified" response if applicable.
153 HttpResponse::setCacheControl('public');
154 HttpResponse::setCache(true);
155 HttpResponse::capture();
157 print "This will be cached until content changes!\n";
158 print "Note that this approach will only save the clients download time.\n";
161 - Bandwidth Throttling
163 HttpResponse supports a basic throttling mechanism, which is enabled by
164 setting a throttle delay and a buffer size. PHP will sleep the specified
165 amount of seconds after each sent chunk of specified bytes.
168 // send 5000 bytes every 0.2 seconds, i.e. max ~25kByte/s
169 HttpResponse::setThrottleDelay(0.2);
170 HttpResponse::setBufferSize(5000);
171 HttpResponse::setCache(true);
172 HttpResponse::setContentType('application/x-zip');
173 HttpResponse::setFile('../archive.zip');
174 HttpResponse::send();
188 public function __construct($url, $namespace = '')
190 $this->namespace = $namespace;
191 $this->request = new HttpRequest($url, HTTP_METH_POST);
192 $this->request->setContentType('text/xml');
195 public function setOptions($options = array())
197 return $this->request->setOptions($options);
200 public function addOptions($options)
202 return $this->request->addOptions($options);
205 public function __call($method, $params)
207 if ($this->namespace) {
208 $method = $this->namespace .'.'. $method;
210 $this->request->setRawPostData(xmlrpc_encode_request($method, $params));
211 $response = $this->request->send();
212 if ($response->getResponseCode() != 200) {
213 throw new Exception($response->getBody(), $response->getResponseCode());
215 return xmlrpc_decode($response->getBody(), 'utf-8');
218 public function getHistory()
220 return $this->request->getHistory();
226 - Simple Feed Aggregator
232 protected $feeds = array();
234 public function __construct($directory = 'feeds')
236 $this->setDirectory($directory);
239 public function setDirectory($directory)
241 $this->directory = $directory;
242 foreach (glob($this->directory .'/*.xml') as $feed) {
243 $this->feeds[basename($feed, '.xml')] = filemtime($feed);
247 public function url2name($url)
249 return preg_replace('/[^\w\.-]+/', '_', $url);
252 public function hasFeed($url)
254 return isset($this->feeds[$this->url2name($url)]);
257 public function addFeed($url)
259 $r = $this->setupRequest($url);
261 $this->handleResponse($r);
264 public function addFeeds($urls)
266 $pool = new HttpRequestPool;
267 foreach ($urls as $url) {
268 $pool->attach($r = $this->setupRequest($url));
272 foreach ($pool as $request) {
273 $this->handleResponse($request);
277 public function getFeed($url)
279 $this->addFeed($url);
280 return $this->loadFeed($this->url2name($url));
283 public function getFeeds($urls)
286 $this->addFeeds($urls);
287 foreach ($urls as $url) {
288 $feeds[] = $this->loadFeed($this->url2name($url));
293 protected function saveFeed($file, $contents)
295 if (file_put_contents($this->directory .'/'. $file .'.xml', $contents)) {
296 $this->feeds[$file] = time();
298 throw new Exception("Could not save feed contents to $file.xml");
302 protected function loadFeed($file)
304 if (isset($this->feeds[$file])) {
305 if ($data = file_get_contents($this->directory .'/'. $file .'.xml')) {
308 throw new Exception("Could not load feed contents from $file.xml");
311 throw new Exception("Unknown feed/file $file.xml");
315 protected function setupRequest($url)
317 $r = new HttpRequest($url);
318 $r->setOptions(array('redirect' => true));
320 $file = $this->url2name($url);
322 if (isset($this->feeds[$file])) {
323 $r->setOptions(array('lastmodified' => $this->feeds[$file]));
329 protected function handleResponse(HttpRequest $r)
331 if ($r->getResponseCode() != 304) {
332 if ($r->getResponseCode() != 200) {
333 throw new Exception("Unexpected response code ". $r->getResponseCode());
335 if (!strlen($body = $r->getResponseBody())) {
336 throw new Exception("Received empty feed from ". $r->getUrl());
338 $this->saveFeed($this->url2name($r->getUrl()), $body);
344 - Download a big file
349 $bigGet = BigGet::url('http://www.example.com/big_file.bin');
350 $bigGet->saveTo('file.bin');
353 class BigGetRequest extends HttpRequest
358 class BigGet extends HttpRequestPool
360 const SIZE = 1048576;
365 private $files = array();
367 static function url($url)
369 $head = new HttpRequest($url, HttpRequest::METH_HEAD);
370 $headers = $head->send()->getHeaders();
373 if (!isset($headers['Accept-Ranges'])) {
374 throw new HttpException("Did not receive an Accept-Ranges header from HEAD $url");
376 if (!isset($headers['Content-Length'])) {
377 throw new HttpException("Did not receive a Content-Length header from HEAD $url");
380 $bigget = new BigGet;
382 $bigget->size = $headers['Content-Length'];
386 function saveTo($file)
389 if ($w = fopen($file, 'wb')) {
390 echo "\nCopying temp files to $file ...\n";
391 foreach (glob("bigget_????.tmp") as $tmp) {
393 if ($r = fopen($tmp, 'rb')) {
394 stream_copy_to_stream($r, $w);
406 // use max 3 simultanous requests with a req size of 1MiB
407 while ($this->count < 3 && -1 != $offset = $this->getRangeOffset()) {
408 $this->attachNew($offset);
411 while ($this->socketPerform()) {
412 if (!$this->socketSelect()) {
413 throw new HttpSocketException;
418 private function attachNew($offset)
420 $stop = min($this->count * self::SIZE + self::SIZE, $this->size) - 1;
422 echo "Attaching new request to get range: $offset-$stop\n";
424 $req = new BigGetRequest(
426 HttpRequest::METH_GET,
429 'Range' => "bytes=$offset-$stop"
434 $req->id = $this->count++;
437 private function getRangeOffset()
439 return ($this->size >= $start = $this->count * self::SIZE) ? $start : -1;
442 protected function socketPerform()
445 $rc = parent::socketPerform();
446 } catch (HttpRequestPoolException $x) {
447 foreach ($x->exceptionStack as $e) {
448 echo $e->getMessage(), "\n";
452 foreach ($this->getFinishedRequests() as $r) {
455 if (206 != $rc = $r->getResponseCode()) {
456 throw new HttpException("Unexpected response code: $rc");
459 file_put_contents(sprintf("bigget_%04d.tmp", $r->id), $r->getResponseBody());
461 if (-1 != $offset = $this->getRangeOffset()) {
462 $this->attachNew($offset);