Proper way to do a user login? Cookies?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Proper way to do a user login? Cookies?

Post by social_experiment »

Stacks wrote:Could you give me an example? I've never seen a "custom" session Id.

Code: Select all

<?php
 // start session
 session_start();
 // create a random number
 $random_number = mt_srand();
 // hash it to make it more difficult to guess
 $random_hashed_number = hash('md5', $random_number);
 // create a session variable
 $_SESSION['custom_sessionId'] = $random_hashed_number;
 //
?>
Now you have a random, unknown, 32 character value that you can use as a session id. It's custom because the people using your system (and an attacker) doesn't know how it's generated. Use it like so (auth page or wherever)

Code: Select all

<?php 
 //
 session_start();
 //
 if (!isset($_SESSION['custom_sessionId']) || (!isset($_SESSION['another_value'])) {
 header('invalid.page');
 }
?>
You are now setting 2 conditions in place to be met for 'authentication' to be valid. If you want to go further, write the custom session id to the database and when you 'auth' check if the $_SESSION['custom_sessionId'] matches that value inside the database, if not, bye-bye unauthorised user.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Post Reply