Jason
Jason

Reputation: 15355

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?

Upvotes: 1

Views: 2951

Answers (2)

Chris Laplante
Chris Laplante

Reputation: 29668

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.

Upvotes: 3

A Dent
A Dent

Reputation: 96

You need to follow SimpleCoders answer but then change your

$fields_string

to just

$fields.  

From http://www.php.net/manual/en/function.curl-setopt.php

Note: Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

Upvotes: 1

Related Questions