creating two different sessions in PHP - 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.

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

How to show, edit user profile when logged in with php

Please i want logged in user to be able to view and edit their previous details in a mysql database..here is my code so far
<?php session_start(); include 'dpconfig.php';
if (isset($_SESSION['uid']))
{
echo $_SESSION['uid'];
}
else
{
echo "You are not Logged In!"; header("Location: header.php");
}
$n = mysqli_query($conn,"Select * from user");
$run = mysqli_query($conn,"Select * from user");
$row = mysqli_fetch_array($run, MYSQLI_BOTH);
{
$showid = $row[0];
$showfirst = $row[1];
$showlast = $row[2];
$showuid = $row[3];
echo $showid;
echo $showfirst;
}
?>
Thanks
What you need to do when your user have log in you then need to have links in the dashboard to profile page then you need to have a query string in your link
eg
<?php
session_start();
include 'dpconfig.php';
if (isset($_SESSION['uid']))
{
echo $_SESSION['uid'];
echo "<a href=\"profile.php?id=".$_SESSION['uid']."&action=view\">View Profile<a/>";
echo "Edit Profile";
}else{
// not allowed redirect
}
?>
The above code is just a basic dashboard after the user have loggedin, we display to links to profile.php with two query string parameters, namely id we will use this to identify the current user, and action, this one will help us to know what action the user is doing(viewing/editing) their profile
Then once they on any of the link, it will go to the profile.php page with url params. then we use GET method to do our proccessing
Read about Get method here
profile.php
<?php
session_start();
include 'dpconfig.php';
if(isset($_GET['id']) && isset($_GET['action'])){
if($_GET['action'] === "view"){
// show user profile
}
if(isset($_GET['action']) ==="edit"):?>
show html form with profile info to edit then process
<?php
endif;
}else{
// not allowed do something
}
?>
Hope this will atleast point you to the correct direction.

Login even if the user not registered with us in data base

Please help me for the following code of my login1.php file as a result of which when some user who is even not registered in our data base, if fill any information or no information as username and password shows has logged in. while it should only be logged in after matching its data from database and should go to commonfile.php.
my code is as under :
<?php
ob_start();
session_start();
include "backoffice/include/config.php";
$user=$_REQUEST['user'];
$pass=$_REQUEST['pass'];
$id=$_REQUEST['id'];
$pid=$_REQUEST['pid'];
$curr=$_REQUEST['curr'];
$reqtype = $_REQUEST["window"];
// echo $curr;
//$link_name=$_REQUEST['id'];
$query=mysql_query("select * from member where email='".addslashes($user)."' and password ='".addslashes($pass)."' and status='Yes'");
$counts = mysql_num_rows($query);
$rows = mysql_fetch_array($query);
$_SESSION['uid']= $rows['id'];
$_SESSION['userid']=$rows['email'];
$_SESSION['user']=$rows['email'];
if(!isset($_SESSION['user'])){header("location:index.php");exit;}
if(!isset($_SESSION['session_id']))
{
if(isset($reqtype) && $reqtype=="offline")
{
header("location:offline.php?id=$user");
}
else
{
header("location:commonfile.php");
}
}else{
if($count!="" )
{
header("location:signin.php?mess=error");
}else{
//header("location:place_order.php?id=$id&pid=$pid#mess");//
header("location:commonfile.php");
}
}
You have $_SESSION['uid']= $rows['id']; so even if $rows is empty (which should give you at least a warning) checking for if(!isset($_SESSION['user'])) will always be false, because $_SESSION['uid']; is set.
Instead you should check if $counts > 0.
Also you should only set the $_SESSION variables when $counts > 0.
Last but not least using the mysql_ functions is considered deprecated.
Please look into PDO it is a lot more secure.

Query and Fetch Comparison SQLite

I'm just creating a simple login script to check the username/password, if there's a match with the database then it'll login. I think I have most of it, it opens up the database, grabs username/pw from the login. I think I set up my query right also that it grabs the username and pw. How would I go about comparing it? I've been stuck on this for quite a while. My fetch isn't working correctly also, it gives me an error. I'm very new to SQLite/Databases so this may seem very bad code but I'm trying my best.
<?php
//opens database
class MyDB extends SQLite3
{
function __construct()
{
$this->open('UserAccounts.db');
}
}
$db = new MyDB();
//username and pw from index.html
$user = $_REQUEST['myusername'] ;
$pw = $_REQUEST['mypassword'] ;
//if there is a database, it opens.
if(!$db){
echo $db->lastErrorMsg();
} else {
//Test to see if things are working correctly.
echo "Opened database successfully\n";
echo "$user";
echo "$pw";
}
$result = $db->query("SELECT * FROM login WHERE user = '$user' AND password = '$pw'");
if ($result->fetchColumn() == $user) {
$_SESSION['loggedin'] = true;
echo "Success";
};
if(!$_SESSION['loggedin']){
echo "Didn't Work";
exit;
};
Probably looks like this:
$fromDB = $result->fetchArray();
if ($fromDB['user'] == $user) {

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 .

Categories