Tag Archives: CURL

POST with Zend_Http_Client

CURL and Zend_Http

It’s a well know fact that you can preform HTTP requests with CURL. Zend Framework does the same job with Zend_Http. Especially Zend_Http_Client can be used to “replace” the usual client – the browser, and to perform some basic requests.

HTTP requests can be performed with Zend_Http_Client
Zend_Http_Client is mostly used to perform GET requests, but it can be also very helpful for POST HTTP requests.

I’ve seen mostly GET requests, although Zend_Http_Client can perform various requests such as POST as well.

// new HTTP request to some HTTP address
$httpClient = new Zend_Http_Client('http://www.example.com/');
// GET the response
$response = $httpClient->request(Zend_Http_Client::GET);

Here’s a little snippet showing how to POST some data to a server.

// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://www.example.com/');
// set some parameters
$client->setParameterPost('name', 'value');
// POST request
$response = $client->request(Zend_Http_Client::POST);

Note that the request method returns a response. Thus if you are simulating a form submit action you can “redirect” to the desired page just like the form.

// new HTTP request to some HTTP address
$client = new Zend_Http_Client('http://www.example.com/');
// set some parameters
$client->setParameterPost('name', 'value');
// POST request
$response = $client->request(Zend_Http_Client::POST);
echo $response->location;

Download Images with PHP

As it seems one possible solution while trying to download images with PHP is to write a “client” to do so. Will it be with cURL, Zend Framework or some other tool – it doesn’t matter.

However one of the most used approaches is simply with file_get_contents and file_put_contents. I’m not sure whether I wrote already about this or not, but this solution simply looks something like this.

 
file_put_contents('/path/to/file', 
                  file_get_contents('http://www.example.com/source.image');

In fact a client will give you more control over the process, to handle errors, etc. So maybe this is a better solution.

HTTP POST with PHP without cURL

Awesome PHP

a great php idea!
It’s strange how powerful PHP can be. There’s a legend that cURL is the only way to perform a HTTP POST with PHP, but that isn’t the truth. An extremely useful script is by using stream_context_create:

$optional_headers = null;
$params = array('http' => array(
                'method' => 'POST',
                'content' => http_build_query(array('name' => 'my-name'))));
 
if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
}
 
$ctx = stream_context_create($params);
$fp = @fopen('http://example.com/post.php', 'rb', false, $ctx);

Well this is only a snippet. You can change a lot this code and perform any request, but here’s a small start up. However note that this will do the same as while posting to example.com/post.php via web form!