PHP not setting cookies but does set sessions - php

I have made a login that works for sessiosn but not cookies.. here is my login.php code
<?php
include 'functions.php';
if(loggedin()){
header("Location: index.php");
exit();
}
if(isset($_POST['login'])){
$username=$_POST['username'];
$password=$_POST['password'];
if(isset($_POST['rememberme'])) {
$rem=$_POST['rememberme'];
} else { $rememberme=""; }
if($username&&$password){
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
while($row = mysql_fetch_assoc($login)){
$db_password = $row['password'];
if($password == $db_password){
$loginok= TRUE;
}
else{
$loginok= FALSE;
}
if($loginok==TRUE)
{
if($rememberme=="on"){
setcookie("username",$username, time() + 7200);
}else if ($rememberme==""){
$_SESSION['username'] = $username;}
header("Location: index.php");
exit();
}
else
die("Incorrect Username/Password");
}
}
else
die("Please enter a username and password");
}
and my functions.php
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$db = "loginphp";
mysql_connect($host, $user, $pass) or die("Couldn't connect");
mysql_select_db($db);
function loggedin()
{
if(isset($_SESSION['username'])||(isset($_COOKIE['username'])))
{
$loggedin = TRUE;
return $loggedin;
}
}
but when I close the broswer the cookie does not save and it acts as if i've logged out completely.
sessions work fine..
here is my logout.php as well
session_start();
session_destroy();
setcookie("username","",time() - 7200);
header("Location: login.php");

I changed the format for your cookie to allow it to live for 30 days, no matter what you should always verify data in set duration of time. You assigned the $_POST to $rem not $rememberme so I corrected your function:
if($loginok==TRUE)
{
if($rem=="on"){
setcookie('username', $username, time() + (60 * 60 * 24 * 30)); // expires in 30 days
}else if ($rem==""){
$_SESSION['username'] = $username;}
header("Location: index.php");
exit();
}
I suggest you rethink how you are dealing with the remember me logins, perhaps you should come up with a hash that you can store in an encrypted format in the cookie and verify it on the server side. This "hash" should change at each visit etc.. just a recommendation.
function loggedin()
{
if(isset($_SESSION['username'])||(isset($_COOKIE['username'])))
{
$loggedin = TRUE;
return $loggedin;
}

It seems like you're setting $rem, rather then $rememberme. Change the line to:
$rememberme = $_POST['rememberme'];
Just to warn you though, with this method if someone wanted to log in, all they'd have to do is set a username in a cookie and bingo!
Have a look at the accepted answer here for a good method.
While I'm at it, you also need to protect yourself against SQL injection attacks, which your current code is open to. Look here.

Related

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 to restrict access to file

index.php
session_start();
if(isset($_POST['login'])){
$username = mysqli_real_escape_string($con,$_POST['username']);
$pass = mysqli_real_escape_string($con,$_POST['userpass']);
$sel_user = "select * from users where user_name='$username' AND user_password='$pass'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
else {
echo "<script>alert('Username or Password is not correct, please try again!')</script>";
}
}
display.php
session_start();
if(!$_SESSION['loggedIn']) {
header("location: index.php");
die();
}
Hello, I'm trying to figure out why my index.php is not letting me properly login and access my display.php The password and username is right, but keeps redirecting me to index.php Any ideas why?
Why don't you use Cookies instead?
In your login.php page instead of:
if($check_user>0) {
$_SESSION['loggedIn'] = true;
$_SESSION['user_name']=$username;
header("location:display.php");
die();
}
Do this:
if($check_user>0) {
$_SESSION['user_name']=$username;
$Month = 86400 + time();
setcookie('user', $username, $Month);
header("Location:display.php");
}
and then on your display.php
session_start();
if(!isset($_COOKIE['user']))
{
header("location:index.php");
die();
}

How to set user/admin accounts for a redirect after log in? PHP

My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.

Outputting incorrect username or password

I need help with this code to output incorrect username or password but it doesn't :(
<?php
include 'functions.php';
if(loggedin()){
header("Location: index.php");
exit();
}
if(isset($_POST['login'])){
$username=$_POST['Username'];
$password=$_POST['Password'];
if(isset($_POST['rememberme'])){
$rememberme = $_POST['rememberme'];
}
if($username&&$password){
$login = mysql_query("SELECT * FROM php_customer WHERE Username='$username'");
while($row = mysql_fetch_assoc($login)){
$db_password = $row['Password'];
if($password == $db_password){
$loginok= TRUE;
}
else{
$loginok= FALSE;
}
if($loginok==TRUE)
{
if($rememberme=="on"){
setcookie('Username',$username, time() + 7200);
}else if ($rememberme==""){
$_SESSION['Username'] = $username;}
header("Location: index.php");
exit();
}
echo "Incorrect Username or Password";
}
}
}
?>
I've tried adding it by the $loginok=false; but nothing works. I don't want you guys to go psycho on me, this is a 1 line of code kinda thing. Also yes I know you can log in if you store a username as a cookie. Just trying to validate atm.
Set your flag to false at the very beginning, before doing the SQL query:
$loginok = FALSE;
$login = mysql_query(....);
Why? Because the SQL query won't return anything for a username that doesn't exist in the table, obviously.
Which means, also, you need to make sure that the line echo "Incorrect Username or Password"; and the if-statement based on $loginok are not inside the loop which goes through the recordset, but after it. Which means you need to learn how to properly indent code so its clear where if-statements and loops begin and end.

php sessions to authenticate user on login form

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');
}

Categories