can't get SOME session variables across pages - php

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')";

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

Notice: Undefined variable: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16

When signing into to the app with username, the email is not used hence the following error is throw and vice versa "Notice: Undefined index: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16"
I've tried putting the lines that were generating the error in conditions but those efforts proved futile
Login.php file(parts relevant to the error)
// STEP 1. Receive data / info paassed to current file
if ((empty($_REQUEST['username']) || empty($_REQUEST['password'])) && (empty($_REQUEST['email']) || empty($_REQUEST['password']))) {
$return['status'] = '400';
$return['message'] = 'Missing requird information';
echo json_encode($return);
return;
}
// securing received info / data from hackers or injections
$email = htmlentities($_REQUEST['email']);
$username = htmlentities($_REQUEST['username']);
$password = htmlentities($_REQUEST['password']);
// STEP 2. Establish connection with the server
require('secure/access.php');
$access = new access('localhost' , 'root', '' , 'menthor');
$access->connect();
// STEP 3. Check existence of the user. Try to fetch the user with the same email address
// STEP 3. Check availability of the login/user information
$username_aval = $access->selectUser_Username($username);
$email_aval = $access->selectUser_Email($email);
//$return = array();
// user is found
if ($username_aval) {
// Get encrypted password and salt from the server for validation
$encryptedPassword = $username_aval['password'];
$salt = $username_aval['salt'];
if ($encryptedPassword == sha1($password . $salt)) {
$return['status'] = '200';
$return['message'] = 'Successfully Logged In';
$return['id'] = $username_aval['id'];
$return['username'] = $username_aval['username'];
$return['email'] = $username_aval['email'];
$return['fullName'] = $username_aval['fullName'];
$return['lastName'] = $username_aval['lastName'];
$return['birthday'] = $username_aval['birthday'];
$return['gender'] = $username_aval['gender'];
$return['cover'] = $username_aval['cover'];
$return['ava'] = $username_aval['ava'];
$return['bio'] = $username_aval['bio'];
$return['allow_follow'] = $username_aval['allow_follow'];
} else {
// In event that encrypted password and salt does not match
$return['status'] = '201';
$return['message'] = 'Password do not match';
}
} else if ($email_aval) {
// Get encrypted password and salt from the server for validation
$encryptedPassword = $email_aval['password'];
$salt = $email_aval['salt'];
if ($encryptedPassword == sha1($password . $salt)) {
$return['status'] = '200';
$return['message'] = 'Successfully Logged In';
$return['id'] = $email_aval['id'];
$return['username'] = $email_aval['username'];
$return['email'] = $email_aval['email'];
$return['fullName'] = $email_aval['fullName'];
$return['lastName'] = $email_aval['lastName'];
$return['birthday'] = $email_aval['birthday'];
$return['gender'] = $email_aval['gender'];
$return['cover'] = $email_aval['cover'];
$return['ava'] = $email_aval['ava'];
$return['bio'] = $email_aval['bio'];
$return['allow_follow'] = $email_aval['allow_follow'];
} else {
// In event that encrypted password and salt does not match
$return['status'] = '202';
$return['message'] = 'Password do not match';
}
}else {
// In event that user is not found
$return['status'] = '403';
$return['message'] = 'User was not found';
}
// stop connection with server
$access->disconnect();
// pass info as JSON
echo json_encode($return);
Access.php file(parts relevant to error)
Will try to select any value in the database based on received Email
public function selectUser_Email($email) {
// array to store full user related information with the logic: key=>Value
$returnArray = array();
// SQL Language / Commande to be sent to the server
// SELECT * FROM users WHERE email='rondell#gmail.com'
$sql = "SELECT * FROM users WHERE email='" . $email . "'";
// executing query via already established connection with the server
$result = $this->conn->query($sql);
// result isn't zero and it has least 1 row / value / result
if ($result != null && (mysqli_num_rows($result)) >= 1) {
// converting to JSON
$row = $result->fetch_array(MYSQLI_ASSOC);
// assign fetched row to ReturnArray
if (!empty($row)) {
$returnArray = $row;
}
}
// throw back returnArray
return $returnArray;
}
// Will try to select any value in the database based on received Email
public function selectUser_Username($username) {
// array to store full user related information with the logic: key=>Value
$returnArray = array();
// SQL Language / Commande to be sent to the server
// SELECT * FROM users WHERE username='rondell'
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
// executing query via already established connection with the server
$result = $this->conn->query($sql);
// result isn't zero and it has least 1 row / value / result
if ($result != null && (mysqli_num_rows($result)) >= 1) {
// converting to JSON
$row = $result->fetch_array(MYSQLI_ASSOC);
// assign fetched row to ReturnArray
if (!empty($row)) {
$returnArray = $row;
}
}
// throw back returnArray
return $returnArray;
}
Current results when logging in via web server
Notice: Undefined index: email in /Applications/XAMPP/xamppfiles/htdocs/menthor/login.php on line 16
{"status":"200","message":"Successfully Logged In","id":"44","username":"rondell","email":"rondell#gmail.com","fullName":"rondell","lastName":"","birthday":"","gender":"","cover":"","ava":"","bio":"","allow_follow":"1"}
Expected Results
{"status":"200","message":"Successfully Logged In","id":"44","username":"rondell","email":"rondell#gmail.com","fullName":"rondell","lastName":"","birthday":"","gender":"","cover":"","ava":"","bio":"","allow_follow":"1"}
use email as object or you can dump the request and see what is happening
Turns out the solution was pretty simple came to be after a bit of hard think... I just needed to simply create two login.php files... One dedicated to the users signing in with username and password and the other for users signing in with email and password...Cheers

Checked the query, database, table names, column names, etc. Still have no idea why this error occurred

The error that I occurred:
Fatal error: Call to a member function bind_param() on boolean in C:\wamp64\www\APU\SDP\reg-list-function.php on line 82
I'm writing a php script where the Admins are able to approve the registration of the user. I've checked through the formats of my database, column names, and even query, and still I've no idea why this error pops out. Any help or suggestions will be appreciated!
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg'])) {
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string) {
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1) {
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
} else {
// begin the process of registration //
while (list($key,$val) = #each ($regid)) {
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list
WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($USERVERCODEQ)) {
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1) {
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
} else {
while ($row = mysqli_fetch_array($VERCODEQ)) {
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE) {
I expect the process will be no issue at all as I've checked everything and nothing seems wrong to me.
Reformatting your code to make it more legible and easier to understand, we now have:
<?php
// we will only start the session with session_start() IF the session isn"t started yet //
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
<?php
// including the conn.php to establish connection with database //
include "conn.php";
?>
<?php
// Begin of the function: Registration List's Verification Form: Registration //
// First we check the form has submitted or not //
if (isset($_POST['submit-list-reg']))
{
// If it is, then we will retreive data from the input forms //
$regid = $_POST["regid"];
$reg_acccode = mysqli_real_escape_string($con, $_POST['reg-acccode']);
$reg_pw = mysqli_real_escape_string($con, $_POST['reg-pw']);
// Taking the current time //
date_default_timezone_set("Etc/GMT-8");
$now = date("Y-m-d H:i:s");
// Variable to store Error Message //
$error = '';
// Alphanumeric Generator //
function random_strings($length_of_string)
{
// String of all alphanumeric character
$str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// Shufle the $str_result and returns substring
// of specified length
return substr(str_shuffle($str_result), 0, $length_of_string);
}
// Sorting out the query related to the function //
// Verify the user is an admin or not //
$VERFYADMIN = "SELECT * FROM user
WHERE status = 2 AND active = 1 AND account_code = '".md5($reg_acccode)."' AND password = '".md5($reg_pw)."'";
$VERFYADMINQ = mysqli_query($con, $VERFYADMIN);
//***BEGIN OF PROCESS***//
if (mysqli_num_rows($VERFYADMINQ) < 1)
{
// if the admin is not verified, then inform the user and send him back to admin panel //
echo "<script>alert('ALERT: Information unable to be verified. Please try again.');";
echo "window.location.href='admin_panel.html';</script>";
exit(0);
}
else
{
// begin the process of registration //
while(list($key,$val) = #each ($regid))
{
// Now to verify the user's legitimacy //
// Take the user's vercode into variable first //
$USERVERCODE = "SELECT * FROM registration_list WHERE registration_id = $val AND verified = 0";
$USERVERCODEQ = mysqli_query($con, $USERVERCODE);
if (mysqli_num_rows($USERVERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the data. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($USERVERCODEQ))
{
$vercode = $row["verification_code"];
}
// since we got the value of the vercode then we start to define the query //
$VERCODE = "SELECT * FROM verification_code WHERE verification_code = $vercode AND code_active = 1";
$VERCODEQ = mysqli_query($con, $VERCODE);
if (mysqli_num_rows($VERCODEQ) < 1)
{
// if we are unable to retrieve the data of the registering user then something must gone wrong //
echo "<script>alert('WARNING: Unable to retrieve the info of VERCODE. Please try again.');";
echo "</script>";
}
else
{
while ($row = mysqli_fetch_array($VERCODEQ))
{
$status = $row["code_status"];
}
// we will first insert the user main information into the database: i.e. password, username, etc. //
$account_code = random_strings(8);
$APPROVE = "INSERT INTO user (username, password, email, account_id, account_code, active, status, registered_date, verification_code)
SELECT username, password, email, account_id, '".md5($account_code)."', 1, $status, $now, verification_code
FROM registration_list
WHERE registration_id = ?";
$stmt = $con->prepare($APPROVE);
$stmt->bind_param("i", $val); // Problem around here //
$stmt->execute();
if (($stmt->error) == FALSE)
{
In here are several things that I wouldn't personally do. As has been mentioned, using variables supplied by user input, even MD5 ones, directly in SQL queries should be best avoided.
The line "while(list($key,$val) = #each ($regid))", which sets the $val variable has an ampersand to suppress any error messages, this in turn could be causing you issues further down. It's best not to suppress these messages, but to find out why they are occurring, this could be the cause of a non numeric value being passed to your "bind_param" function. I'd also use single quotes instead of double quotes with the function as well.
Solved after I changed the variables that contained string value with this format -> ' " . $variable . " ' .

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

Page Redirection doesnt work

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.

Categories