为 PHPUnit ajax 测试获取 cookie

Getting cookie for PHPUnit ajax test

我正在尝试为 ajax 端点编写一些 PHPUnit 测试。当用户不必登录时,我可以毫不费力地做到这一点。但是要测试有问题的端点,用户必须登录并且我想以编程方式获取 cookie 作为测试的一部分。基本上我想要 运行 的测试看起来像:

    $url = "https://example.com/ajax/endpoint";
    $fields = array(
        'name'=>'test '.rand(),       
        'host'=>rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255),
        'port'=>rand(1,1000)
    );
    $fields_string = "";
    foreach ($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = rtrim($fields_string, '&');
    ob_start();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_COOKIE, $userCookie);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    $this->assertEquals(true, $response);
    $json = ob_get_contents();
    $return = json_decode($json);
    $this->assertEquals('false', $return->success);
    $this->assertEquals('', $return->data);
    ob_end_clean();

但是除了打开浏览器、登录然后从浏览器中的 cookie 中读取 PHPSESSID 之外,我不知道获取 $userCookie 的好方法。如何在不手动抓取的情况下获取 cookie?我希望能够从对登录端点的 curl 请求中获取它:

    $url = "https://example.com/ajax/login";
    $fields = array(
        'username'=>$username,
        'password'=>$password
    );
    $fields_string = "";
    foreach ($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);

有什么能阻止您以编程方式获取它吗?

$ch = curl_init('https://example.com/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "login=root&password=toor");
curl_setopt($ch, CURLOPT_HEADER, 1);

$result = curl_exec($ch);
preg_match_all('/^Set-Cookie: PHPSESSID=(.*?);/mi', $result, $matches);
$userCookie = $matches[1];

您的登录 cURL 请求已完成一半。您需要做的是从响应 header 中检索 cookie 以获取 PHPSESSID.

How to get response headers with cURL has been asked in another question you can find here.

获得响应 header 后,您必须对其进行解析以获取 Set-Cookie header。使用该 header 的内容进行后续测试应该从那里开始。