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

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.

Related

Recalling Session When Browser is closed with Cookies

On login I'm creating the following cookies based on a Remember Me checkbox:
$_SESSION['username'] = $username;
//creates a cookie if Remember Me is checked
if(isset($_POST['remember'])){
$expire_time = time()+86400;
setcookie("lion123_rmbr", $email, $expire_time);
setcookie("lion123_rmbr_usrnm", $username, $expire_time);
}
Just above I have the session being created on just the login.
The idea of course is to be able to close the browser, re-open and be able to access the members area without having to login. In header.php I have the following recall:
if (isset($_SESSION['username']) || isset($_COOKIE['lion123_rmbr']) || isset($_COOKIE['lion123_rmbr_usrnm'])) {
$userLoggedIn = $_SESSION['username'];
$user_details_query = mysqli_query($con, "SELECT * FROM users WHERE username='$userLoggedIn'");
$user = mysqli_fetch_array($user_details_query);
}
else{
header("Location: register.php");
}
When I open and close the browser, then navigate to members area, the cookies allow for me to do this; however, the user specific data is missing because $_SESSION['username'] = $username; is not being set on login & of course being terminated once the browser is closed. So I'm getting the error that username is not defined.
I thought that adding the second cookie for username might be the fix...nope :) Any help on how to activate a user session would be appreciated - if the only way the session is created is through login, how can this data be passed to activate $userLoggedIn?
Thankyou.

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 - 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

Keep a given ID in URL upon successful login

if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
$goHere = 'Location: /index2.php?id=' . $id;
header($goHere);
exit;
}
I have the following code that once logged in, it $_GET the id and prepends to the url like index2.php?id=5 . How do I keep this id=5 in the URL no matter WHAT link they click on??
This id is grabbed from this:
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
What I want to do
Well way i have it setup, you login, it then sends you to the homepage such as index2.php?id=[someint] , if you click another link say 'prof.php', it removes the id=[someint] part, I want to keep it there in the url, so as long as a user is LOGGED in -- using my code above, the url might read: index.php?id=5, then go to another page it might read prof.php?id=5, etc, etc. This integer would obviously be dynamic depending on WHO logged in
Instead of passing around an ID in the URL, consider referring to the id value in the $_SESSION variable. That way the user can't modify the URL and see data they aren't supposed to see (or much worse), and you don't have to worry over appending it to every URL and reading it into a value every time you go to process a script. When the user logs in, you determine their ID - read it from a database, determine it realtime, whatever. Then store it in the $_SESSION and refer to it as needed. You can even use this as part of a check to see if the user is logged in - if they have no $_SESSION['id'] value, something is wrong and you make them log in.
The query string isn't the place for that, for a whole host of reasons. The most obvious one is that I can log in with a valid account, then change the number in the URL and it'll think I'm someone else.
Instead, just continue using the session as it's the proper way.
If you REALLY want to do it, you'd probably want to write a custom function for generating links
function makeLink ($link, $queryString = '')
{
return $link . '?id=' . (int) $_SESSION['id'] . ((strpos($queryString, '?') === 0) ? substr($queryString, 1) : $queryString);
}
called like
Click me
As a basic auth example using the ID...
<?php
// Session start and so on here
if (!isset($_SESSION['id']))
{
// Not logged in
header('Location: /login.php');
exit;
}
http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ is a pretty straightforward full example of it.

PHP Session Management - Basics

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.

Categories