0

Greetings,

I'm looking for a way to send a curl request given a full url. All of the examples and documentation I can find look something like this:

$fullFilePath = 'C:\temp\test.jpg';
$upload_url = 'http://www.example.com/uploadtarget.php';
$params = array(
    'photo'=>"@$fullFilePath",
    'title'=>$title
);      

$ch = curl_init();
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_URL, $upload_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($ch);
curl_close($ch);

The problem is that the file, "test.jpg" is actually generated dynamically by a script on the server (so it doesn't exist on the file system).

How can I send the request, instead using $file = "http://www.mysite.com/generate/new_image.jpg"

One solution that came to mind was loading "new_image.jpg" into memory with fopen or file_get_contents() but once I get to that point I'm not sure how to send it as POST to another site

pws5068
  • 2,224
  • 4
  • 35
  • 49

1 Answers1

1

By far the easiest solution is going to be to write the file to a temporary location, then delete it once the cURL request is complete:

// assume $img contains the image file
$filepath = 'C:\temp\tmp_image_' . rand() . '.jpg'
file_put_contents($filepath, $img);
$params = array(
    'photo'=>"@$filepath",
    'title'=>$title
);    
// do cURL request using $params...

unlink($filepath);

Note that I am inserting a random number to avoid race conditions. If your image is not particularly big, it would be better to use md5($img) in your filename instead of rand(), which could still result in collisions.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • This method works, I was hoping to avoid saving a copy but it seems like my only option. Thanks for your help- – pws5068 May 25 '11 at 20:16
  • @pws5068 It's possible, but it basically requires building the post manually. You probably don't want to do that. – lonesomeday May 25 '11 at 20:17