Skip to content

Commit 0f5166a

Browse files
committed
Add post request example
1 parent c0f9661 commit 0f5166a

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,8 @@ $response = $http->sendRequest($fastRequest);
9696
$http->wait();
9797
```
9898

99+
For more extensive examples, check out the code in the [example directory](/example).
100+
99101
[psr-7]: http://www.php-fig.org/psr/psr-7/
100102
[fetch-standard]: https://fetch.spec.whatwg.org/
101103
[fetch-js]: https://developer.mozilla.org/en/docs/Web/API/Fetch_API

example/02-post-request.php

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<?php
2+
require(implode(DIRECTORY_SEPARATOR, ["..", "vendor", "autoload.php"]));
3+
4+
use Gt\Fetch\Http;
5+
use Gt\Fetch\BodyResponse;
6+
7+
/*
8+
* This example uses postman-echo.com do test the request/response.
9+
* See https://docs.postman-echo.com/ for more information.
10+
*/
11+
12+
// Example: Post form data to the echo server.
13+
14+
$http = new Http();
15+
$http->fetch("https://postman-echo.com/post", [
16+
// All of the request parameters can be passed directly here, or alternatively
17+
// the fetch() function can take a PSR-7 RequestInterface object.
18+
"method" => "POST",
19+
"headers" => [
20+
"Content-Type" => "application/x-www-form-urlencoded",
21+
],
22+
"body" => http_build_query([
23+
"name" => "Mark Zuckerberg",
24+
"dob" => "1984-05-14",
25+
"email" => "[email protected]",
26+
]),
27+
])
28+
->then(function(BodyResponse $response) {
29+
if(!$response->ok) {
30+
echo "Error posting to Postman Echo." . PHP_EOL;
31+
exit;
32+
}
33+
// Postman Echo servers respond with a JSON representation of the request
34+
// that was received.
35+
return $response->json();
36+
})
37+
->then(function($json) {
38+
echo "The Postman Echo server received the following form fields:";
39+
echo PHP_EOL;
40+
41+
foreach($json->form as $key => $value) {
42+
echo "$key = $value" . PHP_EOL;
43+
}
44+
});
45+
46+
// To execute the above Promise(s), call wait() or all().
47+
$http->wait();

0 commit comments

Comments
 (0)