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
Related
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.
I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>
Thank you in advance for any one who comes in to my rescue
Case:
I have a login page that users for my system use to login, after loginnng in, they are entitled to an idle moment for about 10 minutes, after that they are redirected to the login page again to enter their details.
Needed:
Am trying to implement a redirect to the other page which is the lock page where the user will only enter password without entering his username but this is really giving me headache because when the session is destroyed, the user's credentials are all cleared hence requiring him/her to enter both the username and password. Is there any way i can store the user's username when the session is timed out so that its echoed in a hidden field on the lock screen.
Am trying to implement this with php
Login.php
//On Load
<?php if(isset($_SESSION['UserName'])) { ?> <style> username { display:none; } </style> <script> docuemnt.GetElementById("username").value = <?php echo $_SESSION['UserName']; ?> </script <?php
//After Login
$_SESSION['UserName'] = $username;
$_SESSION['Login'] = 'True';
$_SESSION['Time'] = time();
Make in every page this code
$time = $_SESSION['Time'];
$time_check=$time-600;
if($time<$time_check) {
$_SESSION['login'] = 'False';
header(location:login.php);
You can Do it by adding username in url and extract that on that page using $_GET variable.Before destroying session store the username from session variable to another and put that in url.
let me correct you here dude,
working version:
$time = $_SESSION["time"];
$time_check = $time + 5;
if(time() > $time_check)
{
$_SESSION["logged"] = "False";
header("Refresh: 1; url=lockscreen.php");
}
and you forgot the "" in header
Don't destroy the session, just unset the userdata you need but not the username.
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.
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.