Get HTTP Request Headers and Body

digital-ether 0 Tallied Votes 11K Views Share

Searching the net I couldn't find a simple way of retrieving HTTP Request Headers and HTTP Request Body in a PHP Script.

PECL extensions offer this but not a standard PHP install.

So heres a simple class that will do it for you.

Docs in my blog: http://fijiwebdesign.com/content/view/90/77/

<?php

/**
* Access the HTTP Request
*/
class http_request {

	/** additional HTTP headers not prefixed with HTTP_ in $_SERVER superglobal */
	var $add_headers = array('CONTENT_TYPE', 'CONTENT_LENGTH');

	/**
	* Construtor
	* Retrieve HTTP Body
	* @param Array Additional Headers to retrieve
	*/
	function http_request($add_headers = false) {
	
		$this->retrieve_headers($add_headers);
		$this->body = @file_get_contents('php://input');
	}
	
	/**
	* Retrieve the HTTP request headers from the $_SERVER superglobal
	* @param Array Additional Headers to retrieve
	*/
	function retrieve_headers($add_headers = false) {
		
		if ($add_headers) {
			$this->add_headers = array_merge($this->add_headers, $add_headers);
		}
	
		if (isset($_SERVER['HTTP_METHOD'])) {
			$this->method = $_SERVER['HTTP_METHOD'];
			unset($_SERVER['HTTP_METHOD']);
		} else {
			$this->method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : false;
		}
		$this->protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : false;
		$this->request_method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : false;
		
		$this->headers = array();
		foreach($_SERVER as $i=>$val) {
			if (strpos($i, 'HTTP_') === 0 || in_array($i, $this->add_headers)) {
				$name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
				$this->headers[$name] = $val;
			}
		}
	}
	
	/** 
	* Retrieve HTTP Method
	*/
	function method() {
		return $this->method;
	}
	
	/** 
	* Retrieve HTTP Body
	*/
	function body() {
		return $this->body;
	}
	
	/** 
	* Retrieve an HTTP Header
	* @param string Case-Insensitive HTTP Header Name (eg: "User-Agent")
	*/
	function header($name) {
		$name = strtoupper($name);
		return isset($this->headers[$name]) ? $this->headers[$name] : false;
	}
	
	/**
	* Retrieve all HTTP Headers 
	* @return array HTTP Headers
	*/
	function headers() {
		return $this->headers;
	}
	
	/**
	* Return Raw HTTP Request (note: This is incomplete)
	* @param bool ReBuild the Raw HTTP Request
	*/
	function raw($refresh = false) {
	
		if (isset($this->raw) && !$refresh) {
			return $this->raw; // return cached
		}
	
		$headers = $this->headers();
		$this->raw = "{$this->method}\r\n";
		
		foreach($headers as $i=>$header) {
				$this->raw .= "$i: $header\r\n";
		}
		
		$this->raw .= "\r\n{$http_request->body}";
		
		return $this->raw;
	}

}

/**
* Example Usage
* Echos the HTTP Request back to the client/browser
*/

$http_request = new http_request();

$resp = $http_request->raw();
echo nl2br($resp);

?>
inakiabt 0 Newbie Poster

apache_request_headers() + $GLOBALS

moshaur 0 Newbie Poster

Thanks, this is great php code to read the api info sent using Post from another website, but I want to get only specific values sent using api. for example I want to know user_email how can get that.

Member Avatar for diafol
diafol

This depends on the API. Perhaps the api itself has a method for just picking certain data. Otherwise you just get hold of the data and navigate to the particular object or array item.

API can return all sorts of data formats, but json is becoming very popular.

The json_decode() function will turn the json data into a stdClass object, which you can traverse. Additionally the json_decode() function with its second parameter set to true will create the comparable associated array. Example...

$data = json_decode(file_get_contents('http://www.example.com/api/sample/'), true); //get associated array

$email = $data['user_email'];

$data = json_decode(file_get_contents('http://www.example.com/api/sample/')); //get data as stdClass object

$email = $data->user_email;
moshaur 0 Newbie Poster

Thank you diafol, the problem is I don't know the url to use file_get_contents, the other site will send data like (api_type:ping, purchase_id, token, full_name, email_address, and country_code) about a product to my api page, I have my account_secret_code my api page must read posted data via api and compare the token with generated token if it is correct then store the information in the data base, my problem is in reading posted data, I tried to use this code which is from the above code in the article:

$headers = array();
    foreach($_SERVER as $i=>$val) {
    $name = str_replace(array('HTTP_', '_'), array('', '-'), $i);
    $headers[$name] = $val;
    }

echo $headers['USER-EMAIL'];

I used this website to simulate sending data and I saw the email I sent.
https://apigee.com/console/others

Is that right or there is something else, by the way I use codeigniter to make the api page that will read and store data sent via api, I found there is RESTful library for codeigniter but I couldn't understand how to use it :(
Regards,

Member Avatar for diafol
diafol

Sorry, I haven't used CI for years. ANybody else?

veedeoo 474 Junior Poster Featured Poster

@moshaur,

ask the API provider about the proper protocol in accessing their API service. Normally, they will provide you with sample codes to access and the expected response format.

As far as the CI implementation is concern, please read this tutorial. The instructions are pretty straight forward.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.