Skip to content

Instantly share code, notes, and snippets.

@kyletaylored
Created September 3, 2021 18:47
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 kyletaylored/7a80f7a3ae8acbfe79ba707779b8c557 to your computer and use it in GitHub Desktop.
Save kyletaylored/7a80f7a3ae8acbfe79ba707779b8c557 to your computer and use it in GitHub Desktop.
Simple PHP fetch command
/**
* Simple PHP Fetch command
*
* @param string $method
* @param string $url
* @param string $body
* @param array $headers
* @return void
*/
function fetch(string $method, string $url, string $body, array $headers = []) {
$context = stream_context_create([
"http" => [
// http://docs.php.net/manual/en/context.http.php
"method" => $method,
"header" => implode("\r\n", $headers),
"content" => $body,
"ignore_errors" => true,
],
]);
$response = file_get_contents($url, false, $context);
/**
* @var array $http_response_header materializes out of thin air
*/
$status_line = $http_response_header[0];
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
$status = $match[1];
if ($status > "400") {
throw new RuntimeException("unexpected response status: {$status_line}\n" . $response);
}
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment