Skip to content

Instantly share code, notes, and snippets.

@mebjas
Forked from jaytaylor/curl_request_async.inc.php
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mebjas/9cfe7ab6b00ee51aaaf4 to your computer and use it in GitHub Desktop.
Save mebjas/9cfe7ab6b00ee51aaaf4 to your computer and use it in GitHub Desktop.
<?php
/**
* @author Jay Taylor [@jtaylor]
*
* @date 2012-02-23
*
* @description Originally found on SO:
* http://stackoverflow.com/questions/962915/how-do-i-make-an-asynchronous-get-request-in-php
*/
/**
* @param $requestMethod must equal 'GET' or 'POST'
* @param $timeout Timeout alue (in seconds)
*/
function curl_request_async($url, $paramsOrBody=NULL, $requestMethod='POST', $timeout=30) {
$paramsType = gettype($paramsOrBody);
if ('array' == $paramsType || 'object' == $paramsType) {
foreach ((array)$paramsOrBody as $key => $val) {
// Cast to array if needed.
if (is_object($val)) {
$val = (array)$val;
}
if (is_array($val)) {
$val = count($val) == 0 ? '' : implode(',', $val);
}
$preppedParams[] = $key . '=' . urlencode($val);
}
$encodedParams = implode('&', $preppedParams);
} elseif (NULL != $paramsOrBody && 0 != strlen($paramsOrBody)) {
// Assume "$paramsOrBody" should be sent as the BODY (as an encoded string.)
$encodedParams = urlencode($paramsOrBody);
//error_log("-------->".$encodedParams.'<--------');
}
$hasParams = isset($encodedParams) && strlen($encodedParams) != 0;
$parts = parse_url($url);
error_log(var_export($parts, true));
$fp = fsockopen(
$parts['host'],
array_key_exists('port', $parts) ? $parts['port'] : 80,
$errno,
$errstr,
$timeout
);
// Data goes in the path for a GET request.
if ($hasParams && 'GET' == $requestMethod) {
$parts['path'] .= '?' . $encodedParams;
}
$out = strtoupper($requestMethod) . ' ' . $parts['path'] . ' HTTP/1.1' . "\r\n" .
'Host: ' . $parts['host'] . "\r\n" .
'Content-Type: application/x-www-form-urlencoded' . "\r\n" .
'Content-Length: ' . strlen($encodedParams) . "\r\n" .
'Connection: Close' . "\r\n\r\n";
// Data goes in the request body for a POST request.
if ($hasParams && 'POST' == $requestMethod) {
//error_log("POST PARAMS: $encodedParams");
$out .= $encodedParams;
}
fwrite($fp, $out);
fclose($fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment