Making HTTP POST Requests in PHP


Recently at my job I have had several situations in which I needed to pass fairly large amounts of data to a particular page on a website for processing, and in which submitting a form isn’t a feasible option. Typically in this situation one would attempt to append the data to the url using GET parameters, but sometimes your data is too large or too sensitive to pass through the URL. Unfortunately, PHP does not provide an easy way to make post requests natively. Luckily for us, there is cURL. cURL allows us to communicate across multiple protocols to a variety of different server types. With cURL, we are able to make HTTP POST requests:

function post_request($url, $data) {
	$output = array();
	foreach ($data as $key => $value) {
		if(is_object($value) || is_array($value)){
			$data[$key] = serialize($value);
		}
	}
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HEADER, false);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	$result = curl_exec($ch);
	if ($result) {
		$output['status'] = "ok";
		$output['content'] = $result;
	} else {
		$output['status'] = "failure";
		$output['error'] = curl_error($ch);
	}
	curl_close($ch);
	return $output;

}

The above function accepts two parameters, the URL to make the request to, and an associative array containing the keys and values you would like to submit with your POST request. The function returns an associative array containing two values: status, which will either be equal to “ok” or “failure” depending on the success or failure of the POST request; and either ‘content’ or ‘error’ depending on success or failure. In the case of a successful POST request, ‘content’ will contain the full output from the page you have posted to (In other words, you may need to be prepared for an entire html document). Otherwise, ‘error’ will contain the details of the error as returned by cURL.

Advertisements
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s