Using Sessions & Session Variables in a PHP Login Script

Using sessions & session variables in a PHP Login Script

Hope this helps :)

begins the session, you need to say this at the top of a page or before you call session code

 session_start(); 

put a user id in the session to track who is logged in

 $_SESSION['user'] = $user_id;

Check if someone is logged in

 if (isset($_SESSION['user'])) {
// logged in
} else {
// not logged in
}

Find the logged in user ID

$_SESSION['user']

So on your page

 <?php
session_start();


if (isset($_SESSION['user'])) {
?>
logged in HTML and code here
<?php

} else {
?>
Not logged in HTML and code here
<?php
}

PHP Login, Store Session Variables

Let me bring you up to speed.

Call the function session_start(); in the beginning of your script (so it's executed every page call).

This makes sessions active/work for that page automagicly.

From that point on you can simply use the $_SESSION array to set values.

e.g.

$_SESSION['hello'] = 'world';

The next time the page loads (other request), this wil work/happen:

echo $_SESSION['hello'];  //Echo's 'world'

To simply destroy one variable, unset that one:

unset($_SESSION['hello']);

To destroy the whole session (and alle the variables in it):

session_destroy();

This is all there is about the sessions basics.

Sessions in PHP, login script

After Username and Password authentication:

$query=mysql_query("SELECT * FROM users where username='$username' AND password='$password' "); 

$count=mysql_num_rows($query);
if($count==1)
/* $count checks if username and password are in same row */
{
echo "Login Successful";
$hour = time() + 3600;
<--- PUT HERE INSTRUCTION BELOW
}

You should store username in a $_SESSION variable when you verify that he is authenticated:

 $_SESSION['user'] = $username;

At beginning of all other pages you should put command

session_start();

and then use an if statment to check if gloabal session variable user is set:

<?php

if( isset($_SESSION['user'])){

?>

//HTML of page if user is authenticated

<?php

}else{

?>

//HTML of page if user is authenticated

<?php


}

?>

Login implementation in PHP

Yes using and creating ($_SESSION) session is the correct way to check logged in users.

$_SESSION is a 'superglobal', or automatic global, variable. This
simply means that it is available in all scopes throughout a script.
There is no need to do global $variable; to access it within functions
or methods.

Check for session on very top of a page, if found redirect to index else to login page.

if(!isset($_SESSION['login_user'])){
header("location:login.php");
}

Refer this simple login example using my sql in php Here

EDIT

As requested by OP - if you want to hide a particular section in index.php page based on session value or say if a user is logged in or not that can be done like:

<?php
if(isset($_SESSION['login_user'])){
?>
<form>
<input type="submit" name="whatever" />
<!-- Other Fields -->
</form>
<?php
}
?>

Html Form in the above code will only be shown if a user is logged in else it will be hidden.

php keep user logged in using session, after changing page

@waterloomatt & @Isaac thanks for your time and responses! After so many hours, finally i found the code that works. If you see anything wrong, i would be happy to know!
Will i have problems with SQL Injection attacks?

login.php

<?php
session_start();

include 'db_info.php';

//connect to db
$conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName)
or die($conn);

//get values
if ((isset($_POST['user'])) && (isset($_POST['user']))){
$username = $_POST['user'];
$password = $_POST['pass'];
} else {
$username = null;
$password = null;
}

//prevent mysql injection
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);

//encrypt pass
$encrypted = hash('sha256', $password);

//search
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$encrypted'";
$result = mysqli_query($conn, $sql) or die("Failed to query database ".mysqli_error($conn));

//compare
$row = mysqli_fetch_array($result);
if (($row['username'] != $username) || ($row['password'] != $encrypted)){
if ((isset($_POST['user'])) && (isset($_POST['pass']))){
$_SESSION['msg'] = 'Credentials mismatch';}
} else {
$_SESSION['id'] = $row['id'];
$_SESSION['user'] = $row['username'];
}
mysqli_close($conn);


?>

mysky.php

<?php 
include 'login.php';

if ((isset($_SESSION['id'])) && (isset($_SESSION['user'])))
{
include 'sky_auth.php';
}
else
{
include 'sky_login.php';
}

include 'footer.php';
?>

sky_login.php

<?php 
$pageTitle = 'MySky Login';
include 'header.php';
?>


<div id="cloud_box">
<div id="cloud_title">My<span>Sky</span> Login</div>

<form action="" name="form" method="POST" onsubmit="return IsEmpty();">

<div id="msg"><?php if (isset($_SESSION['msg'])){
echo $_SESSION['msg'];
unset($_SESSION);
session_destroy();} ?>
</div>

<div id="u">
<div id="user1">U</div>
<input type="text" id="user" name="user"/>
<div id="error_u"></div>
</div>

<div id="p">
<div id="pass1">P</div>
<input type="password" id="pass" name="pass"/>
<div id="error_p"></div>
</div>

<button id="btn" type="submit">Login</button>

</form>

</div>

sky_auth.php

<?php
if(!isset($_SESSION['id']))
{
header("Location: mysky.php");
die();
}
$pageTitle = sprintf('MySky - %s', $_SESSION['user']);
include 'header.php';
?>

<div id="sky_contain">

<div id="logout"><a href="logout.php">Logout</a></div>

</div>

</div>

Sessions in PHP and login confusion

to clear your confusion I will go point by point

So a new session should be created now, right? Why do we include session_start() in the beginning of login.php then?

We include session_start() because it says PHP to start session then and then you can store any information in $_SESSION, so session_start() is necessary


But on the server side, how will USER A's request be linked with USER A's details in the db and how will USER B's request be linked with USER B's details in the db ?

When user login's we store user's (unique) information in $_SESSION.

For example if USER A is logged in than I will get his ID from db and store it in $_SESSION['uid'] and other info if needed.

Then when I want other information of USER A on any page I will just get his ID from $_SESSION and make query according to this.


I hope this will clear your confusion.

PHP Login script with ajax works but session variables do not exist

I have reviewed your code. Everything is perfect . But the problem is when you are assigning the session in "FILE -> functions.php -> loginMember($riziv, $password)". It will not be available to every pages beacuse you are requesting through ajax.

There is two way to resolve it either reload the page after successful login OR return the value from "FILE -> functions.php -> loginMember($riziv, $password)" and reset session in

"FILE -> adminpanel.php"

I hope you will get help from my response.



Related Topics



Leave a reply



Submit