PHP - User not staying logged in - php

I've finally got the courage to make a user login system after who knows how long of putting it off. My only problem is that when I submit the login form it reloads the page and it says that I am logged in, great.
However if I reload the page or go to another page and come back to the original page it forces me to login again. Can anyone help with this? I have a session_start() in the base file that is included in all other page files before the database connection.
I then have the following code for my user login side of things, which as I said, works the first time around, but after that any other interaction will essentially log me out. Any help with this?
The user page which logs you in and creates the session...
Please note that this isn't a live environment so security is being put on the bench for now. However I am aware I will need some security measures in place in the future though.
// Check if the user is logged in or not
if((!empty($_SESSION['loggedin'])) && (!empty($_SESSION['username']))) {
$loggedin = true; // The user IS logged in
} else {
if(isset($_POST['login'])) {
// The login form has been submitted
if((empty($_POST['username'])) || (empty($_POST['password']))) {
// If either username or password fields are blank
$loginfail = true; // If the user could not be logged in
if(empty($_POST['username'])) { $nousername = true; }
if(empty($_POST['password'])) { $nopassword = true; }
} else {
// Username and password field were filled in okay
$username = $_POST['username'];
$password = $_POST['password'];
$checklogin = mysqli_query($sql, "SELECT * FROM users WHERE username = '$username' AND password = '$password'") or die($checklogin . "<br/>" . mysqli_error($sql));
if(mysqli_num_rows($checklogin) == 1) {
// If the login details match up, log them in
$loggedin = true; // The user IS NOT logged in
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = 1;
} else {
// If the login details don't match up, don't login
$loginfail = true; // If the user could not be logged in
}
}
}
}
Thanks!

Related

Log In Form Is Forwarding To Database Connection Page. Not Sure Why. It's Supposed To Be Redirecting To Index2.php

I have this form programmed to log a user in. I have confirmed that it does in fact set a session for a user, but for some reason, it forwards the user to the page to connect to the database. I have this page linked in the code because I obviously need to consult the database to confirm the user has an account, but I don't understand why it goes to this page and then just stays there. Help would be appreciated. Index2.php (set as that right now so users won't see it when they go to the site) is supposed to be set as the redirected page after login. The user is supposed to be able to see the homepage even without logging in, but certain content only appears in the user is logged in.
<?php
session_start();
include("db_connect.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//something was posted
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && !empty($password))
{
//read from database
$query = "select * from users_listers where email = '$email' limit 1";
$result = mysqli_query($conn, $query);
if($result)
{
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['password'] === $password)
{
$_SESSION['user_lister_id'];
header("Location: ../index2.php");
die;
}
}
}
echo "wrong username or password!";
}else
{
echo "wrong username or password!";
}
}
?>
Thank you for the help!

what is the purpose of using of "$_SESSION['authuser'] = 1" in php, why we use 1 in this section

actually, i could not understand why do we use "$_SESSION['authuser'] = 1;" in php code, my code as below
<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 1;
//Check username and password information
if(($_SESSION['username'] == 'joe') and
($_SESSION['userpass'] == '123')) {
$_SESSION['authuser'] = 1;
}
else
{
echo 'Sorry, but you don\'t have permission to view this page!';
exit();
}
?>
Because session (and cookie) support needs it due to a many reasons.
Ie, otherwise it would be required for you (and your visitors) to enter username and password every single time when you CLICK on an any link of your page.
<?php
session_start();
$_SESSION['username'] = $_POST['user'];
$_SESSION['userpass'] = $_POST['pass'];
$_SESSION['authuser'] = 0; // user is not authenticated (just a GUEST), default is 0...
// if visitor is priviledged, show him in, let him see the page
if(($_SESSION['username'] == 'joe') and
($_SESSION['userpass'] == '123')) {
$_SESSION['authuser'] = 1; // insert 1 into DB and set cookie as 1 for user not to enter username and pswd anymore during browsing
}
else
{
//else, keep guest away from a page
echo 'Sorry, but you don\'t have permission to view this page!';
exit(); // shut down
}
?>
In your case the usage of SESSION for username and userpass seems to be redundant. This could be possible.
<?php
session_start();
/*Do not set sessions for username and userpass, only use them in the POST array
*Initialize authuser to 0 because by default a user is not logged in
*/
$_SESSION['authuser'] = 0;
//Check username and password information
if(($_POST['user'] == 'joe') and
($_POST['pass'] == '123')) { //Check the user and set it as authenticated
$_SESSION['authuser'] = 1;
} else { //If the user is not valid, stop execution
echo 'Sorry, but you don\'t have permission to view this page!';
exit();
}
?>
What I'm doing here is:
Starting session
Initializing user as not authenticated (this is optional)
Checking username and password
If they are valid, setting user as authenticated
If not, stopping execution.
Note that it could be useful to set a session for username and password once user is authenticated, instead of only remember the user is logged.

php how to redirect user to index.html when sucessfully logging in

hi i am having problems with a login script for my website i need the script to redrect the user to index.html if the login details are correct. if you could help me at all it would be greatly appreciated.. thank you...
here is my script for checking the details ==>
<?php
include('config.php');
?>
$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())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_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'];
?>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
any help would be greatly appreciated.. thank you.
UPDATE: As #Dagon corrected me..
To redirect user back to index.html, you can use the following:
header('Location: http://example.com/index.html');
exit;
after successful login.
So your source code is not preferly the best to this way of login, but even in this way you should make a redirection after login.
It you can do with JavaScript, exactly i recomend you tu use jQuery API, which will help you to improve many things on your site.
So in your situation i recomend you this way of solution:
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
}
So if you noticed, this line
echo "<script>$('#idofelement2reload').load('php.php?login=1');</script>";
writes a line into html document which call a function to load through jQuery a file with parameter that the user is logged in.
Don`t forget to include jQueries source code in head
Use the header() function after setting the user information in $_SESSION.
// If the password is good, we don't 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'];
header('Location: http://example.com/index.html');
if($dn['password']==$password and mysql_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'];
header('Location:http://sitename.com/index.php');
?>

Login php code, different content for admin/user:

Can you please help me to figure out how shall I use this if statement to show different content to different type of users.
this is the code that I have already found on another question:
if($_SESSION['usertype'] == 2){ //do stuff here} if ($_SESSION['usertype']) == 1) { //do stuff here }
I want to use this on a page where only members can view the page, and depending on the usertype, it should show different content.
But I'm not able to send the usertype in the login page when a user logs in, this is the code used there (login.php):
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This variable will be used to re-display the user's username to them in the
// login form if they fail to enter the correct password. It is initialized here
// to an empty value, which will be shown if the user has not submitted the form.
$submitted_username = '';
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST))
{
// This query retreives the user's information from the database using
// their username.
$query = "
SELECT
id,
username,
password,
salt,
email
usertype
FROM users
WHERE
username = :username
";
// The parameter values
$query_params = array(
':username' => $_POST['username']
);
try
{
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the username
// they entered is not registered.
$row = $stmt->fetch();
if($row)
{
// Using the password submitted by the user and the salt stored in the database,
// we now check to see whether the passwords match by hashing the submitted password
// and comparing it to the hashed version already stored in the database.
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok)
{
// Here I am preparing to store the $row array into the $_SESSION by
// removing the salt and password values from it. Although $_SESSION is
// stored on the server-side, there is no reason to store sensitive values
// in it unless you have to. Thus, it is best practice to remove these
// sensitive values first.
unset($row['salt']);
unset($row['password']);
// This stores the user's data into the session at the index 'user'.
// We will check this index on the private members-only page to determine whether
// or not the user is logged in. We can also use it to retrieve
// the user's details.
$_SESSION['user'] = $row;
$_SESSION['usertype'] = $row;
// Redirect the user to the private members-only page.
header("Location: dashboard.php");
die("Redirecting to: dashboard.php");
}
else
{
// Tell the user they failed
print("Login Failed.");
// Show them their username again so all they have to do is enter a new
// password. The use of htmlentities prevents XSS attacks. You should
// always use htmlentities on user submitted values before displaying them
// to any users (including the user that submitted them). For more information:
// http://en.wikipedia.org/wiki/XSS_attack
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
What changes do I need to make in this code?
I am quite new to all this, any help is appreciated.
You need to edit the last bit of your if($login_ok) section to set the $_SESSION variables correctly:
if($login_ok)
{
...
$_SESSION['user'] = $row['username'];
$_SESSION['usertype'] = $row['usertype'];
...
}
From what I can see in your code, if the rest of it works correctly then the dashboard.php page should be able to access it like this:
<?php
require("common.php");
if($_SESSION['usertype'] == 2) {
//do stuff here
} elseif($_SESSION['usertype']) == 1) {
//do stuff here
}
?>

Login form always takes more then one try

I have a slight problem with my log in script in PHP. When a user logs in, it only works after the second try, there is no error but it just looks like the user entered the wrong password on the first attempt.
Sometimes when I've been testing the site, after i try log in in the first time it sends me back to the log in page. Then I manually enter the url of the home page it will let me go there sometimes. (There's some php at the top that checks if the user is logged in already so im guessing sometimes the log in script sets the SESSION to true)
Majority of the time it doesn't do that though. It will just redirect me back to the log in with out printing the error message. I believe the problem is at the top of the home page and not with the log in script because after removing the redirect if mysql doesn't return a row with a user/password match it will direct me to the log in page anyways.
Here is my login script
<?php
session_start();
// Include required MySQL configuration file and functions
// Check if user is already logged in
if (isset($_SESSION['logged_in'])) {
// If user is already logged in, redirect to main page
redirect('home.php');
}
else {
// Make sure that the user submitted a username/password and username
// only consists of alphanumeric Chars
if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR
( !ctype_alnum($_POST['username'])) ) {
redirect('login.php');
}
// Connect to database
$mysqli = #new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) { printf ("Unable to connect to database %s",
mysqli_connect_error());
exit();
}
//Escape any unsafe characters before querying database
$username = $mysqli->real_escape_string($_POST['username']);
$password = $mysqli->real_escape_string($_POST['password']);
// construct SQL statement for query & execute
$sql = "SELECT * FROM peeps WHERE name = '" . $username . "'
AND pword = SHA1('" . $password . "') ";
$result = $mysqli->query($sql);
// If one row is returned, username and password are valid.
if ($result->num_rows == 1 ) {
// Set the session variable for login status to true
$_SESSION['logged_in'] = true;
$_SESSION['name'] = $username;
echo "successfull ";
redirect('home.php');
}
else {
echo "didnt return row<hr>";
redirect back to login page.
redirect('loginPage.php');
}
}
?>
And here is the code at the top of my home page..
<?php
// Start session
session_start();
// Include required functions file
require_once('functions.php');
// Check login status... if not logged in redirect to login screen
if (check_login_status() == false) {
redirect('loginPage.php');
}
$username = $_SESSION['name'];
?>
Any help would be appreciated, if you want to a little more clarification on what I mean you can sign up for gateKeeper and see what I'm talking about.
Also this is my first question so any comments on how I asked it would be appreciated.
Thanks!
Try debugging it by replacing
if (check_login_status() == false) {
redirect('loginPage.php');
}
with
if (!isset($_SESSION['name'])) { #could be any session variables that you like..
redirect('loginPage.php');
}
or do print_r($_SESSION) on top of your homepage.
I assume that the first page is the script that processes the form from loginPage.php (or loginPage.php itself) and the second one the page that you access after being authenticated.
If I'm not mistaken, the problem seems to be that sometimes you are not correctly identified and that's redirecting you to your login again. Can you show us how the code for the check_login_status() function?

Categories