PHP Session Variable gets lost between pages. - php

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.

Related

PHP wont redirect from log-in form

I am making an html login page which will submit a form to a php page to check to see if user details lie in an established username access database.
If the username and password correspond to a row in the database, the php redirects to an mainpage (mainpage.html), otherwise it redirects back to the login page (LOGINPAGE.html).
The if function I have used to achieve this in my php script is as follows:
if(odbc_fetch_row($DetailCheckExec)) //If username corresponds with password
header('Location: mainpage.html');
else
header('Location: LOGINPAGE.html');
The problem is, the php doesn't seem to redirect. Even if I simplify my code to simply redirect, nothing changes. i.e.
<?php
header("Location: LOGINPAGE.html");
exit;
?>
won't work either.
Any help is appreciated thank you.
well i dont know the function "(odbc_fetch_row($DetailCheckExec)" but there's a step by step login that I made i hope it works
if ((isset($_POST['user'])) and (isset($_POST['password'])))
{//checks if the inputs in the form are empty
//sets two variables with the value of the imputs
$usuario = $_POST['user'];
$clave = $_POST['password'];
//then selects the row where the values are equal in the database
$consulta = "SELECT usuario, contrasena FROM `usuarios`
WHERE usuario = '$usuario' and contrasena = '$clave'";
$resultados=mysqli_query($con,$consulta);
while(($fila=mysqli_fetch_array($resultados))){
$vpeso = $fila['peso'];
$vestatura = $fila['estatura'];
$vusuario = $fila['usuario'];
}
if(($resultados) AND ((isset($vusuario)) and ($vusuario <> '') )){
//starts session
session_start();
//stablishes the user in the session
$_SESSION['usuario'] = $usuario;
//if the user doesn't exist it will bring to signup.php for example
}else{
header("Location: signup.php");
}
}
well I hope it works, sorry for not changing the variable names haha

php session issue either too many loops or doesn't work [duplicate]

This question already has answers here:
Variable errors in session for admin pages
(2 answers)
Closed 7 years ago.
Login script which I know needs some security which I will do once it works, I can log in until I add session info to top of admin pages then either shows login.php or get browser error too many redirect loops.
loginrequiredb.php is this file name
<?php
//calling connection to database
include "connection.php";
//start session
//session_start();
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0)
{
//create session named username that is equal to content of $user
$_SESSION['user']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
session for top of admin pages with lots of commenting out as tried more times than can count!
adminmain.php is this file name
<?php
session_start();
include 'includes/loginrequiredb.php';
if(!isset($_SESSION['user'])==' '){
header("location: login.php");
//}else {
//session_destroy();
//header("location: adminmain.php");
//die();
}
?>
This statement will never work.
You're checking if 'user' exists in $_SESSION (true or false) == ' '. True or false will never == ' ' and therefore you will always redirect to your other script.
if(!isset($_SESSION['user'])==' '){
Change it to:
if(!isset($_SESSION['user'])){
The general workflow should be something like this:
User hits login page
User submits credentials -> Posts to self
Login page detects credentials were entered and validates them
Valid credentials send the user to the "admin" script (and credentials need to be revalidated with every call)
Invalid credentials sends the user back to the login page.

Redirect to either login page or lock page on session time

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.

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