php sessions to authenticate user on login form - php

I have the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
NOTE the authed function worked fine before i added the session code.

what about using this to setup session
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");

First, don't store the password in the session. It's a bad thing. Second, don't store the username in the session until after you have authenticated.
Try the following:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}

Just some random points, even though they may not actually pertain to the problem:
Don't store the password in plaintext in the session. Only evaluate if the password is okay, then store loggedIn = true or something like that in the session.
Check if the password and the username are $_POSTed, not || (or).
Don't pass password and username back and forth between $password and $_SESSION['password']. Decide on one place to keep the data and leave it there.
Did you check if you can store anything at all in the session? Cookies okay etc...?
To greatly simplify your code, isn't this all you need to do?
if (isset($_POST['username'] && isset($_POST['password'])) {
if (auth($_POST['username'], $_POST['password'])) {
$_SESSION['user'] = /* userid or name or token or something */;
header(/* to next page */);
} else {
// display "User credentials incorrect", stay on login form
}
} else {
// optionally: display "please fill out all fields"
}

Here are a few other things, which may or may not help you, by the way :
Do you have error_reporting on ? (see also)
Do you have display_errors on ?
Is session_start the first thing you are doing in your page ? There must be nothing output before
Are the cookies created on the client-side ?
header Location indicates the browser it has to go to another page ; it doesn't stop the execution of the PHP script. You might want to (almost always anyway) add "exit" after it.

Headers are not function calls. They put a directive into the HTTP headers, and the last one to execute is the one which will be processed. So let say if you have something like this
if ($bAuthed)
{
header("location: login.php");
}
// error case
header("location: error-login.php");
You will always be redirected to error-login.php no matter what happens. Headers are not function calls!

The solution to my specific problem above
session_start();
if(isset($_POST['username']) || isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
} else {
header('Location:http://website.com/fail.php');
}

Don't use else section in second if statement.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}

Related

session value lost after redirection in php

PHP session value lost after header redirection in php
Our code
Login.php
<?php
session_start();
include('./includes/variables.php');
include_once('includes/custom-functions.php');
$fn = new custom_functions;
if (isset($_POST['btnLogin'])) {
// get username and password
$username = $db->escapeString($fn->xss_clean($_POST['username']));
$password = $db->escapeString($fn->xss_clean($_POST['password']));
// set time for session timeout
$currentTime = time() + 25200;
$expired = 3600;
// create array variable to handle error
$error = array();
// check whether $username is empty or not
if (empty($username)) {
$error['username'] = "*Username should be filled.";
}
// check whether $password is empty or not
if (empty($password)) {
$error['password'] = "*Password should be filled.";
}
// if username and password is not empty, check in database
if (!empty($username) && !empty($password)) {
// change username to lowercase
$username = strtolower($username);
//encript password to sha256
//$password = md5($password);
// get data from user table
$sql_query = "SELECT * FROM admin WHERE username = '" . $username . "' AND password = '" . $password . "'";
$db->sql($sql_query);
/* store result */
$res = $db->getResult();
// print_r($res);
// die();
$num = $db->numRows($res);
// Close statement object
if ($num == 1) {
$_SESSION['id'] = $res[0]['id'];
$_SESSION['role'] = $res[0]['role'];
$_SESSION['user'] = $username;
$_SESSION['timeout'] = $currentTime + $expired;
//print_r($_SESSION);
//die();
header("location: home.php");
exit();
} else {
$error['failed'] = "<span class='label label-danger'>Invalid Username or Password!</span>";
}
}
}
?>
Home.php
<?php session_start();
print_r($_SESSION);
?>
Output :
array()
We tried the following method
Made sure session_start(); is called before any sessions are
being called
After the header redirect, end the current script using exit();
Made sure cookies are enabled in the browser we were using to test
it on.
Made sure didn't delete or empty the session
Made sure file extension is .php
You have to include you file in which you have initialized session
For example
first file named phpcodeonly.php:
session_start() //put it in start
if(login success){
$_SESSION['email']= $email
}
your other file.php:
include 'phpcodeonly.php'; //on top
<h1> Welcome <?php echo $_SESSION['email']?> </h1>

PHP can't determine whether user is logged in or not

I'm creating a system that the header will show 'login' if the user is not logged in, and if they are, it'll display logout. I've simplified it for now, just showing if the user is logged in or not. With "Login!" meaning they need to login, and "Welcome!" if they are logged in. I used the PHP Code Checker website (https://phpcodechecker.com/) and it couldn't find any errors. I also searched stackoverflow, and everyone else's seems to work.
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
if( !isset($_SESSION['user']) ) {
echo "Login!";
} else {
echo "Welcome!";
}
?>
is the code that checks if the user is logged in or not.
My login page works for EVERYTHING else, for my homepage is shows that the user is logged in, but here is the code anyway. (This is only the PHP code, there is HTML for the submit button, ect.)
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// it will never let you open index(login) page if session is set
if ( isset($_SESSION['user'])!="" ) {
header("Location: index.php");
exit;
}
$error = false;
if( isset($_POST['btn-login']) ) {
// prevent sql injections/ clear user invalid inputs
$email = trim($_POST['email']);
$email = strip_tags($email);
$email = htmlspecialchars($email);
$name = trim($_POST['name']);
$name = strip_tags($name);
$name = htmlspecialchars($name);
$pass = trim($_POST['pass']);
$pass = strip_tags($pass);
$pass = htmlspecialchars($pass);
// prevent sql injections / clear user invalid inputs
if(empty($name)){
$error = true;
$nameError = "Please enter your username.";
}
if(empty($pass)){
$error = true;
$passError = "Please enter your password.";
}
// if there's no error, continue to login
if (!$error) {
$password = hash('sha256', $pass); // password hashing using SHA256
$res=mysql_query("SELECT userId, userEmail, userPass FROM users WHERE
userName='$name'");
$row=mysql_fetch_array($res);
$count = mysql_num_rows($res); // if email/pass correct it returns must be
1 row
if( $count == 1 && $row['userPass']==$password ) {
$_SESSION['user'] = $row['userId'];
header("Location: dashboard.php");
} else {
$errMSG = "Incorrect Credentials, Try again...";
}
}
}
?>
It connects to the database fine, and i'm certain there is no problems with the database, since it works on my other pages.
I've spent a long-while trying to figure this out, and can't.
Thanks!
In your code
if ( isset($_SESSION['user'])!="" ) {
you are comparing true|false != ""
change it to if (isset($_SESSION['user'])) {
or
if (isset($_SESSION['user']) && ($_SESSION['user']!="")) {

Using Session and Cookies together for remember me

In my login page I am using Session and Cookies both, session for usual login and cookies when remember me is checked. My code for creating session or setting cookies is:
if(isset($_POST['login'])){
$username = $_POST['user_login'];
$password = $_POST['password_login'];
$stmt = $db->prepare("SELECT * FROM userss WHERE username = :username AND password = :password");
$stmt->execute(array(':username'=>$username,':password'=>$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$user_db = $row['username'];
$pass_db = $row['password'];
if($username == $user_db && $password == $pass_db) {
$_SESSION['username']=$username;
if ($_POST['rememberme']!=NULL) {
setcookie('username', $username,time()+31556926);
}
header("Location:main.php");
}
and then on any page to create a user fuction I am calling session or cookie like this:
if(isset($_COOKIE['username'])||isset($_SESSION['username'])) {
$username = $_COOKIE['username'];
$username = $_SESSION['username'];
}
Now my problem is:
Even when remember me is checked session is used and not cookies I tested it by exiting my browser. I can't figure out where code has gone wrong.
In the second code if(isset($_COOKIE['username'])||isset($_SESSION['username'])) { is correct but I am not sure how to define username for both different situations also
$username = $_COOKIE['username']; is giving me undefined index username. May be my way of setting cookies has gone wrong.
Replace here
if (isset($_POST['rememberme'])) {
setcookie('username', $username,time()+31556926);
}
And in user functions
if(isset($_SESSION['username']) {
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username']){
$username = $_COOKIE['username'];
}
else
{
//invalid ---
}

PHP Session for login - doesn't recognise

I'm writing a login code for my control panel for my website. I've made the login script. But for some reason the session doesn't save, here is the parts of my code I use:
index.php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) {
require('scripts/validateLogin.php');
}
if($_SESSION['login'] == 1) {
$loginOkay=1;
echo "Logged in";
} else {
$loginOkay=0;
echo "Not logged in";
}
validateLogin.php
require('mysql_connect.php');
$username = htmlspecialchars(strtolower($_POST['username']));
$password = md5(htmlspecialchars($_POST['password']));
$result = mysqli_query($con, "SELECT username,password FROM tb_mods WHERE username = '$username';");
while($row = mysqli_fetch_array($result)) {
if ($row['username'] == $username && $row['password'] == $password) {
$_SESSION['login'] == 1;
}
}
I call session_start(); before I load my loginValidation.php so session_start(); is active in both pages.
I keep getting: Not logged in as result.
I think the line $_SESSION['login'] == 1; is wrong, you need only one equal character to add value to the session variable. I hope it will help.

Is $_SERVER[HTTP_HOST] the cause of redirect issues?

I have enabled vanity urls (user.domain.com). When a session expires or somebody clears the cookies, the page would get redirected to user.domain.com which has the login page. So, on all pages i am using the following code:
if(!isset($_SESSION['user_name'])) { header("Location: http://$_SERVER[HTTP_HOST]");}
2 of of 10 times i get a redirect error saying that the page is redirecting too many times.
Could this be the reason? And if it is what can i do to redirect in a way that won't cause such issues.
Thanks.
Login code:
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugData = $_REQUEST['sub_name'];
if($_POST){
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password FROM accounts WHERE user_name = '$username' and sub_name='$ugData'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password']) {
die('You did not fill in a required field.');
}
// checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password FROM accounts
WHERE user_name = '".$_POST['user_name']."'
and sub_name='".$ugData."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database.
<a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password']) {
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
?>
The header("Location: http://{$_SERVER['HTTP_HOST']}"); isn't the problem per-say.
However, if you do have that code on your login page then yes, you'll just keep redirecting yourself to the home page because you won't be able to login.
Make sure that you do not redirect the user if he's on the login page.
EDIT: Try header('Location: /'); Maybe you have some weird server issue which causes $_SERVER['HTTP_HOST'] do sometimes be null.
Assuming that redirecting to http://yourserver/ means http://yourserver/index.php, then you should change the if to read
if(!isset($_SESSION['user_name']) && $_SERVER['PHP_SELF'] != '/index.php')
{
header("Location: http://$_SERVER[HTTP_HOST]");
}
This will avoid endless redirects.
Try using this with a die():
if(!isset($_SESSION['user_name'])) { header("Location: http://user.domain.com"); die();}
If url changes from user to user grab username from db first, and use it in redirection. Try something like:
...
$username = $row["username"];
...
and use it:
if(!isset($_SESSION['user_name'])) { header("Location: http://".$username.".domain.com"); die();}

Categories