0

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!!

Sanjeev Singh
  • 3,976
  • 3
  • 33
  • 38
mar
  • 111
  • 2
  • 4
  • 10

2 Answers2

5

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.
Community
  • 1
  • 1
Logan Wayne
  • 6,001
  • 16
  • 31
  • 49
  • 1
    I'd add a warning that passwords should be *salted* and *hashed*; and probably a link to [The definitive guide to form based website authentication](http://stackoverflow.com/q/549), a quick read through which will demonstrate how *hard* it is to build a secure web authentication system—often it is better to use a library or framework that has been thoroughly tested and proven than to try rolling one's own. – eggyal Mar 23 '15 at 08:28
1

Put this at the top of all of your pages:

if ($_COOKIE['authorized'] != '1'){
    header("Location: login.php");
    exit();
}
Nissa
  • 4,636
  • 8
  • 29
  • 37
Earle Davies
  • 176
  • 1
  • 9
  • Or use a header file. Put this in one file, and include the header file in each page, that is, include 'header.php'; This is better if you want to make changes later, and don't want to manually update each page. – Jonathan Wheeler Mar 23 '15 at 02:05
  • @earle Davies if ($_COOKIE['authorized'] != '1'){ header("Location: login.php"); exit(); } didn't work, when i put it on the top of each page the contents I extracted from my mysql database dissappear.. – mar Mar 23 '15 at 02:52
  • I don't think your cookie is actually being set. The second argument for a cookie should be a value, not just a 1 so you need to wrap it in an apostrophe or quotes. `setcookie('authorized', '1', 0);` OR `setcookie('authorized', "1", 0);` – Earle Davies Mar 23 '15 at 04:48