PHP – Making API calls on the internet via Proxy

I had to make API calls to the internet from one of my servers that didn’t have connectivity to the outside world. I had IT create an internal proxy for me and I used it in the CURL to make the API call. Here’s the generic function that I created that would take care of using the proxy if stated to do so.

define('CONST_INTERNET_PROXY', '192.168.135.63:3128');

//-- Function to POST data to URL
function postArray($url, $arr_data, $setInternetProxy = false) {
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL, $url);
	if($setInternetProxy) {
		curl_setopt($ch, CURLOPT_PROXY, CONST_INTERNET_PROXY);
	}
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
	curl_setopt($ch, CURLOPT_POSTFIELDS, $arr_data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_FAILONERROR,true);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
	$response = curl_exec($ch);
	$error = curl_error($ch);
	curl_close($ch);
	$arr_response = array();
	$arr_response['response'] = trim($response);
	$arr_response['error'] = trim($error);
	return $arr_response;
}
Advertisements

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