Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I protect a page only for logged users?

I created a login form that works great. But I realized the page my user is directed to can still be accessed by anybody. How do I protect the page being accessed only viewable by those logged in?

Do I need to place a script on the success page itself?

Here is my check_login.php:

<?php
$host="localhost"; // Host name
$username="xxx"; // Mysql username
$password="xxx"; // Mysql password
$db_name="xxx"; // Database name
$tbl_name="xxx"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

$count=mysql_num_rows($result);

$user_info = mysql_fetch_assoc($result);

 if( isset($user_info['url']) ) {

 session_register("myusername");
 session_register("mypassword");
     header('Location: ' . $user_info['url']); //Redirects to the supplied url from the DB
 } else {
  header("location:error.htm");
 }
 ?>
like image 265
Erik Avatar asked Jul 24 '11 22:07

Erik


3 Answers

Every of your page should start with

session_start();

and you should not be using session_register( "variablename" ) as of PHP version 4.2, use

$_SESSION["variable"] = value;

so example page with is-logged-it checking would be:

<?php
session_start();
if($_SESSION["loggedIn"] != true) {
    echo("Access denied!");
    exit();
}
echo("Enter my lord!");
?>

and logging-in script:

<?php
    /*
        ... db stuff ...
    */

if( isset($user_info['url']) ) {
    $_SESSION["loggedIn"] = true;
    $_SESSION["username"] = $myusername;
    header('Location: ' . $user_info['url']); //Redirects to the supplied url from the DB
} else {
    header("Location: error.htm");
}
?>
like image 59
Sebi Avatar answered Oct 20 '22 00:10

Sebi


On the page that requires the user to be logged in check to see if they have a valid session. If not send them to the login page.

if (!$_SESSION['myusername'])  
{  
    header('location: /login.php');  
    exit;  
}
like image 32
plague Avatar answered Oct 19 '22 22:10

plague


In each page/content with restricted access, you should authenticate the client/user. If people were crazy then you'd have to make the user fill in his details (username/password) in every page, but thanks to "HTTP cookies" - we don't have to do that.

like image 25
Dor Avatar answered Oct 20 '22 00:10

Dor