cURL Sending File as Post

Posted on 16th Feb 2014 by admin

This is a bit complicated, I'm just hoping someone else has run into this and knows how to do it a different way or make it work.

When sending a file as part of form information included in a cURL request, it appears you can not include a query string in the file name. Take a look at my example to see what I'm talking about.

Code: //This creates an example image with some text from $_GET['img'] you can try calling this directly to see what the output looks like
if(isset($_GET['img'])){
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 255, 255, 255);
imagestring($im, 3, 3, 3, $_GET['img'], $text_color);
header('Content-type: image/jpeg');
imagejpeg($im);
imagedestroy($im);
exit;
}

//Show what was sent to the $_POST and $_FILES variables
if(isset($_POST['showpost'])){
echo '<pre>';
print_r($_POST);
print_r($_FILES);
exit;
}

//Here's the part where we get in trouble...
//This works
//$imgURL = '@'.$_SERVER['SCRIPT_FILENAME'];

//This doesn't work
$imgURL = '@'.$_SERVER['SCRIPT_FILENAME'].'?img=true';

$data = array('showpost' => 'true', 'file' => $imgURL);

//Now do the cURL request to show information about the file that was sent
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
if(curl_errno($ch))
echo curl_error($ch);
curl_close($ch);
When using the section that says "This doesn't work" you'll get the cURL error "failed creating formpost data".

Any suggestions?

Other forums