Using PHP & curl to publish html form containing 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);

This works to publish fields1 and 2 fields. Is there any way to include a file in this curl process? How should I do it? I guess I need to do more than just encode the value of the file.

So based on SimpleCoders answer I updated 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 sends OK, but then my resulting $ _FILES array on catch.php is empty. Alignment with Example No. 2 at http://www.php.net/manual/en/function.curl-setopt.php This should work.

I am doing this on two different domains ... maybe a problem?

+1
source share
2

- : :

$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;

https://secure.php.net/manual/en/class.curlfile.php, .

+3

SimpleCoders,

$fields_string

$fields.  

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

. CURLOPT_POSTFIELDS multipart/form-data, URL application/x-www-form-urlencoded.

+1

Source: https://habr.com/ru/post/1778289/


All Articles