how would one go about making a login script using sessions that save to the database?

That's a lot of questions in one. It would be nice to know what you already know. To develop a login script using sessions stored in a database, you'll need to know how to:

  • Program with PHP
  • Connect to a database to insert, update, and select data using PHP.
  • Redirect to another page in PHP
  • Use PHP includes
  • Build an HTML form
  • Process an HTTP POST or GET in PHP.

The basics of how I do it is I create a script named login.php for example. This script will serve these functions:

  1. Output an HTML login form.
  2. As the target of the form, process the form to test the username and password against your authentication source--most likely a database.
  3. If authentication fails, re-output the login form with a failure message so the user can try again.
  4. If authentication succeeds, create a session and/or save session data in database, then redirect to the originally requested page.

I "remember" the originally requested page by passing the value in my login form, but you could use cookies or a session variable instead.

The other part of the equation is to build an include script that you include in every PHP page you want to protect. This script checks the session to see if the user is authenticated. (Do this by checking whatever session variable you use to test or by looking at whatever POST or GET parameter you use to maintain the session.) If the user is not logged in, redirect to login.php. Otherwise allow the page to proceed. (When you redirect to login.php, pass the current filename to login.php to "remember" the requested page so that once authentication passes, you can redirect back to where the user was going.

I hope this helps you understand the architecture of building such a system. If you are not a PHP programmer already, then you really need to start with learning PHP. This would not be a good PHP tutorial project in my opinion.

This article has been dead for over six months. Start a new discussion instead.