Created
February 24, 2012 05:27
-
-
Save jaytaylor/1898009 to your computer and use it in GitHub Desktop.
Asynchronous HTTP requests for PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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