I found that I could use PHPUnit to test the behavior of the part of my website that relies heavily on sessions, through a combination of Curl and a cookie that passes the session id.
The following Curl class uses the CURLOPT_COOKIE option to pass a session parameter. The static variable $sessionid saves the session between different Curl calls. Further, sessions can be changed using the static function changeSession.
class Curl {
private $ch;
private static $sessionid;
public function __construct($url, $options) {
$this->ch = curl_init($url);
if (!self::$sessionid)
self::$sessionid = .. generateRandomString() ..;
$options = $options + array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIE => 'PHPSESSID=' . self::$sessionid);
foreach ($options as $key => $val) {
curl_setopt($this->ch, $key, $val);
}
}
public function getResponse() {
if ($this->response) {
return $this->response;
}
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$errno = curl_errno($this->ch);
$header_size = curl_getinfo($this->ch, CURLINFO_HEADER_SIZE);
$this->header = substr($response, 0, $header_size);
$response = substr($response, $header_size);
if (is_resource($this->ch)) {
curl_close($this->ch);
}
if (0 !== $errno) {
throw new \RuntimeException($error, $errno);
}
return $this->response = $response;
}
public function __toString() {
return $this->getResponse();
}
public static function changeSession() {
self::$SESSIONID = Practicalia::generateRandomString();
}
}
An example call
$data = array(
'action' => 'someaction',
'info' => 'someinfo'
);
$curl = new Curl(
'http://localhost/somephp.php',
array(
CURLOPT_POSTFIELDS => http_build_query($data)));
$response = $curl->getResponse();
And any subsequent Curl calls will automatically use the same session as the previous one, unless specifically Curl::changeSession() is called.
unset($_COOKIE)in thesetUpof the test? - Mike B