title: Using PHP & curl to post an html form that includes a file
body: <p>I have a form like this:</p>
  
  <pre><code>&lt;form method="POST" action="i.php" enctype="multipart/form-data"&gt;
   &lt;input type="text" name="field1"&gt;
   &lt;input type="text" name="field2"&gt;
   &lt;input type="file" name="file"&gt;
   &lt;input type="hidden" name="MAX_FILE_SIZE" value="100000"&gt;
   &lt;input type="submit"&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>On the page I already have:</p>
  
  <pre><code>$URL = 'http://somewhere.com/catch.php';
  $fields = array('field1'=&gt;urlencode($_POST['field1'), 'field2'=&gt;urlencode($_POST['field2'));
  
      foreach($fields as $key=&gt;$value) { $fields_string  .= $key.'='.$value.'&amp;'; };
  
      rtrim($fields_string,'&amp;');
      $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);
  </code></pre>
  
  <p>That works to post the field1 &amp; 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.</p>
  
  <p>So based on SimpleCoders' answer I updated to the following:</p>
  
  <pre><code>$URL = 'http://somewhere.com/catch.php';
  $fields = array('field1'=&gt;urlencode($_POST['field1'), 'field2'=&gt;urlencode($_POST['field2'), 'files'=&gt;'@'. $_FILES['file']['tmp_name']);
  
      foreach($fields as $key=&gt;$value) { $fields_string  .= $key.'='.$value.'&amp;'; };
  
      rtrim($fields_string,'&amp;');
      $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);
  </code></pre>
  
  <p>which posts OK but then my resulting $_FILES array on catch.php is empty.  Accoring to Example #2 on <a href="http://www.php.net/manual/en/function.curl-setopt.php" rel="nofollow noreferrer">http://www.php.net/manual/en/function.curl-setopt.php</a> This should work.</p>
  
  <p>I am doing this on two different domains...might that be a problem?</p>