2015-06-03

How to POST data (file included) using Zend Framework 2

Using "normal" PHP, this could be achieved using curl, like this:

$filepath = '/var/www/vhosts/domain.com/http/filename.pdf';
$data = array(
 'field1'=>'value1',  
 'field2'=>'value2',         
 'field3'=>"@$filepath"
);

/*
or, instead of using the @, that is deprecated in more recent PHP versions, replace with:
'file' =>  new CURLFile($filepath,'application/pdf', basename($filepath))
*/

$url = 'www.domain.org/post/address';
try{ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $response = curl_exec($ch); curl_close($ch); } catch (Exception $e) { $error = $e->getMessage(); return false; } ?>



Using Zend Framework 2:

use Zend\Http\Client;


$data = array(
 'field1'=>'value1',  
 'field2'=>'value2'
);

$filepath = '/var/www/vhosts/domain.com/http/filename.pdf';
$url = 'www.domain.com/post/address';


$client = new Client();
$client->setUri($url);
$client->setParameterPost($data);
$client->setMethod('POST');
$client->setFileUpload($filepath,'field3');
$response = $client->send();

if ($response->isSuccess() === true) {
    $content = $response->getBody();
}
?>