Header redirects not working as expected - php

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

Related

How do you loop check a text in php

i am making a code where the system checks if you are an 'Admin' or a 'SuperAdmin'.
i cant seem to make it loop everything to check if 'SuperAdmin' is in the 'user_type'
$sql = "SELECT * from users";
$result = mysqli_query($con,$sql);
while ($row2 = mysqli_fetch_array($result)) {
if ($row2['user_type'] != "SuperAdmin") {
echo "<script>window.alert('You do not have administrative
priviledges for this page!');
location.href='../admin_page.php';</script>";
} else {
}
}
window.alert("You do not have administrative priviledges for this page!"); location.href="../admin_page.php";';
} else {
}
?>
I believe you want to check if the current use is an "Admin" or a "SuperAdmin". In that case, you need to get the row for the current user using the UserID that you get after authenticating the user. Change your query and php code to something like:
$UserId = 111; //This is the user id from database you get on authenticating the user: e.g. 111.
$sql = "SELECT * from users WHERE UserId = ". $UserId;
$result = mysqli_query($con,$sql); //This should retrieve a single row, with details for the specific user.
while ($row2 = mysqli_fetch_array($result)) {
if !(($row2['user_type'] == "SuperAdmin")||($row2['user_type'] == "Admin")){
echo "<script>window.alert('You do not have administrative
priviledges for this page!');
location.href='../admin_page.php';</script>";
} else {
//Code to be executed if the user is an admin or a super admin
}
}

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.

How to non-verify mobile number user redirect to verification page

If user is logged in then if his mobile number is verified then he will allow to move index.php else he will move to mobileverify.php. So i write a function and call this function in index page if unverified user tries to move in index.php function will redirect him mobileverify.php but function is not working please see the code below and tell me where i am wrong
function mobile_verify(){
if(isset($_SESSION['user_id'])){
$login = $_SESSION['user_id'];
$query =mysql_query("SELECT * FROM `users` WHERE `user_id`='$login'");
$row = mysql_num_rows($query);
$verify = $row['verify'];
if($verify === ""){
header('Location: mobileverify.php');
exit();
}
}
}
mysql_num_rows($query);
returns the number of rows in the result set not the values.
try
$row = mysql_fetch_array($result);
you are basically fetching the no of rows meeting your WHERE clause.
IT DOES NOT RETURN THE DATA ITSELF
you could use
$row = mysql_fetch_array($query);
and then check
$verify = $row['verify'];
if(!$verify){
header('Location: mobileverify.php');
}else{
header('Location: index.php');
}

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 */

This if statement isn't working - what am I doing wrong?

I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' ";
$result = mysql_query($q, $con);
if($result == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($result == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($result == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result is a mysql resource. you need
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if($access == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($access == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($access == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result as returned by mysql_query is not a string that you can compare against; it is a resource. You need to fetch the row from $result:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues:
You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string.
The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).
I see two issues:
1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed.
2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result);
$access = $assoc_arr['access'];
now you can compare $access.

Categories