11.3 Performing an HTTP POST Request


You want to use PHP to perform an HTTP POST operation on a remote Web site.

Technique

Use the Net_Curl class from PEAR and set the type property to "post" . Then just fill in the fields property with the array of post fields you want to send:

 <?php // Initialize $conn = new Net_Curl('http://www.designmultimedia.com/php/form.php'); if (Net_Curl::isError($conn)) {     die(sprintf('Error [%d]: %s',                 $conn->getCode(), $conn->getMessage())); } // Set the transfer options $conn->type = 'POST'; $conn->fields = array("name"     => "Sterling Hughes",                       "email"    => "sterling@php.net",                       "comments" => "Nice site."); // Execute the transfer $data = $conn->execute(); if (Net_Curl::isError($data)) {     die(sprintf('Error [%d]: %s',                 $data->getCode(), $data->getMessage())); } print "The results of your transfer were: \n<br>\n"; print $data; ?> 

Comments

Using the curl extension in conjunction with the Net_Curl package makes HTTP POST operations easy. The basic flow is you initialize the transfer, and then you tell PHP that the method of transfer will be HTTP POST by setting the type property to "POST" . After you've told PHP that this will be a POST transfer, you give it an associative array of the information you want to POST to the remote script. Finally, you execute the transfer and receive the results in an array.

Using the Net_Curl package is the best way to perform cURL transfers, but if you want to use the curl extension itself for this, do the following:

 <?php $ch = curl_init('http://www.designmultimedia.com/php/form.php'); if (!$ch) {     die(sprintf('Error [%d]: %s',                 curl_errno($ch), curl_error($ch))); } $submit = array("name"     => "Sterling Hughes",                 "email"    => "sterling@php.net",                 "comments" => "Love the site."); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $submit); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($ch); if (!$data) {     die(sprintf('Error [%d]: %s',                 curl_errno($ch), curl_error($ch))); } print "The results of your transfer were: \n<br>\n"; print $data; ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net