[Drupal] How to use drupal_http_request()?

Zyxware default image4

You might have seen how to set up http request in core PHP. In this article I'm introducing a Drupal function called 'drupal_http_request' which handles our http request.

While using core PHP code to build http request we should be bothered about its input types, status codes and so on. Drupal introduces this method which ensures the simplicity. On calling the function we will be getting a number of responses. Now lets move to our code.

Recently I had one requirement on a project, where I wanted to send a request to a number of domains to check if it is active or not. PHP provides one useful method by using cURL. cURL can be used in Drupal, but the Drupal provides its own mechanism of sending an http request. Syntax: drupal_http_request($url, array $options = array()). This handles GET, POST, PUT or any other HTTP requests.

Let's check how drupal_http_request() make request.

 'POST', // HTTP Request Type
    'data' => $data, // Parameters
    'headers' => array('Content-Type' => 'application/x-www-form-urlencoded'),
  $result = drupal_http_request('http://example-site.com', $options); // Make request

The function takes two arguments first is the URL to make request and second is array of values which is optional. The array can have the following values:

  1. headers: Array containing request headers to send as name/value pairs.
  2. method: Request method (GET/POST)
  3. data: Request body, formatted as query strings this will defaults to null.
  4. max_redirects: Redirect value, which tells the times to be redirected, (default value: 3)
  5. timeout: Default timeout is 30 secs, after timeout error code will be set to HTTP_REQUEST_TIMEOUT constant.

The function returns an object that can have one or more of the components such as request, code, protocol , redirect_code, status_message etc.

Reference link: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_http_request/7

Please fell free to share your thoughts and doubts regarding this here.