Skip to content

Instantly share code, notes, and snippets.

@aL3xa
Created March 6, 2012 17:45
Show Gist options
  • Save aL3xa/1987701 to your computer and use it in GitHub Desktop.
Save aL3xa/1987701 to your computer and use it in GitHub Desktop.
Send HTTP request from PHP
// send HTTP POST request
function send_http($url, $params = null, $type = 'GET')
{
$type = strtoupper($type); // request type
if (!preg_match('/^(GET|POST)$/', $type)) {
die("Unsupported method type: '$type'");
}
/* generate POST string */
$query_string = '';
if ($params){
foreach($params as $key => $value)
{
$query_string.= $key.'='.$value.'&';
}
$query_string = rtrim($query_string, '&'); // trim trailing ampersand
}
if (count($params)){
$url = $url . '?' . $query_string;
}
// cURL
$ch = curl_init(); // open cURL handler
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
if ($type == 'POST') {
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, $url);
}
$response = trim(curl_exec($ch)); // send request
curl_close($ch); // close handler
return ($response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment