I'm trying to write some PHPUnit tests for ajax endpoints. I can do this no sweat when the user doesn't have to be logged in. But to test the endpoint in question, the user does have to be logged in and I want to get the cookie programmatically as part of the test. Basically the test I want to run looks like:
$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();
But I don't know a good way to get $userCookie
other than opening a browser, logging in, and then reading PHPSESSID
from the cookies in the browser. How can I get the cookie for this without grabbing it manually? I'd like to be able to get it from a curl request to the login endpoint:
$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);