php - curl 发布 : 400 Invalid content length

标签 php post curl

我在使用 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);
}

最佳答案

你有几个问题:

  1. CURLOPT_POSTDATA 应该是 CURLOPT_POSTFIELDS

  2. 您正在发送 $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/

相关文章:

php - laravel 查询仅加入最新记录

javascript - 如何以及由谁对同一 PHP 文件中存在的客户端和服务器代码进行代码分解/拆分?

PHP如何防止邮件在header中泄露脚本和IP

asp.net-mvc - 将 Textarea 发布到 Controller (当前正在传递 null)-MVC

linux - 如何在服务器端读取客户端发送的 TLS 证书?

php - Laravel 5.4 SQLSTATE[23000] : Integrity constraint violation: 1062 Duplicate entry '0' Live website

python - Beautifulsoup - 提交表单数据

php - $_POST 和 $_GET 转换报价( ' ) to backslash + quote (\')

javascript - Apps 脚本将参数传递给 cUrl

php/curl - 使用 header 获取远程服务器上的图像扩展