Hi,
I've been reading into testing my PHP code particularly unit testing using PHPUnit. The problem I have is that most of my code is procedural with not even many functions. I have read that unit testing is more suitable for OO PHP however i have seen that many people say it can be used to test procedural. However, the examples i have seen of this have not been with code similar to mine.
I was wondering if anyone could demonstrate with some of my code how i would unit test parts of it. I have included my file that validates login details below if someone could help?
`<?php
session_start();
include'db_config.inc';
$error_flag = false;
$_SESSION['L_ERR_MSG'] = '';
try {
$dbh = new PDO("mysql:host=127.0.0.1;dbname=$db", $user, $password);
}
catch (PDOException $e) {
die($e->getMessage());
}
try {
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);
}
catch(Exception $e) {
$_SESSION['L_ERR_MSG'] = $e;
session_write_close();
header("location: login_failed.php");
}
$_SESSION['username'] = $username;
if(!isset($username) or empty($username)){
if(!isset($password) or empty($password)){
$_SESSION['L_ERR_MSG'] = 'Username and Password fields are empty. Please enter your details in them!';
$error_flag = true;
}
else {
$_SESSION['L_ERR_MSG'] = 'Username field is empty. Please enter your Username!';
$error_flag = true;
}
}
else if(!isset($password) or empty($password)){
$_SESSION['L_ERR_MSG'] = 'Password field is empty. Please enter your Password!';
$error_flag = true;
}
$password = encrypt_password($password);
$loginmatches = $dbh->query ("SELECT * FROM Member WHERE username = '$username'
AND password = '$password'");
if($error_flag){
session_write_close();
header("location: login_failed.php");
exit();
}
else {
if($loginmatches){
if($loginmatches->rowCount() == 1){
$member = $loginmatches->fetch(PDO::FETCH_ASSOC);
$dbh->exec ("INSERT INTO `Login`
(`username`,`loginTime`)
VALUES ('$username',NOW())");
$_SESSION['SESS_USER'] = $member['username'];
$_SESSION['SESS_USER_SITEROLE'] = $member['siteRole'];
if($_SESSION['REDIR_BOOKING'] == 1){
header("location: book_taxi.php");
}
else {
switch($member['siteRole']){
case "MEMBER":
header("location: member_profile.php");
break;
case "DRIVER":
header("location: driver_profile.php");
break;
case "ADMIN":
header("location: admin_profile.php");
break;
case "SUPERADMIN":
header("location: superadmin_profile.php");
break;
}
}
}
else {
$_SESSION['L_ERR_MSG'] = 'Incorrect Username and/or Password entered. Please try again!';
session_write_close();
header("location: login_failed.php");
}
}
}
?>`
It would be good if i could test the different session messages etc.
Any help would be much appreciated.