我正在尝试将代码分解为功能。但是,当我分解代码以使get_login_cookie()
起作用时,该程序停止了按预期的功能。我怀疑是因为curlResponseHeaderCallback
函数未正确调用。有人可以帮我修复它,以便将我分解为2个功能。
原始代码(可以正常工作,并且print_r的cookie也可以)
<?php
function curlResponseHeaderCallback($ch, $headerLine) {
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
$cookies[] = $cookie;
return strlen($headerLine);
}
$url = "https://example.com/login";
$cookies = "";
$fields = [
'username' => "myuser",
'password' => "mypass",
];
$fields_string = http_build_query($fields);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback"); // This is where the error is!
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($ch);
echo "<pre>";
print_r($cookies)
?>
将代码分解为2个函数(代码无法正常工作),我得到的是一个空数组,而不是cookie数组。它很可能无法正常运行,因为我没有正确调用curlResponseHeaderCallback
函数
<?php
function curlResponseHeaderCallback($ch, $headerLine) {
global $cookies;
if (preg_match('/^Set-Cookie:\s*([^;]*)/mi', $headerLine, $cookie) == 1)
$cookies[] = $cookie;
return strlen($headerLine);
}
function get_login_cookie() {
$url = "https://example.com/login";
$cookies = [];
$fields = [
'username' => "myuser",
'password' => "mypass",
];
$fields_string = http_build_query($fields);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, "curlResponseHeaderCallback"); // This is where the error is!
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($ch);
echo "<pre>";
print_r($cookies);
}
get_login_cookie();
?>
答案 0 :(得分:0)
您在第二个功能中错过了global $cookies;
。
回调将数据设置为全局$ cookies,但是您将打印本地$ cookies。