Uploading a image in php with curl
In the latest years we (php programmers) have spent a lot of time behind classes and frameworks , making all our repetitive tasks available in simple and understandable forms like :
$image = new Image('/var/www/image.jpg');
$image->upload('http://www.somesite.com/upload.php');
However , when the Image class can not be used , most of use will google for “how to upload an image with php curl”.
The following snippet of code can be used to upload a image:
$url = 'http://somesite.com/upload.php; $file = 'image.jpg';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,
array('image' => "@$file;type=image;type=image/jpeg"));
$resp = curl_exec($curl);
Note the @ before the file. It will extract the binary contents of file , so be wary of your php memory limit.
Rss
November 19th, 2009 at 1:50 am
Hey,
I’m using the exact same code, but I keep on getting “failed to create formpost data”. I’ve checked the photo path and i’m pretty sure it perfectly right…
$fileToCopy = $_FILES["btnBrowse"]["tmp_name"];
$fileName = $_FILES["btnBrowse"]["name"];
$copyTemp = “temppool/testimage.jpg”;
@copy($fileToCopy, $copyTemp) or die(”can’t copy “.$fileName.” to “.$copyTemp);
//print $_FILES["btnBrowse"]["type"];
$api_sig = md5(”5ed58b4c4fa78297″.”api_key”.”fffaf8c8e4c4b7f016c67b8e03061305″.”auth_token”.$_SESSION["flickrAuthToken"]);
$params = array(
“api_key” => “fffaf8c8e4c4b7f016c67b8e03061305″,
“auth_token” => $_SESSION["flickrAuthToken"],
“api_sig” => $api_sig,
“photo” => “@$copyTemp;type=”.$_FILES["btnBrowse"]["type"]
);
ksort($params);
$curlrequest = curl_init();
curl_setopt($curlrequest, CURLOPT_URL, “http://api.flickr.com/services/upload/”);
curl_setopt($curlrequest, CURLOPT_POST, true);
curl_setopt($curlrequest, CURLOPT_HEADER, false);
curl_setopt($curlrequest, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlrequest, CURLOPT_POSTFIELDS, $params);
November 19th, 2009 at 2:31 am
Hey ,
are you sure?
what does var_export(is_file($copyTemp)) shows, just before $params declaration?