session - PHP: Create a simple log in form without MySQL
I'm trying to mess around with a simple log in form, that is just for fun. The content is nothing sensitive, but I'm trying to learnSESSION
and such. I've created this simple login form, that works fine, but if a user clicks the"home"
button which ishref'd
toprocess_login.php
, they are asked to login again. I'm trying to save theusername
andpassword
it in aSESSION
so if they login, and hithome
from any page, it will remember their log in information and not ask them to continuously log in.
I have aform.php
script, that uses thePOST
method, with twotextfields
, the username and password are saved as "admin" in theprocess_login.php
, and if they match thePOST
indices
from the form, then i'll includecontent.php
. Inprocess_login.php
I take thePOST
data and run it like so :
SESSION_start();
//var_dump($_POST);
$match_username = 'admin' ;
$match_password = 'admin';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == $match_username && $password == $match_password ){
include 'content.php';
}elseif($username == "" || $password != $match_password){
echo "Please try again.";
}
if(!isset($_SESSION["logged_in"])){
//Run if not set
$_SESSION["logged_in"] = array(1 => array($username => $_POST['username'], $password => $_POST['password']));
};
};
You'll see above that I'm trying to set the SESSION information, but I know i'm not doing it correctly. Once a user logs in, everything works. But if that same user clicks on "home," from another page, it will tell them to "Please try again.
" I'd like to let the user stay logged in once they are logged in.
All advice is appreciated. Thank you!
Answer
Solution:
Your test of
$_SESSION["logged_in"]
should not be inside theif(isset($_POST['submit']))
block.I changed your
$_SESSION["logged_in"]
variable. Now it's just a one-dimensional array instead of 2-dimensional, and the keys are the wordsusername
andpassword
-- it doesn't make much sense to use variables as keys there.