braddarb braddarb -5 years ago 85
PHP Question

PHP Session to authenticate user access to pages

I am trying to implement a user login system to my website. I have already made the register login feature and now I am trying to use session to make it so only logged in users can access certain pages, the code for my login page is as follows:

<? session_start(); ?>

<div align="left">
<a href='register.php'>REGISTER&nbsp; <i class="fa fa- user-plus" aria-hidden="true"></i></a>

<link href="css/hawthorne_type1_color1.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">

<form action="" method="POST">
<h3>USERNAME:</h3><input id="username" type="text" name="username"/>
<h3>PASSWORD:</h3><input id="password" type="password" name="password"/><br>
<input class="login" type="submit" name="submit" value="Login" />

if (isset($_POST['username']) and isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM user WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);

if (isset($_POST['submit'])) {
if ($count == 1) {
$_SESSION['username'] = $username;
} else {

$_SESSION['username'] = null;

if (isset($_SESSION['username'])) {
<script type="text/javascript">location.href = '';</script>
$_SESSION['username'] = $username;
} else {


I tried to use the following on each page I want to protect but had no luck:


if (!isset($_SESSION['username'])) {
// use is not logged in
} else {
// user is logged in

Any idea what I'm doing wrong? Any help appreciated.

Answer Source

Using the MySQL API to count the number of rows in a result-set appears to be a popular approach but also the source of endless questions here. I suggest you actually try to fetch a row and:

  1. If row found, user is valid

  2. Otherwise, it isn't

That also allows to grab other user details you might want to use/display such as user profile, full name, etc. In fact, even username should be displayed as stored in DB rather than as typed in last login.

Your code could use some improvements but I'll give you a piece of advice I consider particularly useful: drop your current learning material (on-line tutorial, book, whatever), which is extremelly outdated and probably not good in the first place, and find something better. At least something that uses PDO, prepared statements and password_verify(). Life's too short to learn things you don't need.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download