11.4 Performing an HTTP File Upload


You want to upload a file to a remote site with PHP by using the PUT method.

Technique

Use the Net_Curl class from PEAR, which interfaces with PHP's curl extension:

 <?php // Initialize the transfer $conn = new Net_Curl('http://yoursite.com/'); if (Net_Curl::isError($conn)) {     die(sprintf('Error [%d]: %s',                 $conn->getCode(), $conn->getMessage())); } // Set transfer options $conn->type = "PUT"; $conn->file = "sterling.jpg"; // Execute the transfer $res = $conn->execute(); if (Net_Curl::isError($res)) {     die(sprintf('Error [%d]: %s',                 $res->getCode(), $res->getMessage())); } print "The results of the transfer were:\n<br>\n"; print $res; ?> 

Comments

Here we use the Net_Curl module, which is a simple wrapper around the curl extension. The crux of this recipe lies in setting the $conn->type variable to "PUT" , which tells PHP that we will be using the HTTP PUT method instead of the default HTTP GET method. We then set $conn->file to the name of the file that we want to upload when PHP performs the transfer.

If you want to use a purely PHP implementation (and not use the simpler Net_Curl package), you can do the following:

 <?php // Initialize the cURL transfer $ch = curl_init('http://yourserver.com'); if (!$ch) {     die(sprintf('Error [%d]: %s',                 curl_errno($ch), curl_error($ch))); } // Set transfer options curl_setopt($ch, CURLOPT_PUT, 1); curl_setopt($ch, CURLOPT_INFILE, 'filename'); curl_setopt($ch, CURLOPT_INFILESIZE, filesize('filename')); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Execute transfer $res = curl_exec($ch); if (!$res) {     die(sprintf('Error [%d]: %s',                 curl_errno($ch), curl_error($ch))); } // Free resources curl_close($ch); print "The results of your transfer were: \n<br>\n"; print $res; ?> 


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