The login form works.
The header location works as it shows the details of the previous page.
I don't know how to put it all together.
The login page just refreshes but if I manually go to another page I am logged in. If I go to the page that requires login (which is the page I'm working on) I am not logged in and I am redirected to the login page.
``
http://example.com/articles/login.php?location=%2Farticles%2Fcommentslisting.php
<?php
// login.php
echo '<input type="hidden" name="location" value="';
if(isset($_GET['location'])) {
echo htmlspecialchars($_GET['location']);
}
echo '" />';
?>
<h2>Login Form</h2>
<form role="form" method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="loginform">
<?php
session_start();
?>
<?php
$username = $password = "";
$usernameErr = $passwordErr = $mainErr = "";
$redirect = NULL;
if($_POST['location'] != '') {
$redirect = $_POST['location'];
}
if(isset($_POST["Login"])) {
if (empty($_POST["txtuser"])) {
$usernameErr = "Name is required";
}
else {
$username = test_input($_POST["txtuser"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
$usernameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["txtpass"])) {
$passwordErr = "password is required";
} else {
$password = test_input($_POST["txtpass"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$password)) {
$passwordErr = "Only letters and white space allowed";
}
}
$username = $_POST['txtuser']; //txtuser is the name in the form field
$password = $_POST['txtpass']; //txtpass is the name in the form field
// TO DO: using stmt bind parameter here instead would be more secure
$checkuser = "SELECT * FROM tbl_customer WHERE CustomerName ='$username' AND password ='$password' ";
$run = mysqli_query($connect, $checkuser);
if (mysqli_num_rows($run)>0) {
$_SESSION['user_name'] = $username;
$_SESSION['start'] = time(); // Taking now logged in time.
// Ending a session in 30 minutes from the starting time.
$_SESSION['expire'] = $_SESSION['start'] + (10 * 60);
//header('Location:http://example.com/login/myaccount.php?username=' .$_SESSION['user_name']);
if($redirect) {
header("Location:". $redirect);
} else {
header("Location:login.php");
}
}
else {
$mainErr = "Username and/or password do not match! Try again!";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
checkuser($data);
}
?>