Jump to content

PHP Session - more examples would be nice


Neo

Recommended Posts

Hi

 

I would like to request an expansion to PHP Sessions as I think that the provided example of how to use sessions for making a page counter is too simple.

 

Therefore I would like to suggest that a small tutorial about how-to-make-a login system using session to be added to the PHP Session chapter.

Link to comment
Share on other sites

index.php

<?phpsession_start();if (isset($_SESSION['username'])) {//User has logged inecho "Logged in as: " . $_SESSION['username'];} else {echo "<h3>Login to have access on page.</h3><form method='post' action='login.php'>Username: <input type='text' name='user'>Password: <input type='password' name='pass'><input type='submit' value='Login'></form>";}?>

login.php

<?phpsession_start();$user = "John"; //Example username$pass = "125Eas%"; //Should do this with SQL but easier to understand with phpif (!isset($_SESSION['username'])) {if (isset($_POST['user']) && $_POST['user'] == $user && isset($_POST['pass']) && $_POST['pass'] == $pass) {$_SESSION['username'] = $_POST['user'];echo "<p>Login success. You are logged in as: " . $_SESSION['username'] . "</p>Return to mainpage, click <a href='index.php'>here</a>!";} else {echo "<p>Wrong username or password.</p>";}} else {echo "Already logged in as: " . $_SESSION['username'];}?>
Edited by Mudsaf
Link to comment
Share on other sites

This works. Of course you can immediately begin to consider various refinements. For example raw input from a user can't be trusted because it could be XSS or an attempt at SQL injection. Also don't you want to limit them to only so many failed login attempts per hour or per day? Also they may need a way to recover if they really forgot their username or password. Also the password and username are flowing across the internet in plain text.

 

To get a giant headache you can study...

 

https://www.owasp.org/index.php/PHP_Security_Cheat_Sheet

Edited by davej
Link to comment
Share on other sites

Typically sites like this focus on offering references or basic examples of the common core and native features of a language. Something like a login system is typically the product of putting together many individual pieces, usually encompassing multiple languagues, into one larger, high-level system and typically fall out of scope for a site like this. Given that, there are numerous tutorials an examples online of many common website features, like login / registration systems, file uploaders, etc.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...