【问题标题】:PHP cURL set file as POST form input type filePHP cURL 将文件设置为 POST 表单输入类型文件
【发布时间】:2014-06-23 12:12:13
【问题描述】:

我在另一台服务器上有一个带有<form> 的页面,我使用 cURL 自动设置数据。但是在这种形式中有一个文件输入<input name='file' type='file'>,现在我知道文件输入的行为与其他文件不同。

//This is my code till now.
$ch = curl_init();
//page is password protected I am not sure if this works but I hope it does.
curl_setopt($ch, CURLOPT_URL, "http://user:pass@mydomain.com/system_backup.php");
curl_setopt($ch, CURLOPT_POST, 1);
//set a file as post variable this doesn't work
curl_setopt($ch, CURLOPT_POSTFIELDS, "file=".$file."&var1=".$var1."&var2=".$var2);
$result = curl_exec($ch);
curl_close($ch);

所以我的问题是如何使用 cURL 将文件设置为 postfield。

【问题讨论】:

标签: php file curl


【解决方案1】:

Look at this guide,你需要在文件完整路径前加上'@'

【讨论】:

  • 现在在 PHP 5.5 或更高版本上已弃用。见here
【解决方案2】:

您可以将参数放入数组中,如$postFields = array('file'=>$file,'var1'=>$var1,'var2'=>$var2);

然后使用curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));

希望应该可以工作。

【讨论】:

  • 问题是文件需要是input type='file'的语法
【解决方案3】:

自己找到了解决办法

$postParams['file'] = '@'.realpath("URLTOFILE.txt"); //for type = file
$postParams['var1'] = urlencode("var1"); //type = text, submit pretty much everything.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://user:pass@mydomain.com/system_backup.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 2016-04-08
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多