Jason Jason - 7 months ago 31
PHP Question

Using PHP & curl to post an html form that includes a file

I have a form like this:

<form method="POST" action="i.php" enctype="multipart/form-data">
<input type="text" name="field1">
<input type="text" name="field2">
<input type="file" name="file">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<input type="submit">
</form>


On the page I already have:

$URL = 'http://somewhere.com/catch.php';
$fields = array('field1'=>urlencode($_POST['field1'), 'field2'=>urlencode($_POST['field2'));

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; };

rtrim($fields_string,'&');
$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$URL);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

$result = curl_exec($ch);

curl_close($ch);


That works to post the field1 & 2 fields.
Is it possible to include the file in that curl process somehow? How would I do that? I'm assuming I have to do more than just encode the file value.

So based on SimpleCoders' answer I updated to the following:

$URL = 'http://somewhere.com/catch.php';
$fields = array('field1'=>urlencode($_POST['field1'), 'field2'=>urlencode($_POST['field2'), 'files'=>'@'. $_FILES['file']['tmp_name']);

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; };

rtrim($fields_string,'&');
$ch = curl_init();

curl_setopt($ch,CURLOPT_URL,$URL);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

$result = curl_exec($ch);

curl_close($ch);


which posts OK but then my resulting $_FILES array on catch.php is empty. Accoring to Example #2 on http://www.php.net/manual/en/function.curl-setopt.php This should work.

I am doing this on two different domains...might that be a problem?

Answer

Try something like this, taken from here:

$file_to_upload = array('file_contents'=>'@'.$file_name_with_full_path); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$target_url); 
curl_setopt($ch, CURLOPT_POST,1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $file_to_upload); 
$result=curl_exec ($ch); 
curl_close ($ch); 
echo $result;

Also consider https://secure.php.net/manual/en/class.curlfile.php, which appears to be an easier, more modern way of doing it.