问题描述
我有这样的形式:
<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);
这可以发布field1& 2个字段。
是否可能包含该curl过程中的文件?我该怎么做?我假设我不能只是编码的文件值。
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.
所以基于SimpleCoders的答案我更新到以下:
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);
它发布确定,但是我的结果$ _FILES数组catch.php是空的。参阅这应该可以工作。
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?
推荐答案
尝试这样的操作,:
$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.
这篇关于使用PHP& curl来发布包含文件的html表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!