Created
September 3, 2021 18:47
-
-
Save kyletaylored/7a80f7a3ae8acbfe79ba707779b8c557 to your computer and use it in GitHub Desktop.
Simple PHP fetch command
This file contains 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
/** | |
* 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