Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Coroutine\Http\Client->addData(string $data, string $name, string $mimeType = null, string $filename = null): void
The data to be used to generate a file for the HTTP request. The maximum length shall not be exceed buffer_output_size
.
The name of the HTML or input form where the file is being uploaded to.
Set the optional MIME format of the file, for example application/json
. The default if not set is application/octet-stream
.
Set the optional filename, this defaults to the $name
parameter.
None
Generate a file from a string and attach it to a POST request. This essentially allows you to just generate the contents of a uploaded file through strings.
Requires v4.1.0+
<?php
use OpenSwoole\Coroutine\HTTP\Client;
co::run(function()
{
$client = new Client('127.0.0.1', 80);
$client->setHeaders([
'Host' => "localhost",
"User-Agent" => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
'Content-Type' => 'application/json',
]);
$client->set(['timeout' => 1]);
// Creates a file based on the string, this is uploaded to the remote host
$client->addData('{"name": "OpenSwoole", "age": "12"}', 'formName');
// The post function requires a path and data
$client->post('/upload/file', ['foo' => 'bar']);
echo "Request Status: " . $client->status . "\n";
var_dump($client->body);
$client->close();
});
To send the same request but without additional POST data when you use post()
, you can use the setMethod()
and execute()
functions:
<?php
...
// Creates a file based on the string, this is uploaded to the remote host
$client->addData('{"name": "OpenSwoole", "age": "12"}', 'formName');
$client->setMethod('POST');
// Send POST request without additional data, use a path only
$status = $client->execute('/upload/file');
echo "Request Status: " . $status . "\n";
var_dump($client->body);
echo $client->body;
...