PHP cURL内容长度和内容类型错误

Sim*_*mon 11 php curl header request

我正在尝试通过PHP cURL登录网站,我只收到"错误请求"响应.

我玩了hosts文件并将其设置到我的服务器,以检查我的浏览器发送的请求标头,并将其与cURL发送的请求标头进行比较.

一切都是平等的,除了:

浏览器:

Content-Type: application/x-www-form-urlencoded
Content-Length: 51
Run Code Online (Sandbox Code Playgroud)

PHP cURL:

Content-Length: 51, 359
Content-Type: application/x-www-form-urlencoded; boundary=----------------------------5a377b7e6ba7
Run Code Online (Sandbox Code Playgroud)

我已经使用此命令设置了这些值,但它仍然发送错误的标头:

curl_setopt($this->hCurl, CURLOPT_HTTPHEADER, array(
    'Expect:',
    'Content-Type: application/x-www-form-urlencoded',
    'Content-Length: 51' 
));
Run Code Online (Sandbox Code Playgroud)

dre*_*010 31

您不必自己设置内容长度.如果您使用cURL发送HTTP POST,它将为您计算内容长度.

如果将CURLOPT_POSTFIELDS值设置为数组,它将自动提交请求multipart/form-data并使用边界.如果你传递一个字符串,它将使用,application/x-www-form-urlencoded所以请确保你传递一个urlencoded字符串,CURLOPT_POSTFIELDS而不是一个数组,因为你想要form-urlencoded.

你需要这样做:

$data = 'name=' . urlencode($value) . '&name2=' . urlencode($value2);
curl_setopt($this->hCurl, CURLOPT_POSTFIELDS, $data);

// NOT

$dataArray = array('name' => 'value', 'name2' => 'value2');
curl_setopt($this->hCurl, CURLOPT_POSTFIELDS, $dataArray);
Run Code Online (Sandbox Code Playgroud)

在任何一种情况下,您都不需要设置内容长度,但必须使用第一种方法application/x-www-form-urlencoded在表单上获取编码.

如果这没有用,请发布与设置curl请求相关的所有代码(所有选项和传递给它的数据),这应该有助于解决问题.

编辑:

添加了一个我想出的例子(我登录失败).

<?php

$URL_HOME  = 'http://ilocalis.com/';
$LOGIN_URL = 'https://ilocalis.com/login.php';

$ch = curl_init($URL_HOME);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

$home = curl_exec($ch);

//echo $home;

$post = array('username' => 'drew', 'password' => 'testing 123');
$query = http_build_query($post);

curl_setopt($ch, CURLOPT_URL, $LOGIN_URL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);

$login = curl_exec($ch);

echo $login;
Run Code Online (Sandbox Code Playgroud)