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.
Related
I have a login script I want if user attempt 3 invalid password then the username associated to them would be disabled or blocked for a day / 24hrs.
Since I make a if condition in php login code where status=3 alert your account is blocked for a day.
status is my database column name which count the value of invalid login of user from 1 to 3 maximum.
But issue is my here that is how I make the status automatically count or increase like 1, 2, 3 in user invalid login.
How to I add this function with my login code
I have not idea about that. On YouTube there is not any video regards this even in other website.
Stackoverflow is my last hope where someone helps user.
Please have a look at this question and help to create satatus count automatic when user inter invalid password.
My login PHP is : https://pastebin.com/QpwDtjBg
Thank you in advance
You're gonna want to use PHP's $_SESSION object.
In the code block where you detect bad user/pass combos, add an iterator to the session.
First, add a session entry to the top of your script (Or wherever you define global variables), for bad_logins, and start your session.
session_start();
$_SESSION['bad_logins'] = 0;
Then in the part of your code where you detect a bad login, increment the bad logins by 1.
$_SESSION['bad_logins']++;
This will allow you to then check for bad attempts with an if statement
if($_SESSION['bad_logins'] > 3) {
// Do something here.
}
The script you linked has some other issues you may want to address prior to adding this in though.
You just need to add an update to the field 'status' on the database with 1, 2 or 3, on the IF condition:
if($data == NULL || password_verify($password, $data['Password']) == false) {
And read that same field, when the submit form is sent every single time... if it is already 3, then just skip to the IF condition
if($data['Status'] == "//auto count//")
Something like this (haven't tested the code) and the code should be function based, at least...
`
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(isset($_POST['submit'])) {
$messages = array(
'INVALID_EMAIL' => "<div class='alert-box warning error'><span>Invalid format, re-enter valid email.</span></div>",
'ALL_FIELDS_REQUIRED' => "All field is mandatory! case sensitive.",
'VERIFY_EMAIL' => "Please verify your email!",
'INVALID_COMBINATION' => "Invalid username or password combinations.",
'BLOCKED' => "you are blocked for a day. <a href='#'><span>Know why?<span></a>",
);
$msg = "";
$error = false;
$con = new mysqli("localhost", "softwebs_softweb", "test#123", "softwebs_cms");
$email = $con->real_escape_string(htmlspecialchars($_POST['username']));
$password = $con->real_escape_string(htmlspecialchars($_POST['password']));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$msg = $messages['INVALID_EMAIL'];
$error = true;
}
if ($email == "" || $password == "") {
$msg = $messages['ALL_FIELDS_REQUIRED'];
$error = true;
}
if(!$error) {
$sql = $con->query("SELECT * FROM users where Email_ID = '$email' ");
if ($sql->num_rows > 0) {
$data = $sql->fetch_array();
// Blocked
if ($date['status'] === 3) {
$msg = $messages['BLOCKED'];
$error = true;
}
if ($data['isEmailConfirm'] == "0") {
$msg = $messages['VERIFY_EMAIL'];
$error = true;
}
if ($data == NULL || password_verify($password, $data['Password']) == false) {
$msg = $messages['INVALID_COMBINATION'];
$error = true;
// Update the status + 1
$sql = $con->query("UPDATE users SET status = " . $statusData['status'] + 1 . " WHERE Email_ID = '$email' ");
}
}
}
if($error && trim($msg) !== "") {
$msg = "<div class='alert-box error'><span>$msg</span></div>";
} else {
session_start();
$_SESSION['login']=$_POST['username'];
$_SESSION['id']=$data['id'];
header('location: ./account/dashboard.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.
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
When a user registers, the script sends an email to verify his account. Clicking on the link, the script gets the token
$token = mysql_real_escape_string($_GET["token"]);
and what I thought to do is
if($token != '') {
mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
}
or
if($token != '') {
$result = mysql_query("UPDATE members SET verified = '' WHERE verified = '$token'");
if($result) { }
else { }
}
What is my purpose is to echo a success or failed message on the user. When it will be success then the verified will be empty.
What is the appropriate way of doing this with my examples above?
Should I check if there is the token in the DB before updating it?
Thank you.
Your current method updates a record if it exists but does not take into account that which does not exist or match. You should run something similar to:
if($token != '') {
$result = mysql_query("SELECT COUNT(*) FROM members WHERE verified = '$token'");
while($row = mysql_fetch_row($result)) {
$records = $row[0];
}
if($records == 0) { echo 'no results'; }
elseif($records ==1) { echo 'you matched'; then update the record. }
}
edit
changed BACK to the while loop, wasn't thinking of the count returning 0 rows
I've created the following banning system when a user logins on my site. It checks if the user is banned, and then follows a process to gather information, and finally brings up a notice and doesn't let the user login. However, this does not happen and I can login fine. Any help would be appriciated.
$un9 = "gdscei";
$checkban = mysql_query("SELECT * FROM bans WHERE usr = '" .$un9. "'") or die(mysql_error());
if(mysql_num_rows($checkban) != 0){
$query7 = "SELECT * FROM bans WHERE usr = '".$un9."'";
$result7 = mysql_query($query7) or die(mysql_error());
while ($row7 = mysql_fetch_assoc($result7)) {
$reas = $row7['reas'];
$timeb = $row7['time'];
$tban = $row7['tban'];
$tip = $row7['ipd'];
};
if($timeb == "perm"){
$bant = "Permanent";
}else{
$bant = $timeb;
};
$checkusrdel = mysql_query("SELECT * FROM users WHERE username = '".$un9."'") or die(mysql_error());
if(mysql_num_rows($checkusrdel) != 0){
$acdel = "n";
}else{
$acdel = "y";
};
if(empty($tip) && acdel == "n"){
$bank = "account ban";
}else if($acdel == "y" && empty($tip)){
$bank = "account deleted";
}else if($acdel == "y" && $tip){
$bank = "account deleted + IP ban";
}else{
$bank = "account ban + IP ban";
};
$notice = '<script type="text/javascript">alert("You have been banned, as followed: "'.$bank.'". Your ban lasts until "'.$bant.'"."); window.open("login.php","_self");</script>';
};
The solution is simpler than you may have imagined:
$notice = '<script type="text/javascript">alert("You have been banned, as followed: '.$bank.'. Your ban lasts until '.$bant.'."); window.open("login.php","_self");</script>';
In short, you shouldn't have used brackets twice in the JavaScript alert message.
Addition: Do not forget to echo the notice in the end. The excerpt of your PHP script doesn't show me anything like that. If you want to show your homepage after the ban check, just use the die-function to output a message and terminate the current script if the user is banned. In your case, just add the following after having defined the variable $notice:
die($notice);
You are providing too much information to the user, all they need to know is that they are banned, not the type of ban.
if (banned)
{
ajax.display("Ban HAMMER!!");
}
else
{
user.logon();
redirect("location: home.php");
}