PHP $_Session variable not recognised
I'm trying to differentiate between an admin user and a client with the session variable. Depending on their user type, they will be shown different content of the page. In order to do that, I wanted to check the user's type in the database depending on the $_SESSION after login. It's not an ideal solution but the simplest I can think of, yet I still can't get this to work. Database table holding user details is called LS_Users and the field storing user type (values: either "A" for admin or "C" for client) is called userType.
The problem I'm having is that the user type is not being picked up properly.
开发者_C百科The code below doesn't read the user type.
$usertype = isset($_POST['userType']) ? $_POST['userType'] : $_SESSION['userType'];
$usertype=$_POST['user_type'];
$thisuserSQL="select * from LS_Users where userType = '".$usertype."'";
$exethisuserSQL=mysql_query($thisuserSQL) or die (mysql_error());
$userArray=mysql_fetch_array($exethisuserSQL);
if ($userArray['userType']!=$usertype)
{
echo "Usertype: ".$_SESSION['userType'];
}
else
{
echo "Usertype: empty";
}
And the code below returns the first value from the database instead of matching it to the actual user that logged in.
if ($_SESSION['c_userid'])
{
echo "Name: ".$_SESSION['c_fname'].", Id: ".$_SESSION['c_userid'], "Usertype: ".$_SESSION['userType'];
echo "<hr>";
$usertype = $_REQUEST['userType'];
$currentuserSQL="select * from LS_Users";
// where userType =" '$usertype';
$execurrentuserSQL=mysql_query($currentuserSQL) or die (mysql_error());
$userArray=mysql_fetch_array($execurrentuserSQL);
$_SESSION['c_userid']=$userArray['user_id'];
$_SESSION['userType']=$userArray['userType'];
echo "<p>Hello, ".$_SESSION['c_fname']."! ";
if ($_SESSION['userType']== "C")
{
echo "<p>Client";
}
elseif ($_SESSION['userType']== "A")
{
echo "<p>Admin";
}
else
{
echo "<p>Empty";
}
}
else
{
echo "Please log in.";
}
Many thanks for your help
Did you include the magical session_start();
function into your code?
Put it in the very beginning of every file which uses sessions:
<?php
session_start();
...
If the problem only happens for the userType
, I would like to verify that your php configuration does not have the register_globals
activated. If it does, it might be the source of your problems. Otherwise, please answer the following questions:
Are you sure the other session variables are working?
Are you sure the initialization of the $_SESSION['userType']
is working?
Can you write it after having initialized it?
精彩评论