Created
November 3, 2021 09:50
-
-
Save teocci/1b45aba491271f4edbabd23bef68b047 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
const FORMAT_CONTENT_LENGTH = 'Content-Length: %d'; | |
const FORMAT_CONTENT_TYPE = 'Content-Type: %s'; | |
const CONTENT_TYPE_JSON = 'application/json'; | |
function HTTPJSONPost(string $url, array $params) | |
{ | |
$content = json_encode($params); | |
$response = file_get_contents($url, false, // do not use_include_path | |
stream_context_create([ | |
'http' => [ | |
'method' => 'POST', | |
'header' => [ // header array does not need '\r\n' | |
sprintf(FORMAT_CONTENT_TYPE, CONTENT_TYPE_JSON), | |
sprintf(FORMAT_CONTENT_LENGTH, strlen($content)), | |
], | |
'content' => $content | |
] | |
])); // no maxlength/offset | |
if ($response === false) { | |
return json_encode(['error' => 'Failed to get contents...']); | |
} | |
return $response; | |
} | |
$url = "https://reqbin.com/echo/post/json"; | |
$data = [ | |
"Id" => 78912, | |
"Customer" => "Jason Sweet", | |
"Quantity" => 1, | |
"Price" => 18.00, | |
]; | |
HTTPJSONPost($url, $data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment