Page Redirection doesnt work - php

I grabbed a piece of code a login and registration script when i run the index.php from apache it gives this error in the address tab
http://localhost/johnlogin/?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login?msg=login
and this below error on the browser page
The page isn't redirecting properly
Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
This problem can sometimes be caused by disabling or refusing to accept cookies.
I dig out the code but cant solve the problem here's the code of index.php
require_once('load.php');
$logged = $j->checkLogin();
if ( $logged == false ) {
//Build our redirect
$url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$redirect = str_replace('index.php', 'login.php', $url);
//Redirect to the home page
header("Location: $redirect?msg=login");
exit;
} else {
//Grab our authorization cookie array
$cookie = $_COOKIE['joombologauth'];
//Set our user and authID variables
$user = $cookie['user'];
$authID = $cookie['authID'];
//Query the database for the selected user
$table = 'j_users';
$sql = "SELECT * FROM $table WHERE user_login = '" . $user . "'";
$results = $jdb->select($sql);
//Kill the script if the submitted username doesn't exit
if (!$results) {
die('Sorry, that username does not exist!');
}
//Fetch our results into an associative array
$results = mysql_fetch_assoc( $results );
?>
the load.php basically consists a require_once statement which loads db and a class file here's the class code which id been called by
$logged = $j->checkLogin();
---------the class.php code-------
function checkLogin() {
global $jdb;
//Grab our authorization cookie array
$cookie = $_COOKIE['joombologauth'];
//Set our user and authID variables
$user = $cookie['user'];
$authID = $cookie['authID'];
/*
* If the cookie values are empty, we redirect to login right away;
* otherwise, we run the login check.
*/
if ( !empty ( $cookie ) ) {
//Query the database for the selected user
$table = 'login';
$sql = "SELECT * FROM $table WHERE uName = '" . $user . "'";
$results = $jdb->select($sql);
//Kill the script if the submitted username doesn't exit
if (!$results) {
die('Sorry, that username does not exist!');
}
//Fetch our results into an associative array
$results = mysql_fetch_assoc( $results );
//The registration date of the stored matching user
$storeg = $results['user_registered'];
//The hashed password of the stored matching user
$stopass = $results['user_pass'];
//Rehash password to see if it matches the value stored in the cookie
$authnonce = md5('cookie-' . $user . $storeg . AUTH_SALT);
$stopass = $jdb->hash_password($stopass, $authnonce);
if ( $stopass == $authID ) {
$results = true;
} else {
$results = false;
}
} else {
//Build our redirect
$url = "http" . ((!empty($_SERVER['HTTPS'])) ? "s" : "") . "://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$redirect = str_replace('index.php', 'login.php', $url);
//Redirect to the home page
header("Location: $redirect?msg=login");
exit;
}
return $results;
}
}
all the bug is being happening here
regards

The problem is your script is recursively redirecting to itself.
The problem is when you first try to access the page, the script determines you as not logged in : if ( $logged == false )
and it redirects you to the login.php with params, which are further redirecting it to the same page, hence your script keeps on looping. When your web server (apache) loops it for a certain amount of time it flags the request to be unable to service, hence the error.

Related

Multiple Database requests for login

I have three files that are relevant for this part of my login scenario:
/project/index.html
/project/api/user/login.php
/project/api/objects/user.php
The index.html has a simple login form in it, calling the ./api/user/login.php.
In this form I have a checkbox that is an option for the user in order to stay logged in or not.
If the user has selected this option, with every login, I would like to check if the credentials are correct (login function -> stmt1 in user.php) as well as to update the lastlogin (datetime), the identifier and securitytoken if the checkbox was set (login function -> stmt2 in user.php).
The user.php is included_once in the login.php that gets the values out of the index.html form and sends them to the login() function in the user.php.
Depending on the functions return value, the login.php decides if the login was successful or not.
The login itself (stmt1) works, but the update of lastlogin, identifier and securitytoken (stmt2) doesn't.
login.php
session_start();
// include database and object files
include_once '../config/database.php';
include_once '../objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare user object
$user = new User($db);
// set ID property of user to be edited
$user->username = isset($_GET['username']) ? $_GET['username'] : die();
$user->password = base64_encode(isset($_GET['password']) ? $_GET['password'] : die());
$user->remember = isset($_GET['remember']) ? $_GET['remember'] : die();
$stmt1 = $user->login();
if($stmt1->rowCount() > 0){
// get retrieved row
$row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
$_SESSION['userid'] = $row1['uid'];
// create array
$user_arr=array(
"status" => true,
"message" => "Login erfolgreich!",
"uid" => $row1['uid'],
"username" => $row1['username']
);
$stmt2 = $user->login();
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
print_r($row2);
// create array
$user_arr=array(
"lastlogin" => $row2['lastlogin']
);
}
else{
$user_arr=array(
"status" => false,
"message" => "Benutzername und/oder Passwort nicht korrekt!",
);
}
// make it json format
print_r(json_encode($user_arr));
?>
user.php
function login(){
// select all query
$query1 = "SELECT
`uid`, `username`, `email`, `password`, `created`, `lastlogin`
FROM
" . $this->table_name . "
WHERE
username='".$this->username."' AND password='".$this->password."'";
// prepare query statement
$stmt1 = $this->conn->prepare($query1);
// execute query
$stmt1->execute();
return $stmt1;
// set up the remain logged in function
if(isset($this->remember)) {
$identifier = random_string();
$securitytoken = random_string();
$remember = ",identifier='".$identifier."',securitytoken='".$securitytoken."'";
setcookie("identifier",$identifier,time()+(3600*24*365)); //1 year valid
setcookie("securitytoken",$securitytoken,time()+(3600*24*365)); //1 year valid
} else {
$remember = "";
}
// update last login
$query2 = "UPDATE
" . $this->table_name . "
SET
`lastlogin` = '".date("Y-m-d H:i:s")."'
".$remember."
WHERE
username='".$this->username."' AND password='".$this->password."'";
// prepare query statement
$stmt2 = $this->conn->prepare($query2);
// execute query
$stmt2->execute();
return $stmt2;
}
function random_string(){
if(function_exists('random_bytes')) {
$bytes = random_bytes(16);
$str = bin2hex($bytes);
} else if(function_exists('openssl_random_pseudo_bytes')) {
$bytes = openssl_random_pseudo_bytes(16);
$str = bin2hex($bytes);
} else if(function_exists('mcrypt_create_iv')) {
$bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
$str = bin2hex($bytes);
} else {
//secret key should have >12 random chars
$str = md5(uniqid('SECRET KEY', true));
}
return $str;
}
In the user.php after return $stmt1;
The code is returned and the cookies are not set
I would do this... Check login... If true, save cookies with id and token
And then periodically check if token and id correspond... If so... Just UPDATE the last login time.
Note: your prepared statement is vulnerable!! Dont append the parameters with '.' use placeholders instead, and dont encode the password, is better to hash it... Then compare hashes

PHP authentication dialog keeps repeating

I'm using PHP and want to authenticate a user against an entry in a MySQL database. All pages use HTTPS.
The problem is when I enter the correct username and password, the authorize dialog box disappears then reappears with the username and password blank.
Does anybody know how to fix it?
Snippets of code:
<?php
session_start();
if($_SERVER["HTTPS"] != "on")
{
header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER ["REQUEST_URI"]);
exit();
}
require_once("../php-files/cookies.php");
require_once("../php-files/db_connect.php");
/* If user tries to bypass logging in then we need to redirect back
* to main page. First though, we need to get whether we're localhost or
* live production.
*/
if($_SESSION["atHome"] == true)
{
require_once("/Calendar/Month.php");
require_once("/Calendar/Month/Weekdays.php");
}
else
{
require_once("../Calendar/Month.php");
require_once("../Calendar/Month/Weekdays.php");
}
include("../php-files/create-calendar.php");
include("../php-files/put-footer.php");
include("../php-files/timestamp.php");
//if cookie not set redirect back to home page
// prevents people from getting this page by using /php-files/new_event.php
// unless they have a cookie set
if(!isset($_COOKIE['www_broken_com']))
{
if($_SESSION["atHome"] == true)
header("Location: https://localhost");
else
header("Location: https://www.broken.com");
}
$theCookie = $_COOKIE['www_broken_com'];
$theCookie = explode(";",$theCookie);
//check to see if an Admin is going to enter a new event
//if so ask if they want to enter or to approve events submitted
function authenticate_user()
{
header('WWW-Authenticate: Basic Realm="New"');
header("HTTP/1.0 401 Unauthorized");
return(FALSE);
}
$authenticate = TRUE;
$authorized = FALSE;
$authorizedName = "";
$privleges = "";
//Compare the email address of the person currently accessing and see if
//he's in the admin database. If so then he as admin privleges.
$db_conn = new db_stuff();
$db = $db_conn->connect();
$query = "SELECT * FROM admin WHERE email = '$theCookie[5]'";
if(!$result = $db->query($query)) exit("Could not select for new event");
if($result && $result->num_rows != 0)
{
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']))
$authenticate = authenticate_user();
if($authenticate == TRUE)
{
$userName = $_SERVER['PHP_AUTH_USER'];
$userPwd = $_SERVER['PHP_AUTH_PW'];
$query = "SELECT * FROM admin WHERE name = '$userName' AND pwd = PASSWORD('$userPwd')";
if(!$result = $db->query($query))
echo "<br />Could not select for authentication";
if($result && $result->num_rows != 0)
{
while($admin = $result->fetch_array())
{
$authorizedName = $admin[2] . " " . $admin[1];
}
$authorized = TRUE;
$privleges = ", you have administrator privleges.";
$_SESSION['authorizedName'] = $authorizedName;
}
}
else
{
exit("In FALSE");
$authorized = FALSE;
$_SERVER['PHP_AUTH_USER'] = "No one";
}
}
else
$privleges = " ";
After much digging......
run phpinfo() to see if: Server API = CGI/FastCGI (It should be the 4th line from the top)
If it is set, you can't do basic-authorization without a work-around.
Common workaround is to alter htaccess and add this line: RewriteRule .*-[E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
This worked for me.
See stackoverflow: Basic Authentication with PHP gives an endless loop for more info.

can't get SOME session variables across pages

Trying to add some extra elements to my session variables for filesystem directory work, and I noticed that I can't add some. Here's what I have:
<?php
#login.php
// This page processes the login form submission.
// Upon successful login, the user is redirected.
// Two included files are necessary.
// Check if the form has been submitted:
if(isset($_POST['submitted']))
{
// For processing the login:
require_once ('login_functions.php');
// Need the database connection:
require_once ('../mysqli_connect.php');
// Check the login:
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if ($check) //OK!
{
// set the session data:
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['company_name'] = $data['company_name'];
$_SESSION['email'] = $data['email'];
// Store the HTTP_USER_AGENT:
$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
//Redirect:
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit(); // Quit the script.
}
else // Unsuccessful!
{
// Assign $data to $errors for error reporting
// in the login_functions.php file.
$errors = $data;
}
mysqli_close($dbc); // Close the database connection
} //End of the main submit conditional
//Create the page:
include('login_page_inc.php');
?>
here are the login functions:
<?php #login_functions.php
//This page defines two functions used by the login/logout process.
/*This function determines and returns an absolute URL.
* It takes one argument: the page that concludes the URL.
* The argument defaults to index.php
*/
function absolute_url ($page = 'about.php')
{
//Start defining the URL...
//URL is http:// plus the host name plus the current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Remove any trailing slashes:
$url = rtrim($url, '/\\');
// Add the page:
$url .= '/' . $page;
// Return the URL:
return $url;
}//End of absolute_url() function.
/*This function validates the form data (email address and password).
* If both are present, the database is queried.
* The function requires a database connection
* The function returns an array of information, including:
* - a TRUE/FALSE variable indicating success
* - an array of either errors or the database result
*/
function check_login($dbc, $email = '', $pass = '')
{
$errors = array(); // Initialize error array.
// Validate the email address:
if (empty($email))
{
$errors[] = 'You forgot to enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
// Validate the password:
if (empty($pass))
{
$errors[] = 'You forgot to enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if(empty($errors)) //If everything's OK.
{
// Retrieve the user_id and first_name for that email/password combo
$q = "SELECT user_id, first_name, email FROM
user WHERE email='$e' AND pass=SHA1('$p')";
$r = #mysqli_query ($dbc, $q); // Run the query.
//Check the result:
if (mysqli_num_rows($r)==1)
{
//Fetch the record:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Return true and the record:
return array (true, $row);
}
else //Not a match for writer, check the publisher table
{
$q = "SELECT pub_id, company_name, cemail FROM
pub WHERE cemail='$e' AND password=SHA1('$p')";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)==1)
{
//Fetch the record:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Return true and the record:
return array (true, $row);
}
else
{
echo '<p>Invalid Credentials</p>';
}
}
} // End of empty($errors) IF.
// Return false and the errors:
return array(false, $errors);
} // End of check_login() function.
?>
Note: $_SESSION['first_name'] and $_SESSION['company_name'] have always worked correctly, however adding email and user_id is not working. Thanks in advance.
email and user_id will never work for the publisher: as the login function returns "pub_id" and "cemail". To fix this, you could change the SQL to:
$q = "SELECT pub_id as user_id, company_name, cemail AS email FROM
pub WHERE cemail='$e' AND password=SHA1('$p')";

Header redirects not working as expected

I have the following function which retrives the currently logged in users' username and finds out their access level from the database (either 'requested','user', or 'admin')
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if(isset($_SESSION['username']))
{
if($access == 'user')
{
return 1; // Returns 1 if access level is user
}
elseif($access == 'admin')
{
return 2; // Returns 2 if access level is admin
}
elseif($access == 'requested')
{
return 3; // Returns 3 if access level is requested
}
}
}
When I am checking whether the user is an admin using the follow code, this works correctly.
/* Redirects user if access level does not equal admin */
$result = fetchAccess();
if($result != 2)
{
header("location:index.php");
}
However when I check to see whether the access is 'requested' - this following is NOT working correctly.
<?php
/* Redirects user if access level does is 'requested' */
$result = fetchAccess();
if($result == 3)
{
header("location:redirect.php");
}
?>
Does anyone know why this is?
You can do this:
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
global $access
$access = $row['access'];
}
then:
global $access
if($access != admin){
header("location:redirect.php");
}
Have you verified that $result actually equal to 3? it may very well be that in the first instance $result == "" which is != 2 so it is not working at all. Try debugging it by including a header like:
<?php
$result = fetchAccess();
header("X-my-result: [$result]");
if ( $result == 3 ) {
header("Location: redirect.php");
}
?>
and see what you get back for value of $result in the headers.
do an echo statement to see what is return in the $result variable. btw, i'm not sure if your logic in your first redirect statement is to encompass both 'user' and 'requested', but those users will be redirected to index.php

$_SESSION difficulties

I am creating a login script that stores the value of a variable called $userid to $_SESSION["userid"] then redirects the user back to the main page (a side question is how to send them back where they were?).
However, when I get back to that page, I am echoing the session_id() and the value of $_SESSION["userid"] and only the session id shows up. It had occurred to me that maybe my redirect page needs to have at the top, but if this were true, then the session_id I'm echoing would change each time I end up on the page that is echoing it. Here is the script:
<?php
session_start();
include_once("db_include.php5");
doDB();
//check for required fields from the form
if ((empty($_POST['username']) && empty($_POST['email'])) || empty($_POST['password'])) {
header("Location: loginform.php5");
exit;
} else if($_POST["username"] && $_POST["password"]){
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE username='".$_POST["username"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit; }
} else if($_POST["email"] && $_POST["password"]) {
//create and issue the query
$sql = "SELECT id FROM aromaMaster WHERE email='".$_POST["email"]."' AND password=PASSWORD('".$_POST["password"]."')";
$sql_res =mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
//get the number of rows in the result set; should be 1 if a match
if(mysqli_num_rows($sql_res) != 0) {
//if authorized, get the userid
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
//set session variables
$_SESSION['userid'] = $userid;
mysqli_free_result($sql_res);
//redirect to main page
header("Location: loginredirect.php5");
exit;}
} else {
//redirect back to login form
header("Location: loginform.php5");
exit;
}
mysqli_close($mysqli);
?>
You're doing this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $_info["id"];
}
Where you should do this:
while($info = mysqli_fetch_array($sql_res)) {
$userid = $info["id"];
}
Make sure:
<?php
session_start();
Is at the top of each page.
Additionally, you can test by commenting out your redirects and echo'ing the value you're setting with to make sure you're retrieving/storing the correct value to begin with.
You need to call session_write_close() to store the session data changes.
Side answer: you can use the $SERVER["HTTP REFERER"] to redirect back, if it was filled by the browser

Categories