Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function async_request($method, $url, $params, array $headers = [])
{
$method = strtoupper($method);
$data = http_build_query($params);
$parts = parse_url($url) + [
'port' => 80,
'path' => '/',
];
$headers += [
'Content-Type' => 'application/x-www-form-urlencoded',
'Host' => $parts['host'],
'Content-Length' => $method == 'GET' ? 0 : strlen($data),
'Connection' => 'Close',
];
$path = ($method == 'GET') ? $parts['path'] . '?' . $data : $parts['path'];
$output_header = sprintf('%s %s HTTP/1.1', $method, $path) . "\r\n";
foreach ($headers as $name => $value)
{
foreach((array) $value as $v)
{
$output_header .= "$name: $v\r\n";
}
}
$output_header .= "\r\n";
$handle = @fsockopen($parts['host'], $parts['port'], $_errno, $_errstr, 30);
if ($handle === false)
{
throw new \RuntimeException($_errstr);
}
fwrite($handle, $output_header);
if ($method !== 'GET') fwrite($handle, $data);
fclose($handle);
return $output_header;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment