Recurring redirect error - php

I have posted a question for this a long time ago, but i still can't find a answer. Basically, when a user has logged into the account and has been inactive for a while and when they return they would click something and then the system would log them out and they would have to re-login. It works 90% of the time, but sometimes it gives an error like: This page is redirecting in a way it will never complete.
But when a user clears the cookies it works fine and sometimes closing the tab and opening up a new one works too.
Here's the code:
<?php
$SUBDOMAIN = mysql_real_escape_string($_GET['p_name']);
$pname = mysql_real_escape_string($_GET['p_name']);
echo "$p_name";
include("db.php");
?>
<?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['p_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 p_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 p_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
{
// if they are not logged in
?>
</table>
</form>
<?php
}
?>

Hey, your code formatting is really bad no fun to read you might want to fix that. :)
I just had a quick look at it, erros occurring only 90% or sometimes hard to catch.
I saw you are using header("Location: home.php"); without any exit; at the end, which is generally a bad idea unless you intent to do so.
The function call header("Location: home.php"); will not stop the script from processing. The user might get the header and redirects and stops code from processing (depending on some php settings) but maybe some cookies get set before the user gets redirected. So try adding a exit; after your redirect header calls.
format you code

I would wager a guess that this has to due with the differing expire times of your session cookie, and the expire times you set for your ID_my_site and Key_my_site cookies. If not overridden, the default session timeout is 30 minutes (expressed as seconds in the settings - so 1,800). Your cookies are set to expire after an hour. So you could find yourself in a situation where the session has expired, but the other cookies are still present. Depending on the order / way you are checking things and then redirecting, you will encounter this situation if the user was idle for more than 30 minutes but less than 1 hour.
Since the only redirect you are performing in this code sample is the one to home.php, there is some sort of check occurring in that file, that is sending them on the never ending redirect spiral.
As an aside, that code sample really is very messy. You are assigning and reassigning the $username variable so often for example (and to seemingly different types of things - though I wouldn't know without seeing actual input), that it is no wonder you are having mystery issues. These few lines for example are redundant:
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
You're assigning $username from the session and immediately assigning it back.
From the beginning of the file:
$SUBDOMAIN = mysql_real_escape_string($_GET['p_name']);
$pname = mysql_real_escape_string($_GET['p_name']);
These two variables are assigned the same $_GET value, but it doesn't appear that $SUBDOMAIN is ever used.
And from the end of the file you are assigning the same value twice:
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
I really would encourage you to step back from your code, look at your inputs and figure out what you need to accomplish and refactor or rewrite this code entirely. With stuff like this floating around it is no wonder you have mystery bugs in your system.

Additionally, a HTTP Location header requires the URL to be absolute. You should use something like this:
$currentServerHost = $_SERVER['HTTP_HOST'];
$currentBaseURI = $currentServerHost . rtrim(dirname($_SERVER['PHP_SELF']), '/\');
header( 'Location: ' . 'http://' . $finalURI . '/home.php' );
exit;

Related

Implementing a check for user levels

I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP

Wrong session value when reading

I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?
As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.
I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.

Trying to login via php not working scripts

Hi I am trying to get the user signed in via sessions, here is my code it was working before now it isn't i didnt even change the code.
profile.php (to show after logged in)
<?php
ob_start();
session_start();
$userName = $_SESSION['username'];
$userid = $_SESSION['userid'];
if(isset($_GET['session'])) {
$currentSessionID = $_GET['session'];
$currentSessionID = md5(md5(md5($currentSessionID)));
session_id($currentSessionID);
header("Location:profile.php");
return;
}
if(!isset($userName)){
echo "OUT";
return;
}
...
scripts/signin.php
ob_start();
session_start();
include"config.php";
echo "here";
// check for required fields
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['Username']) && isset($_POST['Password'])) {
$user = mysql_real_escape_string($_POST['Username']);
$pass = mysql_real_escape_string($_POST['Password']);
$decrypt = md5(md5(md5($pass)));
$ensure = "select * from userinfo WHERE Username = '$user' and Password='$decrypt' and status='1'";
$result= mysql_query($ensure);
if(mysql_num_rows($result) > 0) {
echo "here2";
$entry = mysql_fetch_array($result) or die(mysql_error());
$_SESSION['username'] = $entry['Username'];
echo $entry['Username'];
$_SESSION['userid'] = $entry['Id'];
$currentSessionID = session_id();
$currentSessionID = md5(md5(md5($currentSessionID)));
header("Location: http://www.myprocity.com/profile.php?session=".$currentSessionID);
echo "here3";
the reason why im passing in the session id is because im trying to only keep sign in and sign up HTTPS while the other pages HTTP so I can show Google ads, does anyone know how to implement this without security issues (perfectly)
it always goes to OUT even when $_SESSION is my username (database is correct)
In profile.php you are checking for the presence of a session ID, and changing the session ID if you find it. You are doing this after you've set up a session with session_start(), but the PHP manual specifically says you must call session_id() before session_start() for this to work.
You're also hashing $_GET['session'] before sending it, and again before using it. The session ID you're trying to use in profile.php won't match the session ID used in signin.php
The result is that $_SESSION does not have the data in it you are expecting.
You need to rationalise your use of session_id(), and ensure the correct value is passed from page to page. All the hashing with md5() is just complicating matters - drop it. Realistically, I don't see why you need anything more than session_start() at the top of each page and let PHP handle the sessions. You may have an argument for doing what you're doing, but your solution simply won't work.

Login system - Session cookie not set for the first time

I created a login/register system from scratch by following various tutorials and reading articles online. The system works but there is a bug which I don't understand. When a user tries to login for the first time, it returns an error that the account is not found, but if the user tries to login again, then it proceeds with logging in. I tested if it stores a session cookie and it turns out that it doesn't (at least not for the first time). Next time the user tries to log in, it stores the cookie properly.
This is my first part of the login script, the one that checks if the captcha entered is correct and then it sets the session cookies and redirects the user to the login page script that checks if the user exists.
<?php
session_start();
$mode = $_GET['mode'];
if($mode == 'login')
{
require_once('recaptchalib.php');
$privatekey = "---";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
header('Location: http://cpalander.net/login.php?option=captcha');
} else {
$user = $_POST['username2'];
$pass = $_POST['password3'];
$_SESSION['pass3'] = $pass;
$_SESSION['user3'] = $user;
header('Location: http://cpalander.net/login.php?option=checkuser');
}
die();
}
else if($mode == 'sendticket')
{
require_once('recaptchalib.php');
$privatekey = "---";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
header('Location: http://cpalander.net/dashboard.php?option=sendticket&error=captcha');
} else {
$subject = $_POST['subject'];
$message = $_POST['message'];
header('Location: http://cpalander.net/dashboard.php?option=sendticket&subject=' . urlencode($subject) . '&message=' . urlencode($message));
}
die();
}
else
{
require_once('recaptchalib.php');
$privatekey = "---";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
header('Location: http://cpalander.net/register.php?option=captcha');
} else {
$_SESSION['user2'] = $_POST['username'];
$_SESSION['pass2'] = $_POST['password'];
$_SESSION['mail2'] = $_POST['email'];
header('Location: http://cpalander.net/makeacc.php');
}
die();
}
?>
And this is the part of code that checks if the user exists and redirects the user in case of an error:
<?php session_start();
$data = $_GET["option"];
$user = $_SESSION['user3'];
$pass = $_SESSION['pass3'];
function generateRandomString($length = 10)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>....</head>...
<body>...
...<?php
if ($data == 'checkuser')
{
$user = $_SESSION['user3'];
$link = new mysqli('127.0.0.1', '*******', '*******', '*******');
if ($link->connect_errno) {
die('Failed to connect to MySQL: (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$result = $link->query("SELECT * FROM users WHERE username='$user' AND active=1 AND banned=0");
$numrows = $result->num_rows;
if($numrows == 0)
{
$link->close();
session_destroy();
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=login.php?option=notfound&user=' . $user . '">'; // This is the part that I used to check if the $user variable is set
exit;
}
$row = $result->fetch_assoc();
$sid = $row['salt'];
$pass_h = hash('sha256', $sid . $pass);
$result = $link->query("SELECT * FROM users WHERE username='$user' AND password='$pass_h' AND active=1 AND banned=0");
$numrows = $result->num_rows;
if($numrows == 0)
{
$link->close();
session_destroy();
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=login.php?option=notfound">';
exit;
}
else
{
$link->close();
$_SESSION['user'] = $user;
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=dashboard.php?option=home&user=' . $user . '">';
exit;
}
$link->close();
}...</body>
Can anyone help me out on this one? Also, session_start(); is on top of the login page code.
session_start should be present in all your files that need access to the $_SESSION variable. That means, if you are acessing unrelated files, you need to add session_id() or session_start(); to them (the session_id() or session_start(); part is to make sure that the dread the Session already started warning doesn't show up if a require/include to the same file were made in the same request)
session_destroy() destroys the session, you might just want to session_unset() instead, since session_destroy() will recreate the session when session_start() anew is called again. But if you really want to destroy the session and start again, a cross browser way is to call both session_unset() and session_destroy() (cough IE cough)
Also, you should take notice that apart from the question itself, you are allowing a XSS vulnerability on your code by passing the raw $_POST data to an URL without checking it.
The code appears as if it should work. You destroy the session when the user is not found,
so there's no reason for it to work the second time and not the first... unless there is
something going on before, that relies on some session data, and which you did not post.
The only thing that seems iffy is the fact that the two login fields are named username2 and
password3, but I guess that you should get errors every time if that was a problem - unless
you generate "username2" or "username3" in response to different conditions?
Apart from that, I have some suggestions:
1) The
require_once('recaptchalib.php');
can be placed at the beginning, since you seem to use it anyway.
Then instead of
$user = $_POST['username2'];
$pass = $_POST['password3'];
$_SESSION['pass3'] = $pass;
$_SESSION['user3'] = $user;
you can just put (but more on that later)
$_SESSION['pass3'] = $_POST['password3'];
$_SESSION['user3'] = $_POST['username2'];
and you have no need of three separate die()s - actually I think you need none of them.
In this point:
if ($data == 'checkuser')
{
$user = $_SESSION['user3'];
you do not check that $_SESSION['user3'] is actually set. You might get errors
because of that. Actually, you had already assigned $user before (again without checking
that it had been set).
This row here is really dangerous
$result = $link->query("SELECT * FROM users WHERE username='$user' AND active=1 AND banned=0");
since if I sent you a "username2" with a value of "bobby' OR ''='" your query would have become:
$link->query("SELECT * FROM users WHERE username='bobby' OR ''='' AND active=1 AND banned=0");
and since ''='' is always true, chances are that little Bobby Tables might have logged in, even if inactive and banned.
Then you store the password in the clear in the session, which I'll admit is little danger - but that is still worse than no danger at all. Why not store a hash instead?
$_SESSION['pass'] = hash('sha256', $_POST['password3']); // unsalted password
$_SESSION['user'] = hash('sha256', $_POST['username2']); // unsalted username
...
$link->query("SELECT * FROM users WHERE SHA2(username,256)='$user'
AND SHA2(CONCAT(salt,'$pass'),256)=password AND active=1 AND banned=0");
Now whatever one might place into $_POST, it will be grinded and digested to two safe hashes. The
session no longer contains either username or password. The password is still salted. If either
the user is nonexistent, banned, inactive, or password is wrong, the query will yield no results,
and its cost will always be the same, defeating most timed attacks.
If you keep the username/pass in the clear, then you need to mysqli_escape() it to avoid a SQL injection attack (or use prepared statements with bound parameters).
Looking at the dates on this post I see I am late to the party, but I found this because I was having a very similar issue. See my post at PHP code to replicate nocache=1 functionality .
Here's an experiment that may narrow the problem: Browse away from your page, go to your browser's cookies and delete cookies for that domain, browse back to the login page, then check to see if there is a PHPSESSID cookie. My guess is there won't be. Then try the login (which you say fails). THEN check cookies again - the PHPSESSID will be there. Then the next login attempt works.
NOW try this: Again clear the cookies for that domain, then browse to that login page with a ?nocache=1 at the end of the URL. This time there probably WILL be a PHPSESSID cookie, and this time the login will work the first try.
In my case that ?nocache=1 thing works, but it is not even needed when I'm running the same code locally on my localhost.
It seems definitely like a session handling setting on the server.

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