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 ---
}
Related
From index.php I get the values of the username and password fileds with $_POST
index.php
if(isset($_POST["username"]) && isset($_POST["password"])){
$username = mysql_real_escape_string(strtolower($_POST['username']));
$password = mysql_real_escape_string($_POST['password']);
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
checkUser($_SESSION['username'], $_SESSION['password']);
}
Then I store these $username and $password variables inside the $_SESSION and call a function checkUser($_SESSION['username'], $_SESSION['password'])); which sends two parameters. The checkUser() function executes inside lib.php
lib.php
session_start();
function checkUser($username, $password){
include "connection.php";
$result = mysqli_query($conn, "SELECT * FROM `data` WHERE `username` = '$username' AND `password` = '$password'") or die("No result".mysqli_error());
$row = mysqli_fetch_array($result);
$logic = false;
if (($row['username'] == $username) && ($row['password'] == $password)) {
$logic = true;
echo "HI,".$username;
?>
<a href='logout.php'>Log Out</a>
<?php
$file = $row['file'];
echo "<img src='images/users/".$file."' >";
}
else{
echo "Failed to login. Username or password is incorrect. Try again.";
}
}
This part is for showing the name of the user and the image according to it.
logout.php works
logout.php
unset($_SESSION["username"]);
unset($_SESSION["password"]);
unset($_SESSION["file"]);
header("Location: index.php");
session_destroy();
The problem is when I navigate from one page to another, the $_SESSION variable becomes empty. Something is wrong with session. Please help me.
in the php pages you need to access session variable add session_start() after the starting <?php code
I have this code, it was originally in mysql() but since it's deprecated and obsolete well i decided to change. Something is clearly not working because when I execute it always says incorrect password/username although it is correct. Database works. Triple checked. Pardon me, i'm a noob at php. here:
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
?>
<div class="alert alert-info">You have been logged out securely.</div>
<?php
}
else
{
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$escapePass = stripslashes($_POST['username']);
$escapeUser = $_POST['username'];
$ousername = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($link, $escapePass);
$password = sha1(stripslashes($_POST['password']));
}
else
{
$username = mysqli_real_escape_string($link, $escapeUser);
$password = sha1($_POST['password']);
}
//We get the password of the user
$query = 'SELECT password, id FROM users WHERE username="'.$username.'" ';
$req = mysqli_query($link, $query);
$dn = mysqli_fetch_array($req);
print $reg;
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysqli_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
#Fred -ii- This:
if(get_magic_quotes_gpc())
{
$escapePass = stripslashes($_POST['username']);
$escapeUser = $_POST['username'];
$passescape = sha1($_POST['password']);
$passescape2 = sha1(stripslashes($_POST['password']));
$ousername = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($link, $escapePass);
$password = mysqli_real_escape_string($link, $passescape2);
}
else
{
$username = mysqli_real_escape_string($link, $escapeUser);
$password = mysqli_real_escape_string($link, $passescape);
}
Just for a quick testing purpose, try this below which is a bare bones method.
You can then slowly build up sanitizing and troubleshoot from thereon.
<?php
$username = $_POST['username'];
$password = sha1($_POST['password']);
$link = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT password, id FROM users
WHERE username = '$username' AND password='$password'";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) < 1)
{
echo 'Sorry, your username and/or password was incorrect.';
}
else
{
echo "Welcome!";
}
?>
Footnote: I noticed in your original code that you are using sessions.
I did not see session_start(); in your code, nor any mention of it.
This needs to be at the top of your code and inside all your files used,
which will be needed in order to access anything currently in $_SESSION
More on sessions can be found on the PHP.net Website.
http://www.php.net/session_start
I am trying to pass a session variable from the log in script to display a Welcome [Username] massage, at the moment its not passing it through - any ideas? I am quite new to PHP so all your comments are greatly appreciated.
The code is as follows.
<?php
ob_start(); // Start output buffering
session_start(); //must call session_start before using any $_SESSION variables
$_SESSION['username'] = $username;
function validateUser()
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';
//connect to the database here
$hostname_PropSuite = "localhost";
$database_PropSuite = "propsuite";
$username_PropSuite = "root";
$password_PropSuite = "root";
$PropSuite = mysql_pconnect($hostname_PropSuite, $username_PropSuite, $password_PropSuite) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_PropSuite, $PropSuite);
$username = mysql_real_escape_string($username);
$query = "SELECT password, salt FROM admin_users WHERE username = '$username';";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: http://localhost/PropSuite/index.php?login=fail');
die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
header('Location: http://localhost/PropSuite/index.php?login=fail');
die();
}
else
{
validateUser(); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: http://localhost/PropSuite/main');
die();
//redirect to another page or display "login success" message
?>
Add username as parameter in the function
function validateUser($username)
{
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
And pass it when you call it
validateUser($username); //sets the session data for this user
I think that your problem is that you are using $_SESSION['username'] = $username; before $username is defined. $username = isset($_POST['username'])?$_POST['username']:''; needs to be above $_SESSION['username'] = $username;.
To access a variable declared in the global scope, from within a function, you have to use global keyword, like so:
function validateUser()
{
global $username;//NEEDED to access $username declared in global scope
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
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();}
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');
}