I am creating a user login system similar to a client intranat. And when I try to access the main page I get a redirect loop in FF.
I am checking to see if a user is logged in with this:
if(($_SERVER['PHP_SELF'] != '/webmaster/index.php') && ($_SESSION['loggedin'] != '1234')){
header("Location: ".$domain."index.php?l=no");
exit();
}
Below is my process-login.php -> which is the file that handles client login:
<?php
ob_start();
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL | E_NOTICE);
include ("config.inc.php");
include ("jsonEncode.php");
// username and password sent from form
$username = '';
$password = '';
$username = mysql_real_escape_string($_GET['username']);
$password = mysql_real_escape_string($_GET['password']);
$sql = "SELECT * FROM clients WHERE username='$username' AND password='$password' LIMIT 1";
//echo $sql;
$result = mysql_query($sql);
$data = mysql_fetch_array($result);
$count = mysql_num_rows($result);
if($count==1){
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$_SESSION['client_id'] = $data['c_id'];
$_SESSION['loggedin'] = "1234";
/*
echo $_SESSION['client_id'];
echo $_SESSION['password'];
echo $_SESSION['username'];
*/
echo $_SESSION['loggedin'];
// valid
$var = array('valid' => 1, 'username' => $username, 'password' => $password);
print php_json_encode($var);
}else{
// invalid
$var = array('valid' => 0, 'username' => $username, 'password' => $password);
print php_json_encode($var);
}
?>
The main index.php page has two forms one for clients and one for webmastsers, and if you are a client you are redirected to: clients/, and if you're a webmaster you're redirected to: webmaster/.
I have checked my login scripts and it is returning the right information and logging it in, but it keeps looping.
The form is submitted via ajax then returns JSON with a value of 1 being valid or 0 invalid to see if the user can continue.
If the form is submitted through AJAX are you sure that the session cookie is set accordingly? I know that Firefox will send cookie information together with asynchronous requests but are you confident that it will work the other way around?
if (($_SERVER['PHP_SELF'] != '/webmaster/index.php') &&
($_SESSION['loggedin'] != '1234')) { // I don't like this!
header("Location: ".$domain."index.php?l=no");
exit();
}
The $_SESSION['loggedin'] value would be != '1234' most of the time and this would be the case initially, you should check whether the value is undefined as well and act accordingly. What guarantees do you have right now that if the user requests index.php that $_SESSION['loggedin'] is not != '1234' if this is a new session? Otherwise you'll have a redirection loop which can be caused if the AJAX response doesn't set a session cookie accordingly, assuming you use session cookies to track user session?
Related
I am building a study planner that features just a single welcome area, after logging in. I am currently trying to obtain the user ID of the currently logged in user for use in an SQL update query in this welcome area, as well as the user’s first name for use in the welcome message.
I have tried putting $_SESSION['user_id'] = userid; and $_SESSION['user_firstname'] = firstname; after $_SESSION['login_user'] = $username; ($_SESSION['login_user'] = $username; works fine by the way) but upon logging into the page, I get these errors: Notice: Use of undefined constant userid - assumed 'userid' in C:\wamp64\www\justread\session.php on line 11 and Notice: Use of undefined constant firstname - assumed 'firstname' in C:\wamp64\www\justread\session.php on line 12.
Now, I know the errors want me to do some sort of initialisation for ‘userid’ and ‘firstname’ first before using them to set up a session variable but I am not sure how to go about it, so I am wondering if someone could help me, please.
Thanking you in advance.
I can post more codes if required but the codes I believe are concerned are:
login.php:
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
// Storing Session
$user_check = $_SESSION['login_user'];
$_SESSION['user_id'] = userid;
$_SESSION['user_firstname'] = firstname;
// Test to see the content of the global session variable
print_r($_SESSION);
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysqli_query($mysqli, "SELECT username FROM logins WHERE username='$user_check'");
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
// Closing Connection
mysqli_close($mysqli);
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
In PHP, variable name starts with '$' sign. Also, in login.php, you have to fetch the data using mysqli_fetch_row or any similar function. Am assuming you are redirecting to session.php after logging in. In that case, you don't have to assign anything to the session variables. It will be there already. All you have to do is to access it.
login.php
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
$row = mysql_fetch_object($query);
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = $row->userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = $row->firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
if (!isset($_SESSION['user_id'])) {
// Closing Connection
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
print_r($_SESSION);
Also, move the connection part to a seperate file and include it in all scripts, so that when your credentials change, you don't have to change it in all the files.
I have built a login php form for an internal website I'm building for our intranet. I am going to combine a few different websites together under one login system. I want to see how I could check if a user is logged in if they visit one of the url's directly and if they're not logged in then redirect them to the login page then after successfully logging in redirect back to the initial page.
I have logged their username and password into a cookie. I know this isn't secure, but again this is just an in house website on the companies intranet. So I don't need much security. The log in system is to just track what each user is doing.
Here's my login code, but now I need to figure out how to check if a user is logged in or not on separate web pages.
//get info from login form
if(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
//query users table
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);
if(!$select_user_query) {
die("Query failed" . mysqli_error($connection));
}
//loop through user info and assigning to variables
while($row = mysqli_fetch_array($select_user_query)) {
$db_id = $row['user_id'];
$db_username = $row['username'];
$db_password = $row['user_password'];
$db_firstname = $row['user_firstname'];
$db_lastname = $row['user_lastname'];
$db_role = $row['user_role'];
}
//validate username and password
if($username === $db_username && $password === $db_password) {
//create cookie to remember user
if(isset($rememberme)) {
//set cookie to last one year
setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), time()+60*60*24*365, '/', 'localhost');
} else {
//cookie expires when browser closes
setcookie('username', $_POST['username'], false, '/', 'localhost');
setcookie('password', md5($_POST['user_password']), false, '/', 'localhost');
}
//if user exists send to dashboard
$_SESSION['username'] = $db_username;
$_SESSION['user_firstname'] = $db_firstname;
$_SESSION['user_lastname'] = $db_lastname;
$_SESSION['user_role'] = $db_role;
header("Location: ../dashboard.php ");
} else {
header("Location: ../index.php");
}
}
Here is how to check if a user is logged in and then redirect them to the page they first visited.
First check to see if a user is logged in:
<?php
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location: index.php");
}
?>
Then include that file in all of your web pages you will be using. Also, create a session for the URL. This will go at the top of your page:
<?php include "includes/login-check.php"; ?>
<?php $_SESSION['url'] = $_SERVER['REQUEST_URI']; ?>
<?php ob_start(); ?>
Then right in the body of the HTML add this:
<input type="hidden" name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />
Then within your login file check for the URL session:
//check to see what page user first visited
if(isset($_SESSION['url'])) {
$url = $_SESSION['url'];
} else {
$url = "../index.php";
}
//redirect user to page they initially visited
header("Location: $url");
That should fully answer your question.
Create a file which you should include at the top in every file of your system and add the following code
session_start();
if(!(isset($_SESSION['username'])))
{
header("Location:login.php")
}
I have a this login script:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
include 'includes/connect.php';
$username = mysqli_real_escape_string($con, $username);
$query = "SELECT password, salt
FROM member
WHERE username = '$username';";
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0)
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
$_SESSION['username']=$username;
if($hash != $userData['password'])
{
header('Location: login.html');
}else{ // Redirect to home page after successful login.
$_SESSION['username']=$username;
header('Location: stats.php');
}
?>
then this is stats.php:
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location:register.html");
}
?>
and under this is my html 5 document.
however it doesnt matter if im logged in or not and it still allows me to access stats.php
You are not storing any session value so if condition will always fail.
So Add
$_SESSION['username'] = $userData['username'];
inside login.php.
You haven't set a session yet. That's why you are getting redirected.
Set a session here on your login.php code like this
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
//Set here like this
$_SESSION['username']=$username; // or whatever you have
you always set the username sesion var . Imagine this situation:
I wanna get the users stats , i only need test login with user and try again with other username .
if i write success one time the user name without the correct password , the result of query get a num_Rows > 0 , because the username is ok .
the next step you are going to test the password but between generate hash and test hash you init the sesion.Now my password is wrong but i get init sesion with the username. ????
if know the url to stats i could acces by http url and see the info that isn t mine.
Your structure to login has got a big bug.
You need insert the set session var inside check password. before header ... stats.php and remove the others occurs on login.php document.
you can make this to logout on logout.php : sesion_Destroy()
I have a simple login form in which if an error occurs such as wrong password, I need it to be able to remember the username which was entered. Would I Go about doing this PHP or Javascript as I am not allowed to use JQuery.
My current PHP - (Not Including the HTML Form)
<?php
//MySQl Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("clubresults") or die(mysql_error());
//Initiates New Session - Cookie
session_start(); // Start a new session
// Get the data passed from the form
$username = $_POST['username'];
$password = md5($_POST['pass']);
// Do some basic sanitizing
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
//Performs SQL Query to retrieve Login Details from DB
$sql = "select * from admin_passwords where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
//Assigns a Variable Count to 0
$count = 0;
//Exectues a loop to increment on Successful Login
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
//If count is equal to 1 Redirect user to the Members Page and Set Cookie
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
header("Location: members.php"); // This is wherever you want to redirect the user to
} else {
//Else Echo that login was a failure.
die('Login Failed. <a href=login.php>Click Here to Try Again</a>');
}
?>
Any help would be appreciated. Cheers
You could use $_SESSION or $_COOKIE.
For $_COOKIE, just use setcookie(...) (for localhost, on $domain, use false)
For $_SESSION, just set it like any other array
To check for existence of the value, use isset(...).
Don't use session variable..you can achieve this by passing username as parameter to login form when login fails its means..
//Else Echo that login was a failure.
die('Login Failed. Click Here to Try Again');
in form
if (isset($_GET['username']) set it into login username field otherwise keep it empty
So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.