获取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();

但我不知道有什么好方法可以获得$userCookie,除了打开浏览器,登录,然后从浏览器中的cookie中读取PHPSESSID。我如何在不手动抓取的情况下获取饼干?我希望能够从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请求已经完成了一半。您需要做的是从响应标头中检索cookie以获得PHPSESSID

您可以在这里找到另一个问题,询问了如何使用cURL获取响应标头。

一旦获得了响应标头,就必须对其进行解析以获得Set-Cookie标头。将该标头的内容用于后续测试应该可以从那里开始工作。