views:

62

answers:

4

Hey Guys,

I've got the following login script..

<?php
$name = $_POST["name"];
$password = $_POST["password"];
$query = "SELECT * FROM users WHERE username = '$name'
         AND password = '$password'";
$q=mysql_query($query) or die(mysql_error());
$result = mysql_query($query);
if (mysql_fetch_row($result)) {
  /* access granted */
  session_start();
  header("Cache-control: private");
  $_SESSION["access"] = "granted";
  header("Location: ./menu.php");
  } else
  /* access denied &#8211; redirect back to login */
  header("Location: ./login.html");
  ?>
  mysql_close();
  ?>

But what would I now need to "menu" to redirect users who are not logged in to the login page? to prevent direct access?

Thanks.

+4  A: 

in menu.php?

session_start();
if (!isset($_SESSION['access']) || $_SESSION['access'] != "granted") {
  header("Location: ./login.html");
  exit();
}
Fosco
Don't forget a session_start() at the top
Mark Baker
You forget to close isset().
Lex
@Lex, fixed thanks.
Fosco
+1  A: 

Check the value of $_SESSION["access"] on the top of your menu.php. Also, you miss a call to session_start. It may not be needed if you have session.auto_start enabled, but it's good habit to explicitly call it.

Maerlyn
+2  A: 

You have to put something like this at the top of menu.php:

<?php
    session_start();
    if(!isset($_SESSION['access']) || $_SESSION['access'] != 'granted'){
        header("Location: ./login.html');
    }
?>

And don't forget to sanitize your query input:

$name = mysql_real_escape_string(stripslashes($_POST["name"]));    
$password = mysql_real_escape_string(stripslashes($_POST["password"]));    

And don't forget to call session_start(); at the beginning of each script that uses $_SESSION

Lex
`stripslashes` is only needed if he has magic_quotes_gpc enabled
Maerlyn
+1 for the more complete example code.
Fosco
A: 

Check $_SESSION["access"] in menu to see if the user is logged in. By the way, you should read on SQL injection and rewrite that SQL query using escaping.

DrunkenBeard