include user ID in session - php

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'];

Related

How to validate session in 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;
}

HTML Login using PHP and mySQL issues

I am creating a web based application using HTML5, it is connected to a mySQL database. I am trying to use PHP to connect the two.
I am trying to create a login page that checks the number and password against that in the database to see if it is a valid login.
Hard coding the number and password works fine but when trying to apply it to the database I always get a 'Logged in' message even though the login credentials are invalid. I tried using both $_POST and $dbRow but to no avail.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$s_number) {
if ($_POST["passwd"]==$s_pass) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
I am very new to PHP. I have searched for other examples but there seems to be many different ways to do this that I dont understand. Any help would be much appreciated!
Try this:
<?php
include ("dbConnect.php");
if(isset($_POST["snumber"]))
{
$s_number = mysql_real_escape_string($_POST["snumber"]);
$s_pass = mysql_real_escape_string($_POST["passwd"]);
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_assoc($dbResult);
if ($dbRow["staff_number"]==$s_number && $dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
}
else {
echo "<p>Bad username and password</p>";
}
?>
PS: Go for mysqli or PDO ;) ; you can try a count or a mysql_num_rows to see if the match result is zero.
Saludos .
Adrian and Robert have addressed parts of the problem.
If you're just learning PHP then all the more reason that you should start writing your code to use the mysqli API rather than the deprecated mysql_ functions. They are almost the same - but the latter will disappear at some point in the future.
If you're writing a login page then you're presumably concerned about security - however without properly escaping your code it's trivial to bypass the control mechanism (and in some cases exposes your database to serious vandalism / disclosure issues).
Further even by fixing the SQL injection problem, it's easy to get past the authentication using session fixation.
The next mistake is that you never check if the interactions with the database are successful or not.
Hence this looks like a duplicate of this question - although I've not flagged it as such due the poor quality of the answers / discussion on that post.
Further, since you've only SELECTed rows from the database matching the username / password, why do you then compare the username and password with the data you retrieved?
It's generally considered good security practice, to NOT explain why the login failed when some provided authentication details.
So trying again....
<?php
session_start();
include ("dbConnect.php");
function auth($user, $pass)
{
$user=mysqli_real_escape_string($user);
$pass=mysqli_real_escape_string($pass);
$qry="SELECT SUM(1) AS matches
FROM YOURDB.staff_details
WHERE staff_number='$user'
AND password='$pass'";
$res=mysqli_query($qry) || die "Sorry - not available";
$r=mysql_fetch_assoc($res);
return $r['matches'];
}
if (auth($_POST["snumber"], $_POST["passwd"])) {
session_regenerate_id();
echo "<p>Logged in!</p>";
} else {
echo "<p>Sorry - invalid authentication</p>";
}
You need to use $dbRow instead of $_POST.
As currently you are just comparing $_POST with $_POST.
It's always going to be the same.
Secondly, you've specified different field names in your query and array key.
Try this.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$dbRow['staff_number']) {
if ($_POST["passwd"]==$dbRow['password']) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
EDIT: Although you don't really need to do the If Statement after.
If you're getting a result from your DB query with the Username/Password matching, the credentials are correct.
So you could do,
if (!empty($dbRow)){
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}

creating two different sessions in PHP

I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.

Undefined variable error in my PHP script

What is the problem with following code? Please help me out.
I want to match admin-id and password from the database along with login-id and password of the normal users and further want to transfer the control to the respective forms.
When I run this code it gives following errors:
Notice: Undefined variable: userstatus in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 25
Notice: Undefined variable: usertype in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 30
$query1="select user_type,user_staus from `user_info` where name='$username' and
password='$password'";
$fetched=mysql_query($query1);
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
if($userstatus==1) //if is logged in already
{
echo "Please login after some time";
exit();
}
if($usertype == 0) // if user is not an admin
{
$query1="select * from `user_info` where name='$username' and password='$password'";
$result = mysql_query($query1);
if(mysql_num_rows($result) == 1)
{
header("Location: user_form.php");
}
}
else if($usertype == 1) //if the user is a normal user
{
header("Location: admin_form.php");
}
else
{
echo "please register to login";
}
Can someone help me find the problem?
There are many problems with your code, main reason you receiving an error is because $usertype and $userstatus are not predefined and not validated.
But in my opinion it is not a main issue with your code.
There are few questions that I would like to ask you:
Why creating two loops if you need to fetch a single row?
Why querying database twice if you already know the answer?
Are you escaping $username and $password for bad characters using mysql_real_escape_string method?
here is an example how this code should look like:
$query1 = "SELECT user_type,user_staus FROM `user_info` WHERE name='{$username}' AND password='{$password}' LIMIT 1";
$fetched = mysql_query($query1);
//check if record exists otherwise you would receive another notice that can
//break redirect functionality
if (mysql_num_rows($fetched))
{
$record = mysql_fetch_assoc($fetched);
// make sure that value is integer
if ((int)$record["user_staus"])
{
exit("Please login after some time");
}
else
{
$url = (bool)$record["user_type"] ? 'admin_form.php' : 'user_form.php';
header("Location: {$url}");
exit(0);
}
}
else
{
echo "please register to login";
}
UPDATE
As suggested by nikc.org, removed 3rd level if nesting and replaced with ternary comparison
you have overlooked the scope rules ( since you have not shown full code)
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
Here $usertype and $userstatus are declared inside inner while loops { } .
ie, their scope resorts to that { } . as soon as code comes out of it the $userstatus and $usertype dies and so further accessing is not possible .
you must declare there variables ut side in global area first .

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