I'm able to successfully create sessions and run them and it works fine in pages exclusive to those particular users.
For example, if there are 8 pages for admin then those 8 pages will contain the code which checks only for the admin session from the admin class.
But if there is a page where all three have the user permission to, which will be the login page I'm unable to handle three sessions together for three separate users. When I am already logged in to the system using any one of the users and then try to go to the login page it should automatically redirect me to that user's exclusive home page. But instead it asks me to enter the login credentials again.
My PHP code:
<?php
if(isset($_SESSION['p_login'])){
header("location:login_tests/Patient.php");
}
else if(isset($_SESSION['d_login'])){
header("location:login_tests/Doctor.php");
}
else if(isset($_SESSION['a_login'])){
header("location:admin/Dashboard.php");
}
// Login functionalities
if(isset($_POST['submit1'])){
// Patient login
if($_POST['users']=="patient"){
session_start();
include_once 'classes/patient.php';
$patient = new Patient();
if ($patient->p_session())
{
header("location:login_tests/Patient.php");
}
$patient = new Patient();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$login = $patient->p_login($_REQUEST['username'],$_REQUEST['password']);
if($login){
header("location:login_tests/Patient.php");
}
else
{
echo "<script>alert('Login Failed!');</script>";
}
}
}
// Doctor login
else if($_POST['users']=="doctor"){
session_start();
include_once 'classes/doctor.php';
$doctor = new Doctor();
if ($doctor->d_session())
{
header("location:login_tests/Doctor.php");
}
$doctor = new Doctor();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$login = $doctor->d_login($_REQUEST['username'],$_REQUEST['password']);
if($login){
header("location:login_tests/Doctor.php");
}
else
{
echo "<script>alert('Login Failed!');</script>";
}
}
}
// Admin login
else{
session_start();
include_once 'classes/admin.php';
$admin = new Admin();
if ($admin->a_session())
{
header("location:admin/Dashboard.php");
}
$admin = new Admin();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$login = $admin->a_login($_REQUEST['username'],$_REQUEST['password']);
if($login){
header("location:admin/Dashboard.php");
}
else
{
echo "<script>alert('Login Failed!');</script>";
}
}
}
}
// Registration functionalities
else if(isset($_POST['submit2'])){
include_once 'classes/patient.php';
$patient = new Patient();
if ($_SERVER["REQUEST_METHOD"] == "POST"){
$register = $patient->p_register($_REQUEST['name'],$_REQUEST['gender'], $_REQUEST['dob'], $_REQUEST['nic'], $_REQUEST['address'],$_REQUEST['email'], $_REQUEST['username'], $_REQUEST['password']);
if($register){
echo "<script>alert('Registration Successful!');</script>";
}
else
{
echo "<script>alert('Entered email address or username already exists!');</script>";
}
}
}
?>
If I understand you correct, your problem is the 3 session variables $_SESSION['p_login'], $_SESSION['d_login'] and $_SESSION['a_login'].
There is no need to use 3 separate variables, use 1: $_SESSION['user'] = value.
Give it a value according to permission (e.g. patient=1, docter=2, admin=3). Then you only have to test:
if( $_SESSION['user'] < 2 ) only permission for patient pages.
if( $_SESSION['user'] < 3 ) permission for patient pages + docter pages.
if( $_SESSION['user'] < 4 ) permission for all pages.
Related
How can I make a system of access levels for the user after making the login and soon a session is established?
I need to do with this code~
// Login logic
function process_login($user, $pass, AuthMeController $controller) {
if ($controller->checkPassword($user, $pass)) {
printf('<h1>Hello, %s!</h1>', htmlspecialchars($user));
echo 'Successful login. Nice to have you back!';
session_start();
$_SESSION['UserSession'] = array($user['default'], $user['GM']);
//header('Location: https://mysite');
echo "<br /><a href='../index.php'>Back to Form</a>";
return true;
} else {
echo '<h1>Error</h1> Invalid username or password.';
header('Refresh: 5; URL=https://mysite');
}
return true;
}
I've a login page, where I'm setting the admin ID as a session variable
$_SESSION['adminUserId'] = $row['id'];
Now I've a header.php file which is called first on every page. To display the header.
And the first line of Header.php has
if (!isset($_SESSION['adminUserId'])) {
header("Location: ../index.php");
}
Now the strange part about this is, while I'm doing echo $_SESSION['adminUserId']), it displays the value of the variable. But when I'm checking the variable with isset, the result is false. I'm unable to understand this, as how this is happening.
Also, another strange thing, include header.php is the first line of code for every page, it works fine for all the pages apart from one, where it redirects the user to index.php
I've tried changing the variable name, setting the variable in a different way. But doesn't work for the specific page.
if (!isset($_SESSION['adminUserId'])) {
header("Location: ../index.php");
}
The expected result for a logged in user should be true but for a not logged in user it should be false, but it is showing vice versa
index.php (Here the session is getting set)
$qry = $DB_con->prepare("SELECT * FROM user WHERE username = '".$username."' AND password = '".$password."' AND role ='".$role."' AND country ='".$country."'");
$qry->execute();
$admin = $qry->fetchAll(PDO::FETCH_ASSOC);
// print_r($admin);
if($admin){
foreach($admin as $row)
{
if($username==$row['username'] && $password==$row['password'] && $role == 'Admin')
{
$country = $row['country'];
$_SESSION['Country'] = $country;
$DEO_id = $row['id'];
$_SESSION['adminUserId'] = $DEO_id;
$session_role = $row['role'];
$_SESSION['session_role'] = $session_role;
$usernameAdmin = $row['username'];
$_SESSION['city'] = $usernameAdmin;
$_SESSION['isAdminLoggedIn'] = "True";
header('location:admin/dashboard.php');
}
elseif($username==$row['username'] && $password==$row['password'] && $role == 'Data Entry User')
{
$DEO_id = $row['id'];
$_SESSION['dataEntry_ID'] = $DEO_id;
$country = $row['country'];
$_SESSION['Country'] = $country;
$session_role = $row['role'];
$_SESSION['session_role'] = $session_role;
header('location:data_operator/dashboard.php');
}
else
{
$error = "Invalid Username or Password.";
}
}
}
{
$error = "Invalid Username or Password.";
}
dashboard.php (Where the header.php is called and code works fine)
<?php include('header.php');
include('../include/dbcon.php');
?>
Now there's another link in the dashboard page
<a href="new-registration.php" class="btn btn-success btn-icon-split" style="width:100%">
<span class="text">New Registration</span>
</a>
When I see the new-registration.php page, this is how it looks like
<?php include('header.php');
include('../include/dbcon.php');
?>
And now the final header.php(where all this action is taking place)
<?php
include('../include/dbcon.php');
if(!isset($_SESSION['adminUserId']))
{
header("Location: ../index.php");
}
?>
I need to control a session in a REST API. My REST API is implemented with slim and doctrine and within the routes.php file I have defined the POST request of the login:
session_start();
$app->post('/login', function ($request, $response) {
$em = getEntityManager();
$args = $request->getParsedBody() ?? json_decode($request->getBody(), true);
$user = $em->getRepository(Usuario::class)->findOneByUsername($args['username']);
if (null == $user) {
echo "<script language='javascript'>alert('User not found'); window.location='App.php'</script>" ;
} else {
if ($user->getPassword() == $args['password']){
$_SESSION['id'] = $user->getId();
$_SESSION['username'] = $user->getUsername();
if($user->getAdmin() && $user->getEnabled()){
echo "<script language='javascript'>window.location='Admin.php'</script>" ;
} else if($user->getEnabled()){
echo "<script language='javascript'>window.location='Comparator.php'</script>" ;
} else {
echo "<script language='javascript'>alert('Account
inabilited'); window.location='App.php'</script>" ;
}
} else {
echo "<script language='javascript'>alert('Incorrect Password'); window.location='App.php'</script>" ;
}
}
});
I have 3 page .php. In page App.php I have an access form. I want to do is that when any user wants to enter the Admin or Comparator page, he can not enter without logging in previously.
For this I have added the following code to the pages previously named:
<?php if (session_status() != "PHP_SESSION_ACTIVE" && session_status() != 2) { ?>
<script>window.location='App.php'</script>
<?php }?>
But when entering a valid username and password I get the following error:
It's very weird because the field username in the class Usuario exists.
Any solutions?
In my program i want when the session is time out after entering the login details again back to the previous page for this i am doing like this
index.php:
$PAGE_TITLE = "Sign In...";
getTitleSetting('Super');
divertAdminUser();
$index_local_url =$_SERVER['HTTP_HOST'].'/TicketRoom/public_html/test/users/index.php';
$redirect_url = $_SERVER['HTTP_REFERER'];
if(isset($_POST['seller_password']) && isset($_POST['seller_email']) && $_POST['seller_submit_x'] != '' && $_POST['seller_submit_y'] != ''){
$password=$_POST['seller_password'];
$username=check_input($_POST['seller_email']);
$db=new DbConnect($DB_HOST, $DB_USERNAME, $DB_PASSWORD, $DB_NAME,$DB_REPORT_ERROR, $DB_PERSISTENT_CONN);
$db->open() or die($db->error());
if(authenticateUser($password, $username, $db)){
$seller_id =$_SESSION['SESS_v_seller_id'];
$select_email_query=mysql_query("select * from ".TK_SELLER_USERS." where id='".$seller_id."'");
$row_seller_id = mysql_fetch_array($select_email_query);
$trading_status = $row_seller_id['status'];
$_SESSION['SESS_v_usertype'] = $row_seller_id['user'];
if($redirect_url == $index_local_url)
{
if($trading_status == "Active-pending")
{
header("location:reset_password.php");
exit;
}
else
{
if($row_seller_id['user'] == "Affiliate")
{
if($_SESSION['sts_aff'] == "P")
{
header("location:dashboard/awaiting_approval.php");
exit;
}
else
{
header("location:dashboard/current.php");
exit;
}
}
else if($row_seller_id['user'] == "Performer")
{
header("location:accountsettings/performer_index.php");
exit;
}
else if($row_seller_id['user'] == "Venu_owner")
{
// header("location:https://example.com/test/users/accountsettings/performer_index.php");
header("location:accountsettings/performer_index.php");
exit;
}
else
{
header("location:dashboard.php");
exit;`
}
}
}
else
{
header("location:".$redirect_url);
}
}
else{
$_SESSION['sess_msg'] = "Authentication failed!";
$_SESSION['sess_class']='err';
header ("Location: index.php");
exit;
}
}
i am trying to get back to previous page but it is not working properly when session time out its come back to login page
here my $redirect_url = some previous page($_SERVER['HTTP_REFERER'])
again entering the login details my $redirect_url change to login page url
$redirect_url = login page($_SERVER['HTTP_REFERER'])
so its repeat the same page and i want only for session time out not for the logout how can i do it can you explain please.
When you check the session at if session is not stored then create temp session variable and store the current URL in that.
After user login check if temp session variable is set or not. If set then get the value of that variable and redirect to that page else continue with profile / dashboard page.
I was wondering if anyone could help me - I have successfully created a log in system allowing a user (student) to log in. My system also requires an admin log in, with the admin having privileges to view pages that the student does not. Both the admin and student information comes from two different tables. Below is the code I have used for the student log in (there are two different pages - users and login). I am stuck as to how to implement the admin log in. Any help is appreciated!
(Admin will log in using 'adminnum' and 'adminpassword'.
login.php
<?php
include "core/init.php";
include "includes/content.php";
if (empty($_POST) === false) {
$studentemail = $_POST ['studentemail'];
$studentpassword = $_POST ['studentpassword'];
if (empty($studentemail) === true || empty($studentpassword) === true) {
$errors[] = "You need to enter an email address and password";
} else if (user_exists($studentemail) === false) {
$errors[] = "We can't find that email address. Have you registered?";
} else {
if (strlen($studentpassword) > 32) {
$errors[] = 'Password too long';
}
$login = login($studentemail, $studentpassword);
if ($login === false) {
$errors[] = 'That email/password combination is incorrect';
} else {
$_SESSION['studentid'] = $login;
header('Location: index.php');
exit();
}
}
} else {
$errors[] = 'No data received';
}
include "includes/overall/overall_header.php";
if (empty($errors) === false) {
?>
<h2> We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
?>
<center><input id="submit" type="submit" value="Back" onclick="location.href='Login2.php'"></center>
<?php
include "includes/overall/overall_footerloggedout.php";
?>
users.php
<?php
function logged_in() {
return (isset($_SESSION['studentid'])) ? true : false;
}
function user_exists($studentemail) {
$studentemail = sanitize($studentemail);
$query = mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail`
= '$studentemail'");
return (mysql_result($query, 0) == 1) ? true : false;
}
function studentid_from_student ($studentemail) {
$studentemail = sanitize($studentemail);
return mysql_result(mysql_query("SELECT `studentid` FROM `student` WHERE `studentemail` = '$studentemail'"), 0, 'studentid');
}
`function login($studentemail, $studentpassword) {
$studentid = studentid_from_student($studentemail);
$studentemail = sanitize($studentemail);
$studentpassword = md5($studentpassword);
return (mysql_result(mysql_query("SELECT COUNT(`studentid`) FROM `student` WHERE `studentemail` = '$studentemail' AND `studentpassword` = '$studentpassword'"), 0) == 1) ? $studentid : false;
}
?>
I suggest to change your logic, extracting users and admins from two different table. Make them in only one table, but all users should contain column flag for example, where flag=1 is ADMIN and flag=0 is USER.
all i can suggest as i am not a php coder but have done some in the past is to add another field in your database where you will set levels of privileges for users (0 for normal members, 1 for admin). After you have done that just add it to your users script through php coding which i barely know. Hope that helps a little bit.