Skip to content

Instantly share code, notes, and snippets.

@wallacemaxters
Created March 28, 2016 16:57
Show Gist options
  • Save wallacemaxters/b39c9e069a2e71e71bea to your computer and use it in GitHub Desktop.
Save wallacemaxters/b39c9e069a2e71e71bea to your computer and use it in GitHub Desktop.
<?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