我在使用 PHP 中的 cURL 脚本发送 POST 请求时遇到问题。
我正在尝试制作一个代理,主要是供我个人使用,它将通过服务器获取网页并在本地显示给我。
找到的 URL 是这样的:http://fetch.example.com/http://theurl.com/
当我在该页面上的表单中发帖时,它将转到表单的 ACTION(获取 URL 在前面)。我正在尝试使用下面的代码让它处理这个 POST 请求,但我 POST 的任何内容总是会带来 400 Bad Request 错误。
$chpg = curl_init();
curl_setopt($chpg, CURLOPT_URL, $_URL);
curl_setopt($chpg, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($chpg, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($chpg, CURLOPT_COOKIESESSION, true);
curl_setopt($chpg, CURLOPT_COOKIEJAR, "cookies/$_COOKIE_FILE.$_DOMAIN.txt");
curl_setopt($chpg, CURLOPT_COOKIEFILE, "cookies/$_COOKIE_FILE.$_DOMAIN.txt");
if($_POST) {
$fields = array();
foreach($_POST as $col => $val) {
$fields[$col] = urlencode($val);
}
print_r($fields);
curl_setopt($chpg, CURLOPT_POST, count($fields));
curl_setopt($chpg, CURLOPT_POSTDATA, $fields);
}
最佳答案
你有几个问题:
CURLOPT_POSTDATA
应该是CURLOPT_POSTFIELDS
。您正在发送
$fields
PHP 数组 作为CURLOPT_POSTFIELDS
。这实际上需要是 格式name1=value1&name2=value2&...
。要解决这些问题,请按如下方式修改您的 PHP 代码:
if($_POST) { $fields_str = http_build_query($_POST); curl_setopt($chpg, CURLOPT_POST, count($_POST)); curl_setopt($chpg, CURLOPT_POSTFIELDS, $fields_str); }
作为Lawrence Cherone指出,您可以放弃
foreach
循环并使用http_build_query
相反。
关于php - curl 发布 : 400 Invalid content length,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369129/