HTTP Request without CURL

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.');
            }
        }

        return $this->_response;
    }

    private function _assemble()
    {
        $params = array(
        	'http' => array(
        		'method'  => $this->_method,
        		'content' => $this->_body
            )
        );

        if (!empty($this->_headers)) {
            $params['http']['header'] = $this->_headers;
        }

        return stream_context_create($params);
    }

    private function _openStream()
    {
        $this->_stream = @fopen($this->_url, 'rb', false, $this->_assemble());

        if (!$this->_stream) {
            throw new Exception('It was not possible to '
                              . "connect to {$this->_url}.");
        }
    }
}

More on this in my next post.

No user responded to this post

You must be logged in to post a comment.

full indir download