Created
June 21, 2023 12:34
-
-
Save kuya-joe/2e63e69ba25822fd590b7058b0350dc6 to your computer and use it in GitHub Desktop.
example fetch function using php
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
<?php | |
/* from StackOverflow: https://stackoverflow.com/a/52662522/1345527 */ | |
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 !== "200") { | |
throw new RuntimeException("unexpected response status: {$status_line}\n" . $response); | |
} | |
return $response; | |
} | |
// usage | |
$response = fetch( | |
"POST", | |
"http://example.com/", | |
json_encode([ | |
"foo" => "bar", | |
]), | |
[ | |
"Content-Type: application/json", | |
"X-API-Key: 123456789", | |
] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment