phasync
HttpClient / post

Method

HttpClient::post

Send a POST request with a body.

Description#

public HttpClient::post(
    UriInterface|string $url,
    mixed $requestData,
    HttpClientOptions|array|null $options = null
): ResponseInterface

An array or object is sent form-encoded; pass ['headers' => ['Content-Type: application/json']] to send it as JSON. A MultipartStream is sent as multipart/form-data.

Parameters#

$url UriInterface|string
The URL to post to
$requestData mixed
The body: a string, a stream, an array or an object
$options HttpClientOptions|array|null = null
Options for this request only

Return values#

ResponseInterface

Errors / Exceptions#

ExceptionWhen
InvalidArgumentExceptionFor an option name that does not exist
RuntimeExceptionFor a headers entry without a colon, and for array or object data with a Content-Type other than application/x-www-form-urlencoded or application/json

Examples#

Example 1Post a form
use phasync\HttpClient\HttpClient;

$base   = require __DIR__ . '/../server.php';
$client = new HttpClient();

// An array is sent form-encoded unless a Content-Type header says otherwise
$response = $client->post("$base/echo", ['name' => 'Ada', 'tags' => ['math', 'engines']]);
$echo     = json_decode((string) $response->getBody(), true);

echo $echo['headers']['content-type'], "\n";
echo json_encode($echo['form']), "\n";
Output
application/x-www-form-urlencoded
{"name":"Ada","tags":["math","engines"]}
Example 2
$response = $client->post('https://example.com/login', ['user' => 'frode', 'password' => $secret]);

$response = $client->post('https://example.com/api', ['name' => 'x'], [
    'headers' => ['Content-Type: application/json'],
]);

See also#