【问题标题】:Using PHP & curl to post an html form that includes a file使用 PHP & curl 发布包含文件的 html 表单
【发布时间】:2010-07-15 15:57:53
【问题描述】:

我有这样的表格:

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

在我已有的页面上:

$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 过程中?我该怎么做?我假设我必须做的不仅仅是对文件值进行编码。

所以根据 SimpleCoders 的回答,我更新了以下内容:

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

它发布了 OK,但是我在 catch.php 上生成的 $_FILES 数组是空的。根据http://www.php.net/manual/en/function.curl-setopt.php 上的示例 #2,这应该可以工作。

我在两个不同的域上执行此操作...这可能是个问题吗?

【问题讨论】:

    标签: php post curl


    【解决方案1】:

    尝试这样的事情,采取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;
    

    还可以考虑https://secure.php.net/manual/en/class.curlfile.php,这似乎是一种更简单、更现代的方式。

    【讨论】:

    • 由于无法保证外部链接的寿命,您可以在此处发布信息并留下参考吗?
    【解决方案2】:

    您需要遵循 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-17
      • 2011-04-16
      • 2013-06-13
      相关资源
      最近更新 更多