Amp\Artax\FormBody::addField PHP Method

addField() public method

Add a data field to the form entity body
public addField ( string $name, string $value, string $contentType = 'text/plain' ) : self
$name string
$value string
$contentType string
return self
    public function addField($name, $value, $contentType = 'text/plain')
    {
        $this->fields[] = [(string) $name, (string) $value, (string) $contentType, $fileName = null];
        $this->cachedBody = $this->cachedLength = $this->cachedFields = null;
        return $this;
    }

Usage Example

 public function testMultipartBodyRequest()
 {
     $uri = 'http://httpbin.org/post';
     $client = new Client();
     $field1 = 'test val';
     $file1 = __DIR__ . '/fixture/lorem.txt';
     $file2 = __DIR__ . '/fixture/answer.txt';
     $boundary = 'AaB03x';
     $body = new FormBody($boundary);
     $body->addField('field1', $field1);
     $body->addFile('file1', $file1);
     $body->addFile('file2', $file2);
     $request = (new Request())->setBody($body)->setUri('http://httpbin.org/post')->setMethod('POST');
     $promise = $client->request($request);
     $response = \Amp\wait($promise);
     $this->assertEquals(200, $response->getStatus());
     $result = json_decode($response->getBody(), true);
     $this->assertEquals($field1, $result['form']['field1']);
     $this->assertEquals(file_get_contents($file1), $result['files']['file1']);
     $this->assertEquals(file_get_contents($file2), $result['files']['file2']);
     $this->assertEquals('multipart/form-data; boundary=' . $boundary, $result['headers']['Content-Type']);
 }