PHP Session Management - Basics - php

i have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner

First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}

Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? ยป Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>

Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.

It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.

Related

How to use $_SESSION in right way?

At the moment I am writing a little media library in PHP and i want to set sessions, so the user stays logged in and get's echoed his name at the front page.
[index.php]
if(isset($_SESSION['loggedin']))
{
//ECHO $USERNAME
}else{
echo '<p>To start, please login or register.</p>';
}
?>
I want, if theres an session id set, that PHP echoes out the $username.
[signup.php]
<?php
session_start();
$conn = mysqli_connect("$host", "$user", "$pass", "$db");
$uid = ($_POST['uid']);
$pw = ($_POST['pw1']);
$pw2 = ($_POST['pw2']);
if ($pw == $pw2) {
$sql = "INSERT INTO user (uid, pw) VALUES ('$uid', '$pw')";
$result = mysqli_query($conn, $sql);
echo "Registration succeeded.";
}else{
echo "Please check your information.";
}
header ("Refresh: 3; ../index.php");
So, after PHP successfully compares my $pw1 and $pw2 i want to start a session, then it should put the $username in the $_SESSION array.
Of course next to the secure session id.
I repeat, after this i want to echo the $username out at front page.
What is the best way to do it?
Thanks.
$sql="SELECT username FROM users WHERE userid=$uid";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($result);
$_SESSION['username']=$row['username'];
You can do something like this.
Usage of $_SESSION super global array (compact version)
session_start(); //To init
$_SESSION['username'] = 'Bob'; // Store value
echo $_SESSION['username']; // Treat like normal array
Detailed example
To use a session, you have to init it first.
session_start();
After that you access the session vars via the super global
$_SESSION
A good way is always to store a value in your variables you want to use:
// init session
session_start();
// check if session var is set, if not init the field with value in the super global array
if(!isset($_SESSION['auth'])) $_SESSION['auth'] = false;
if(!$_SESSION['auth']) {
//do auth here like eg.
header('Location: signup.php'); // if auth is okay -> $_SESSION['auth] = true + redirect to this (main) script
die(); // This is really necessary because a header redirect can be ignored.
}
// if auth okay, do fancy stuff here
For security read the following
Remember to escape your user input, always!
How can I prevent SQL injection in PHP?
The session_id is stored in cookies normally.
Or - the old way via URL parameter.
You do not have to secure the session_id.
Read also advices about XSS/CSRF.
Plus tokens are also good.
May be this is what you mean with secure session_id.
Stackoverflow: preventing csrf in php
OWASP: https://www.owasp.org/index.php/PHP_CSRF_Guard
OWASP: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet

PHP Session Variable gets lost between pages.

I have made a simple login page to access an application. The login works fine at times, but from time to time, I'll have trouble logging into the system, as the session data will be lost on the last page.
The files I have are
1) login.php, with Login name and Password Field.
2) loginprocess.php - Which will connect to the database to check whether there username and password exists, after which a session is created.
3) listing.php - Which will be the final page if login is successful.
The loginprocess.php page will create a session variable if Login Name and Password exists in the database. It'll then redirect to the last page.
$selectstring = "SELECT * FROM logintable WHERE username='".$loginname."' AND password='".$pass."'";
$result = mysql_query($selectstring);
//IF YES THEN GO TO MAIN
if(mysql_num_rows($result) > 0)
while($row = mysql_fetch_array($result))
{
//CREATE SESSION
session_start();
// Set session variables
$_SESSION["loginname"]= $loginname;
header("Location: listing.php");
exit;
}
else {
echo "ERROR";
header("Location: login.php?message=error");
exit;
}
At the top of the last page, listing.php, I'll have a script that will redirect if session variable is empty.
session_start();
if (!isset($_SESSION['loginname']) && empty($_SESSION['loginname'])) {
header("Location: login.php");
}
Am I inserting session_start(); too late on loginprocess.php ?
First, move the session_start(); to the top of your file.
Next, you need to do an OR instead of an AND in your if, because the login name is either unset or empty.

PHP - Managing Session - Doesnt Logout

I have created a user authentication system with necessary DB tables and php.
THe first time before I login (Before any SESSION is created) the redirect on every page works perfect (ie Redirects to the login page if not logged in).
But once I login with a user and then logout the same doesnt work. I think it might be a problem with not ending the SESSION (Sorry if am wrong)
Here are some pieces of the code in each Page
Login PHP
<?php
session_start();
$message="";
if(count($_POST)>0)
{
include('config.php');
echo $_POST['username'];
$result = mysql_query("SELECT * FROM members WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["id"] = $row[ID];
$_SESSION["username"] = $row[username];
$_SESSION["password"] = $row[password];
$_SESSION["mname"] = $row[mname];
$_SESSION["fname"] = $row[fname];
date_default_timezone_set("Asia/Calcutta");
$lastlog=date("d/m/Y");
$logtime=date("h:i a");
$query = "UPDATE `members` SET `lastlogin`='$lastlog',`logintime`='$logtime' WHERE `ID`='$row[ID]'";
mysql_query($query);
$_SESSION['logged'] = TRUE;
}
else
{
echo "<SCRIPT>
alert('Wrong Username/Password or Awaiting Approval');
</SCRIPT>";
header("Location:login_failed.html");
}
}
if(isset($_SESSION["id"])) {
header("Location:member/myprofile.php");
}
?>
PHP code on every page
<?php
session_start();
include('config.php');
if(!$_SESSION['logged'])
{
header("Location: ../login.html");
exit;
} ?>
And Finally Logout
<?php
session_start();
unset($_SESSION["id"]);
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["mname"]);
unset($_SESSION["fname"]);
header("Location:../login.html");
?>
Is there any problem with my Code. Am i missing something? I couldn't get it right. Pls Help
Thanks guys got it solved..
Now can you tell me How I can redirect login.php to user home page(myprofile.php) in case the User is logged in (Session exists) - Like facebook,gmail etc
Instead of calling unset() on each session var, you can simply use session_destroy(), which will destroy all of the current session data.
session_start();
session_destroy();
header("Location:../login.html");
For complete destructive power, you might also want to kill the session cookie:
setcookie(session_name(), '', 1);
See this question for a more complete example of session logout.
You need to unset $_SESSION['logged']
Also you should reference keys in the $row variable with strings. Eg $row['username'];.
Turning on E_NOTICE level warnings with error_reporting will help you with this.
If you haven't already, reset the session login
unset($_SESSION['logged']);
Or just change it to false
$_SESSION['logged'] = false;
When you are directly hitting a page in address bar for the first time then its a new request which goes to the server and server checks for existing session as written in your code. But its not same when you are pressing back button after logout. In this case there is no request is going to the server instead the request is fetched from browser cache. If you want to disable this situation then you have to tell browser explicitly to not to store your page in cache memory. For more detail please go through this link

PHP Session Security Tips

this is what I'm doing currently to create sessions on login page.
if($count==1) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
i know this is very basic and I need to protect the user sessions. Can u provide me some basic tips. If you could edit the code and write the secure one, it would be great. Thanks.
Currently, I am using the email address as session username.
Ask your self this question:
Why am I storing the password when the username is unique in the database
After you have answered that you should of come to the conclusion that its pointless, you can either store the username or the user id in the session when it comes to login systems.
How login systems tend to work is that the user sends the username password from a form to the server where its validated, during the validation process you select the user from from the database where username = post_username.
If there is no rows found the user does not exists so you can directly send output at that point, if the user does exist you then compare the password with the post_password.
the reason why we specifically select the row by just the username is that you should be incorporating some sort of hashing system to add extra security.
if you stored the password as (password + hash) which would be a new string, you would also store just the hash aswell, thus if a user is found then you can create a hash from (post_password + db_hash) and check to see if its the same as the db_password.
this way if your database gets leaked somehow your users credentials are more secure.
once the user has been validated you would store the user id within the session, and then on every page load you can check if the id is within the session and if it is the user is currently logged in and you can select the users data by SELECT * FROM users WHERE id = session_id.
This should get you started.
/*
SecureSession class
Written by Vagharshak Tozalakyan <vagh#armdex.com>
Released under GNU Public License
*/
class SecureSession {
// Include browser name in fingerprint?
var $check_browser = true;
// How many numbers from IP use in fingerprint?
var $check_ip_blocks = 0;
// Control word - any word you want.
var $secure_word = 'random_string_here';
// Regenerate session ID to prevent fixation attacks?
var $regenerate_id = true;
// Call this when init session.
function Open()
{
$_SESSION['ss_fprint'] = $this->_Fingerprint();
$this->_RegenerateId();
}
// Call this to check session.
function Check()
{
$this->_RegenerateId();
return (isset($_SESSION['ss_fprint'])
&& $_SESSION['ss_fprint'] == $this->_Fingerprint());
}
function Destroy()
{
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// Finally, destroy the session.
session_destroy();
}
// Internal function. Returns MD5 from fingerprint.
function _Fingerprint()
{
$fingerprint = $this->secure_word;
if ($this->check_browser)
$fingerprint .= $_SERVER['HTTP_USER_AGENT'];
if ($this->check_ip_blocks)
{
$num_blocks = abs(intval($this->check_ip_blocks));
if ($num_blocks > 4)
$num_blocks = 4;
$blocks = explode('.', $_SERVER['REMOTE_ADDR']);
for ($i=0; $i<$num_blocks; $i++)
{
$fingerprint .= $blocks[$i] . '.';
}
}
return md5($fingerprint);
}
// Internal function. Regenerates session ID if possible.
function _RegenerateId()
{
if ($this->regenerate_id && function_exists('session_regenerate_id'))
session_regenerate_id();
}
}
Common practice is to check the user name and password against the database, then on success store just the user id in the session. Then later, to see if a person is logged in or authorized, you check that user id stored in the session. Though, the session variables are only visible to the server unless you've done something horribly wrong. So its not horrible or insecure but its basically unnecessary.
Edit
Removed bit about cookies, could cause confusion.

how to check if a user is logged on in php. beginner

using mysql as database. I got this code from the previous answers to the same question:
session_start()):
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
Could you please explain what is: $_SESSION['loggedin'] .
Where could I define it? the loggedin, please help
http://www.php.net/manual/book.session.php
I hope it will help you ;)
$_SESSION is a super-global array (available anywhere) that store all sessions variables.
session_start(); // begins session
$_SESSION['user_id'] = 99;
So, the loggedin variable is set to true when a user logged in, and then it is stored in the session. Sessions are basically information that are saved on the server.
$_SESSION is simply a persistent container where you can store anything and retrieve it in other requests during the same session. As such, you would have to set $_SESSION['loggedin'] and $_SESSION['username'] at the point where the user has successfully logged in.
You use sessions to store userdata to pass it between all pages that get loaded. You can define it as said by others by using the $_SESSION['sessionname'] var.
I will post a simple script below how to let people login on the website since you wanted to know how to use it:
session_start(); #session start alwas needs to come first
//Lets make sure scriptkiddies stay out
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
//Read the user from the database with there credentials
$query = mysql_query("select id from user where username = $username and password = $password");
//Lets check if there is any match
if(mysql_num_rows($query) > 0)
{
//if there is a match lets make the sessions to let the user login
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
}
This is a simple script how to use a Session for a login system. There are many other ways you can use sessions
After login:
$_SESSION['loggedin'] = true;
That's it.

Categories