mar mar - 10 days ago 6
MySQL Question

How to redirect users to login page if they haven't logged in?

I have the following code for my login page login.php:

<form method="post" action="confirmLoginCredentials.php">
<h2>LOGIN</h2>
<p>Username: <input type="text" name="username" /></p>
<p>Password: <input type="password" name="password" /></p>
<p><input type="submit" name="submit" value="Login" /></p>

</form>


After submitting, It redirects to confirmLoginCredentials.php which is:

<?php

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

require_once 'config.php';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$q = "SELECT first_name, last_name FROM users WHERE user_name = '$username' AND password = '$password'";

$result = $mysqli->query($q) or die(mysqli_error($mysqli));


if (!mysqli_num_rows($result) == 1) {
header("Location: login.php");
}
else {
setcookie('authorized', 1, 0);
header("Location: index.php");
}

?>


This works fine and it redirects the user to the index page if they have logged in successfully. How do I redirect the user to the login.php page from all pages in my website if they have not yet logged in? (in other words, the user cannot access the contents of my site if they have not logged in) what code should i put in all other pages of my site to do this?

any help will be very much appreciated!!
thanks!!

Answer

NOTE:

  • You can use SESSION function to achieve your goal
  • Do not mix mysql_* function with mysqli_*
  • It is better to use mysqli_* prepared statement so you don't have to escape each of your variables, and it is a better way to prevent SQL injections.

Your config.php:

<?php

$mysqli = new mysqli("DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME"); /* REPLACE NECESSARY DATA INSIDE */

/* check connection */
if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
}

?>

Your confirmLoginCredentials.php:

<?php

session_start(); /* START THE SESSION */

include("config.php");

if($stmt = $mysqli->prepare("SELECT first_name, last_name FROM users WHERE user_name = ? AND password = ?")){

  $stmt->bind_param("ss",$_POST["username"],$_POST["password"]); /* BIND VARIABLES TO YOUR QUERY */
  $stmt->execute(); /* EXECUTE THE QUERY */
  $stmt->store_result();
  $result = $stmt->num_rows; /* STORE NUMBER OF ROWS */
  $stmt->bind_result($firstname,$lastname); /* STORE THE RESULT */
  $stmt->fetch(); /* FETCH THE RESULT */
  $stmt->close(); /* CLOSE THE STATEMENT */

  if($result == 1){ /* IF FOUND ONE */
    $_SESSION["username"] = $firstname; /* STORE THE USERNAME INTO A SESSION VARIABLE */
    header("LOCATION:index.php"); /* REDIRECT USER TO INDEX PAGE */
  }
  else { /* IF NO RESULT FOUND */
    header("LOCATION:login.php"); /* REDIRECT USER TO LOGIN PAGE */
  }

} /* END OF PREPARED STATEMENT */

?>

Then create a header.php to be included in all your pages, excluding your login.php:

<?php
  session_start();
  if(empty($_SESSION["username"])){ /* IF NO USERNAME REGISTERED TO THE SESSION VARIABLE */
    header("LOCATION:login.php"); /* REDIRECT USER TO LOGIN PAGE */
  }
?>

Example in your index.php:

<?php
  include("header.php");
?>
<!-- YOUR INDEX PAGE -->

If a logged-in user accessed your login page, you can redirect him/her to the index page like this:

<?php
  session_start();
  if(!empty($_SESSION["username"])){ /* IF USERNAME IS ALREADY ASSIGNED ON SESSION VARIABLE */
    header("LOCATION:index.php"); /* REDIRECT USER TO INDEX PAGE */
  }
?>
<form method="post" action="confirmLoginCredentials.php">
<h2>LOGIN</h2>
    <p>Username: <input type="text" name="username" /></p>
    <p>Password: <input type="password" name="password" /></p>
    <p><input type="submit" name="submit" value="Login" /></p>
</form>

For your logout.php, you can use unset() and would look like this:

<?php
  session_start();
  unset($_SESSION["username"]);
  header("LOCATION:login.php");
?>

Extra Note:

  • You should have session_start(); at the beginning of your code if you're gonna use a session variable or functions.