0

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);
}




?>
  • You only create the variable $redirect = NULL and give it a value if location is empty. If the user logs in correctly no value is given and therfore the user is redirected to "login.php". Though, i would recommend limiting users to only go to login,php when they are not logged in. – Anders Jun 29 '20 at 09:51
  • Thanks, I understand what you are saying however I don't know how to code this. –  Jun 29 '20 at 10:47
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Jun 30 '20 at 14:07
  • Thnk you very much for your comment Yes I have just been learning about prepared statements so I will go through and change my code to use prepared statements instead. –  Jun 30 '20 at 14:13

2 Answers2

0

get request url and after login return to this url $_SERVER['REQUEST_URI']

<?php
        if(isset($_SERVER['REQUEST_URI'])) {
            $rurl= htmlspecialchars($_SERVER['REQUEST_URI']);
        }
?>
<input type="hidden" name="location" value="<?php echo $rurl; ?>" />

After login make header to return url

 if(!empty($_SERVER['REQUEST_URI'])){
    header("Location:$_SERVER['REQUEST_URI']");
    }
    else{ 
    header("Location:dashbord.php");     
}
  • Thanks this seems to partly work as when the user is logged in the location now remains in the url however I am not being taken to the previous page. –  Jun 29 '20 at 10:47
  • i have been add return to ur location url coming from. – Berlik Tradingplc Jun 29 '20 at 11:11
0

Ok, using the comments above and some internet research I have got this working. The user needs to log in to the commentlisting page before they can view comments. So the url is saved in session logged in and the user is redirected to the login page.


    <?php
    // do check to see if user logged in
    if (!isset($_SESSION["username"])) {
        echo '<script>alert("you must be logged in ")</script>';
        $_SESSION['loggedin'] = $_SERVER['REQUEST_URI']; 
        header("location: login.php?location=" . urlencode($_SERVER['REQUEST_URI']));
        exit; 
    }
    ?>

After login checks session is set to true and user is redirected back to the url contained in the logged in session with the username appended to the url.


    $_SESSION["username"] = true;
    
    if(isset($username)) {
           header('Location:' .$_SESSION['loggedin'].'?username=' .$_SESSION['user_name']);       
        } else {
            header('Location:login.php');
     }

To get the full url including parameters you can use


     header("location: login.php?location=" . urlencode($_SERVER['REQUEST_URI']).$_SERVER['QUERY_STRING']);