How to validate session in php? - php

I want to some users can access to a page and others user can't but I don't know how to valide my session variable in my index for example. How I have to the top of my index.php page to validate that only some users can see that page?
This is the process for my login
<?php
session_start();
include 'db.php';
if(isset($_POST['btn_entrar']))
{
$user=$_POST['usuario'];
$password=$_POST['contraseña'];
$admin='Administrador';
$vendedor='Vendedor';
$query_admin = $mysqli->query("SELECT * FROM empleado WHERE usuario='$user'
AND contra='$password' AND cargo='$admin'") or die($mysqli->error());
$query_ven = $mysqli->query("SELECT * FROM empleado WHERE usuario='$user'
AND contra='$password' AND cargo='$vendedor'") or die($mysqli->error());
if(mysqli_num_rows($query_admin)==1)
{
$row = $query_admin->fetch_array();
$_SESSION['user_id'] = $row['id_empleado'];
header("location: index.php");
}
else if(mysqli_num_rows($query_ven)==1)
{
header("location: index_empleados.php");
}
else
{
echo "<script>alert('Usuario o contraseña son incorrectos')</script>";
header("location: login.php");
}
}

First, there's no reason to do two queries. Just do one query to check the username and password. Then you can test $row['cargo'] to determine what kind of user they are.
So if the username and password query is found, you can do something like:
$_SESSION['cargo'] = $row['cargo'];
Then at the top of pages that should only be visible to administrators, you can do:
<?php
session_start();
if ($_SESSION['cargo'] != "Administrador") {
header("Location: index_empleados.php");
exit;
}

Related

include user ID in session

Currently my php login form will only carry acrocss the username on the session, I want this to carry across the user id (automatically created when the user registers).
As shown below I have included the user_id but it is not displaying on my webpage, the username is however.
Just wondering if anyone can help me with this? (I'm new to PHP)
Login process:
require_once('connection.php');
session_start();
if(isset($_POST['login']))
{
if(empty($_POST['username']) || empty($_POST['PWORD']))
{
header("location:login.php?Empty= Please Fill in the Blanks");
}
else
{
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if(mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];
header("location:../manage_event.php");
}
else
{
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
}
else
{
echo 'Not Working Now Guys';
}
Session on next page:
session_start();
if(isset($_SESSION['User']) || isset($_SESSION['user_id']))
{
echo ' Welcome ' . $_SESSION['User'].'<br/>';
echo ' User ID ' . $_SESSION['user_id'].'<br/>';
}
else
{
header("location:login/login.php");
}
Though your security is questionable, i’ll answer your question anyway. As stated in another response you aren’t assigning your variables the right way. See an example here
The following code will fix your problems contrary to the other solution:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
if ($result = mysqli_query($con, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id']=$row['user_id'];
header("location:../manage_event.php");
}
}else {
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
Make sure to replace this code with your old fetching code block. Thus in the first ‘else’ clause.
How about assigning the fetched result to $row:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if( $row = mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];

Managing two different SESSION in PHP

I have a table for users in my MySQL database with a tinyint value (0 or 1) which I use to determinate the category of the user.
So, at my login.php, I get the value (stored as 'admin'):
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
$isadmin = intval($row['admin']);
Then I assign the session:
if (password_verify($pwd, $row['password']) && $count==1){
if($isadmin==1) {
$_SESSION['admin_session'] = $row['userid'];
header("location: adminpanel.php");
} else {
$_SESSION['user_session'] = $row['userid'];
header("location: adminpanel.php");
}
}
And when it comes to check the session, I do this:
if (isset($_SESSION['user_session'])){
header("location: adminpanel.php");
exit;
} else if(isset($_SESSION['admin_session'])){
header("location: adminpanel.php");
exit;
}
But... It's not working. The page doesn't load and it shows a browser error message saying there are too many redirections being made. How can I do this?
I know both sessions are heading to the same "adminpanel.php". What I'm trying to do is both can access but once they're logged, depending on its category (whether they're admin or not), they'll be able to do certain stuff.
I would suggest simplifying the process and just keeping a User in the session with a flag telling you if they are an admin or not.
$query = $db->query("SELECT ..., admin FROM users WHERE email='$mail'");
$row = $query->fetch_array();
if (password_verify($pwd, $row['password'])){
$_SESSION['user'] = $row['userid'];
$_SESSION['isadmin'] = $row['admin'] == 1 ? true : false;
}
And when it comes to check the session, I do this:
if (isset($_SESSION['isadmin']) && $_SESSION['isadmin']){
header("location: adminpanel.php");
exit;
} else
// NOTE you had this redirecting exactly as above to adminpanel
header("location: userpanel.php");
exit;
}
Try to add ob_start(); on the top of your php script. I think it's because of your using header function many times.

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

$_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

how to go back to login page if given wrong php GET credentials?

so im given 3 variables on my login page from an outside source, if one of those do not belong in the database I want it to just go to the normal login.php page. as of right now it stays on that page and does not change the url even though the vars are not in the db.
i give it localhost/john/login.php?uniqueID=BmWDLlkcyU&compID=2&tempID=22
, but tempID 22 does not exist so i want it to revert to login.php
$uniqueID = $_GET['uniqueID'];
$compid = $_GET['compID'];
$tempID = $_GET['tempID'];
$checkUnique = mysqli_query($conn, "SELECT unique_id from answers WHERE unique_id = '$uniqueID' and template_id = '$tempID'");
$checkComp = mysqli_query($conn, "SELECT company_id from t_list WHERE company_id = '$compid'");
if(!$checkUnique)
{
header("Location: login.php");
exit;
}
else if(!$checkComp)
{
header("Location: login.php");
exit;
}
do this way
$checkUniquerowcount=mysqli_num_rows($checkUnique);
$checkComprowcount=mysqli_num_rows($checkComp);
and check for
if( $checkUniquerowcount > 0 && $checkComprowcount >0 )
{
}
else
{
header("Location: login.php");
exit;
}

Categories