Question

How do I protect pages using sessions PHP?

Asked by: dialeradmin

Hi.

I am new at PHP and I am working on creating a secure website.  Let me give you a quick rundown of what I currently have.

I have an index.php which is the login page.  When you first visit the website, you are required to first login on this index.php.  If you enter correct login information, it takes you to the specified location in the header.

However, I was curious as to how to do two things.
1.) I need to create a session so that all of my pages can only be viewed if the user is logged in.  As of now, if anyone knew the complete web address for any of my other pages, they could view it, regardless of being logged in or not.  I cannot figure out how to create a session and keep it running with the code I currently have.  Hopefully someone can help me out!

2.) I also have a Level_access field set in my SQL database that I want to direct people to different locations based on their "access level".  For example, let's say person A has access level "1".  I want that person to go to the administrator main page.  But person B has access level "2".  I want that person to go to the members main page.  Is there a way I could do that with my code as well?

Here is the code I have for the index.php...Any help is appreciated!!!

<?php
require_once('db.php');
include('functions.php');

if(isset($_POST['Login']))
{
   if($_POST['username']!='' && $_POST['password']!='')
{
//Use the input username and password and check against 'users' table
$query = mysql_query('SELECT ID, Username, Active FROM users WHERE Username = "'.mysql_real_escape_string($_POST['username']).'" AND Password = "'.mysql_real_escape_string(md5($_POST['password'])).'"');
                  
if(mysql_num_rows($query) == 1)
{
$row = mysql_fetch_assoc($query);
   if($row['Active'] == 1)
   {
    session_start();
    $_SESSION['user_id'] = $row['ID'];
    $_SESSION['logged_in'] = TRUE;
    header("Location: members.php");
   }

   else {
    $error = 'Your user account was not activated. Please open the email that was sent and click on the activation link.';
   }
}

else {            
header("Location: login_fail.php");            
}
}

else {
$error = 'Please enter both your username and password to access your account';
}
}
?>

<?php if(isset($error)){ echo $error;}?>

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2007-06-29 at 09:05:23ID22667069
Tags

pages

,

php

,

protect

,

using

,

sessions

Topics

PHP Scripting Language

,

PHP and Databases

,

PHP for Windows

Participating Experts
3
Points
500
Comments
15

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. isset($_SESSION['username']) problem
    I have a problem with isset($_SESSION['username']). when i use this code <? if (isset($_SESSION['username'])) { echo '<tr> <th width="100%" align="left" valign="middle" bordercolor="#CCCCCC" bgcolor=&q...
  2. PHP mysql_fetch_assoc() Error
    I'm trying to create a program that stores and pulls data from a mysql database. The problem i'm having is that about half the time, when its pulling information from the database, it will give me this error: Warning: mysql_fetch_assoc(): supplied argument is not a valid My...
  3. mysql_fetch_assoc() error problem
    I am trying to pump the results of this query directly into an array, but i am getting a mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource error $sql = "SELECT DISTINCT p.products_id, p.products_image, p.products_date_available, pd.products_na...
  4. Warning: mysql_fetch_assoc():
    Hi guys, I updated the apache and php to the following versions, and now some of my scripts are not working anymore. here is the error msg i am receiving now. PHP version 5.2.5 MySQL version 4.1.22-standard Apache version 2.0.63 Warning: mysql_fetch_assoc(): supplied...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: coviexPosted on 2007-06-29 at 09:42:08ID: 19391496

1) You already have a session "$_SESSION['logged_in'] ".

So all you need now is to create a function or single file which will check if user is logged in right at the start of each script.

<?php
if (!isset($_SESSION['logged_in'] ))
{
    header("Location:index.php");
}
?>

2) Create new field in members table in DB and grant certain access rights upon registration process or whenever you want later depending on certain user`s action.
Then in index.php instead of

<?php
if($row['Active'] == 1)
   {
    session_start();
    $_SESSION['user_id'] = $row['ID'];
    $_SESSION['logged_in'] = TRUE;
    header("Location: members.php");
   }
?>

white something like :

<?php
if($row['Active'] == 1)
   {
    session_start();
    $_SESSION['user_id'] = $row['ID'];
    $_SESSION['logged_in'] = TRUE;

switch ($row['level'])
{
    case 1 :
    {
        header("Location: admin.php");
        break;
    }
    case 2 :
    {
        header("Location: members.php");
        break;
    }
}
}
?>

 

by: dialeradminPosted on 2007-06-29 at 10:54:10ID: 19392113

coviex...

I tried your solution to question #1...

What I did was place the code you provided me with onto let's say (members.php and admin.php):

<?php
if (!isset($_SESSION['logged_in'] ))
{
    header("Location:index.php");
}
?>

Now, without logging in, I try to access those pages by typing in the full url...The result takes me to index.php.  When I try to login, the result takes me to index.php.  I can't get anywhere but the index...So then I was thinking that I should change the header on each page the code was pasted on, to that page's location...I tried that, and the result was the page loading very slow until it eventually timed out.

Maybe there is something I'm doing wrong?  Or maybe I didn't post the code on the right pages?  Can you clear some things up as to where I'm supposed to put the code, and am I supposed to change anything according to what page it is?

Thanks

 

by: i_m_aamirPosted on 2007-06-29 at 10:59:11ID: 19392157

i guess you have included some common file e.g. header.php or something like that on every page and you can use this logged in check script on that page

 

by: ZSoderquistPosted on 2007-06-29 at 13:18:52ID: 19393219

session_start(); need to be on the first line

<?php
session_start()
if (!isset($_SESSION['logged_in'] ))
{
    header("Location:index.php");
}
?>

 

by: dialeradminPosted on 2007-06-29 at 13:43:10ID: 19393433

Awesome...That is working!  Before I award points, hopefully someone can help me with question #2.  I'm still having troubles with that.

I currently have a field set up in my SQL database titled ,"Level_access".  In order to redirect a user to a certain page after login, how should I approach it, again?  I couldn't get the switch method coviex suggested working...Any final help??  Thanks!!!!!!

Here is my index.php once more:
==============================================
<?php
require_once('db.php');
include('functions.php');

if(isset($_POST['Login']))
{
      if($_POST['username']!='' && $_POST['password']!='')
      {
      //Use the input username and password and check against 'users' table
      $query = mysql_query('SELECT ID, Username, Active FROM users WHERE Username = "'.mysql_real_escape_string($_POST['username']).'" AND Password = "'.mysql_real_escape_string(md5($_POST['password'])).'"');
                  
            if(mysql_num_rows($query) == 1)
            {
            $row = mysql_fetch_assoc($query);
            if($row['Active'] == 1)
                  {
                  session_start();
                  $_SESSION['user_id'] = $row['ID'];
                  $_SESSION['logged_in'] = TRUE;
                  header("Location: members.php");
                  }
                  else {
                  $error = 'Your user account was not activated. Please open the email that was sent and click on the activation link.';
                  }
            }
            else {            
            header("Location: login_fail.php");            
            }
      }
                     else {
      $error = 'Please enter both your username and password to access your account';
      }
}
?>

 

by: ZSoderquistPosted on 2007-06-29 at 16:40:57ID: 19394219

Here's a possible example: Add a field to your table named `access` field type ENUM ('1','2','3')
in your sql query add the `access` field to the list then:
<?
switch($row['access']) {
    case 1:
          header("Location: access1.php");
          break:
    case 2:
          header("Location: access2.php");
          break:
    case 3:
          header("Location: access3.php");
          break:
    default:
          header("Location: index.php");
}
?>  

 

by: ZSoderquistPosted on 2007-06-29 at 16:42:41ID: 19394226

Now .. the big thing about header redirecting is that there can not be anything ANYTHING echo'd out prior to calling the header. No spaces or line breaks outside of PHP <? ?> tags or anything.

 

by: coviexPosted on 2007-06-30 at 00:31:33ID: 19395163

ZSoderquist don`t you think that reposting other's code is not very nice?!

 

by: dialeradminPosted on 2007-07-02 at 07:09:09ID: 19403561

Alright.  I did as both ZSoderquist and Coviex suggested by using the switch case in my index.php.

Now, the result is whenever the correct username and password has been entered, it takes you nowhere, and instead reloads the index.php, which is the login page.

I have posted the index.php, which contains the updated code using switch statements.  Please let me know if something is wrong within my code.  Any last suggestions?  Thanks!

index.php
============================================
<?php
require_once('db.php');
include('functions.php');

   if(isset($_POST['Login']))
   {
      if($_POST['username']!='' && $_POST['password']!='')
      {
      //Use the input username and password and check against 'users' table
      $query = mysql_query('SELECT ID, Username, Active FROM users WHERE Username = "'.mysql_real_escape_string($_POST['username']).'" AND Password = "'.mysql_real_escape_string(md5($_POST['password'])).'"');
                  
            if(mysql_num_rows($query) == 1)
            {
                  $row = mysql_fetch_assoc($query);
                  if($row['Active'] == 1)
                  {
                        session_start();
                        $_SESSION['user_id'] = $row['ID'];
                        $_SESSION['logged_in'] = TRUE;
                              
                        switch($row['Level_access'])
                        {
                            case 1:
                        {
                                 header("Location: control_panel.php");
                                  break;
                        }
                            case 2:
                        {
                                  header("Location: members.php");
                                  break;
                        }
                        }
                  }
                  else {
                  $error = 'Your user account was not activated. Please open the email that was sent and click on the activation link.';
            }
      }
            else {            
            header("Location: login_fail.php");            
            }
      }
      else {
      $error = 'Please enter both your username and password to access your account';
      }
}
?>

<?php if(isset($error)){ echo $error;}?>

 

by: ZSoderquistPosted on 2007-07-02 at 07:28:39ID: 19403727

You need to update your SQL query


$query = mysql_query('SELECT ID, Username, Active, Level_access FROM users WHERE Username = "'.mysql_real_escape_string($_POST['username']).'" AND Password = "'.mysql_real_escape_string(md5($_POST['password'])).'"');

 

by: dialeradminPosted on 2007-07-02 at 07:41:44ID: 19403858

Yes.  Thank you!
I must have overlooked that so many times!!!

I award ZSoderquist with the points, thanks to being very clear in his instructions, and for his continued help!

 

by: ZSoderquistPosted on 2007-07-02 at 07:42:54ID: 19403870

coviex:  ZSoderquist don`t you think that reposting other's code is not very nice?!

coviex, I apologize, I didn't know you were the creator of the switch statement, even though yours is syntatically incorrect :) .. btw, I'm here to help people, I could care less about the points. Maybe you could try that sometime :)

 

by: ZSoderquistPosted on 2007-07-02 at 07:44:08ID: 19403886

dialeradmin, thanks for the grade and good luck.

 

by: coviexPosted on 2007-07-03 at 00:45:05ID: 19409399

ZSoderquist: maybe you`ll try to read some manual on switch statement. i`m sure you`ll find something new for you in it`s syntax =) Or i have even better advise - don`t spent so much time helping people, find yourself a paid job =)

 

by: ZSoderquistPosted on 2007-07-03 at 08:02:38ID: 19411797

coviex, the conversation has turned quite immature so I will not continue on with it. I do wish you luck and thanks for contributing and using experts-exchange

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...