HTTP Request without CURL
January 8, 2009 No comments yet
A short tutorial on how to make a simple object for HTTP request without the need of using CURL.
The way to accomplish that is using the function stream_context_create to prepare the string, and then you use fopen and stream_get_contents to get the response.
<?php
class Custom_Http_Request
{
private $_url;
private $_body;
private $_method = 'POST';
private $_headers = array();
private $_response;
private $_stream;
public function __construct($url, $body)
{
if (empty($url) || empty($body)) {
throw new Exception('Both URL and BODY are required '
. 'for fetching the request.');
}
$this->_url = $url;
$this->_body = $body;
}
public function setMethod($method)
{
if ('POST' == $method || 'GET' == $method) {
$this->_method = $method;
return $this;
}
throw new Exception('Invalid method set.');
}
public function addHeader(array $header)
{
if (!empty($header)) {
$this->_headers[] = $header;
return $this;
}
throw new Exception('The headers are empty.');
}
public function getMethod()
{
return $this->_method;
}
public function getBody()
{
return $this->_body;
}
public function getHeaders()
{
return $this->_headers;
}
public function getResponse()
{
if (is_null($this->_stream)) {
$this->_openStream();
}
if (is_null($this->_response)) {
$this->_response = @stream_get_contents($this->_stream);
if (false === $this->_response) {
throw new Exception('It is not possible to '
. 'read from the response.');
}
}
…


