Diferent user page for multiple user level.
Where should i put this code to redirect to different pages for each user level.
And maybe I have some errors. How should it be?
$_SESSION['role'] = $row['role'];
if ($_SESSION['role'] == "normalUser")
{
//do stuff here for users
header('Location: memberpage.php');
}
else if ($_SESSION['role'] == "profesor" )
{
//do extra stuff here for only profesor
header('Location: profesori.php');
} else {
header('Location: admin.php');
This is user.php
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT * FROM members WHERE username = :username AND active="Yes" ');
$stmt->execute(array('username' => $username));
return $stmt->fetch();
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$row = $this->get_user_hash($username);
if($this->password_verify($password,$row['password']) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['Fname'] = $row['Fname'];
$_SESSION['Lname'] = $row['Lname'];
$_SESSION['indeks'] = $row['indeks'];
$_SESSION['module'] = $row['module'];
$_SESSION['semester'] = $row['semester'];
$_SESSION['email'] = $row['email'];
$_SESSION['titula'] = $row['titula'];
$_SESSION['kabinet'] = $row['kabinet'];
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}
?>
This is login.php
<?php
session_start();
require_once('includes/config.php');
if( $user->is_logged_in() ){ header('Location: index.php');exit; }
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($row = $user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: memberpage.php');
exit;
} else {
$error[] = 'Погрешно корисничко име или лозинка, или вашиот акаунт не е активиран.';
}
}
$title = 'Најави се';
require('layout/header.php');
?>
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-8 col-md-6 col-sm-offset-2 col-md-offset-3">
<form role="form" method="post" action="" autocomplete="off">
<h2>Ве молиме најавете се!</h2>
<p><a href='./'>Врати се на почетна!</a></p>
<hr>
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Вашиот акаунт е активиран, можете да се најавите.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Проверете го вашето сандаче за линкот за промена на лозинка.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Лозинката е променета, можете да се најавите.</h2>";
break;
}
}
?>
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg" placeholder="Корисничко име" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control input-lg" placeholder="Лозинка" tabindex="3">
</div>
<div class="row">
<div class="col-xs-9 col-sm-9 col-md-9">
<a href='reset.php'>Ја заборавивте лозинката?</a>
</div>
</div>
<hr>
<div class="row">
<div class="col-xs-6 col-md-6"><input type="submit" name="submit" value="Најави се" class="btn btn-primary btn-block btn-lg" tabindex="5"></div>
</div>
</form>
</div>
</div>
</div>
<?php
require('layout/footer.php');
?>
Firstly I would recomend to you change attitude about roles admin / professor and everything else should be student (it's more secure, because in your case, if you forget to add role, user will be admin by default).
My second recomendation is you should validate if the user in the session is really user object and not only loggedin value. This validation shoud also be in the User class.
And login.php file code looks wrong. You have to use the User class and you should make login, session values management and checking roles exclusively through this object.
And finally your question - redirecting to specific page should be within login form processing.
Related
I read on stack overflow about flash data only valid till next server request, therefore I made new flashdata for couple of message display..
here below is the my code
This is my controller Controller
public function login(){
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required|min_length[5]');
if($this->form_validation->run() == TRUE){
$username= $this->input->post('username');
$password= $this->input->post('password');
$this->load->model('Auth_model');
$user = $this->Auth_model->get_login();
if ($user == 0) {
//echo "<script>alert('wrong username');</script>";
$this->session->set_flashdata("msg","Username does not exists");
redirect("auth/login");
}
else{
print_r($user['username']);
if($username == $user['username'] && $password == $user['password']){
$this->session->set_flashdata("success","You are logged in");
$_SESSION['user_logged'] = TRUE;
$_SESSION['username'] = $user['username'];
redirect("user/dashboard","refresh");
}
else {
//echo "<script>alert('wrong password');</script>";
$this->session->set_flashdata("msg","Password does not match.");
redirect("auth/login");
}
}
}
$this->load->view('login_v');
}
Model
public function get_login(){
$username = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
$this->db->select('*');
$this->db->from('users');
$this->db->where(array('username' => $username));
$query = $this->db->get();
$user = $query->row();
if ($this->db->affected_rows() != 1) {
return false;
}
else {
$data = array(
'user_id' => $user->user_id,
'username' => $user->username,
'password' => $user->password
);
//print_r($data);
//$this->session->set_userdata($data);
return $data;
}
}
view
<?php if(isset($_SESSION['success'])) {?>
<div class="alert alert-success"><?php echo $_SESSION['success']; ?></div>
<?php } ?>
<?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
<?php $this->session->flashdata('msg');?>
<form action="" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" name="password" id="password">
</div>
<div>
<button class="btn btn-primary" name="login">Login</button>
</div>
</form>
I want to display
$this->session->set_flashdata("msg","Username does not exists");
but my if else is just doing redirect, the commented script tag works fine though.
How to make "msg" work?
Thanks in advance.
please add echo statement in the view like
<?php echo $this->session->flashdata('msg');?>
OR
<?=$this->session->flashdata('msg')?>
It should be like this :
Get your flashdata by using its key, Should be like this
<?php if(!empty($this->session->flashdata('msg'))) {?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata('msg'); ?>
</div>
<?php } ?>
Or simply do like this:
<div class="alert alert-success"><?php echo $this->session->flashdata('msg'); ?></div>
For more : https://www.codeigniter.com/user_guide/libraries/sessions.html
I have a small web application with smarty template engine. The login is in the header.tpl. Login & Logout are working fine, but they need a page reload to see the changes in the header. Any ideas why this happens? I think there is no caching activated.
header.tpl
{if isset($user) }
<form class="logoutform col-md-12 nopadding" method="post">
<div class="col-md-10"><p class="welcometext">Hello {$user.username}!</p></div>
<div class="hidden"><input type="hidden" name="action" value="logout"></div>
<div class="col-md-2"><button type="submit">Logout</button></div>
</form>
{else}
<form class="loginform col-md-12 nopadding" method="post">
<div class="col-md-5"><input type="text" placeholder="Username" name="username"></div>
<div class="col-md-5"><input type="password" placeholder="Password" name="password"></div>
<div class="hidden">
<input type="hidden" name="action" value="login">
</div>
<div class="col-md-2"><button type="submit">Login</button></div>
</form>
{/if}
function login & logout in der page.class.php
function logout()
{
session_destroy();
//header('Location: '.BASEURL);
}
function login($username, $password)
{
$pdo = new PDO('mysql:host='.HOST.';dbname='.DATABASE, USER, PASSWORD);
$statement = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$result = $statement->execute(array('username' => $username));
$user = $statement->fetch(PDO::FETCH_ASSOC);
//DB Abfrage in user class exportieren? checkUserLogin, dann return true oder errormeldung
if ($user == false || password_verify($password, $user['password']) == false) {
$loginerror = 'username or password wrong';
}
else {
if ($user['email_confirmed']==0) {
//$this->assign('error', 'Please confirm your e-mail adress.');
$loginerror = 'please confirm your e-mail adress.';
}
else {
//$_SESSION['loggedUser'] = $user['id'];
$_SESSION['user'] = $user;
return true;
}
}
$this->assign('loginerror', $loginerror);
}
}
Yes, as any web application on server side. You have to do a redirect at the end of the login, something like header('Location: '.$yourLoginPageUrl); to force the refresh.
I have this code here which I have been using in several projects without any issue. The only thing i've changed is that I am using MAMP instead of XAMPP for this.
The problem I'm facing is the code runs without any errors (it runs through the if else statement in the login functions, but nothing happens (it doesn't redirect the user) and if I input wrong details it shows that no records are found. Can someone guide me through this please?
Login.php
<?php
session_start();
if (!empty($_SESSION['admin'])&&!empty($_SESSION['type'])) {
header("Location: admin/index.php");
}
elseif (!empty($_SESSION['user'])&&!empty($_SESSION['type'])) {
header("Location: user/");
}
?>
<!--===== LOGIN =====-->
<section id="login" class="padding" style="padding-top: 200px;">
<div class="container">
<div class="row">
<div class="col-md-12 text-center">
<div class="profile-login">
<div class="login_detail" style="margin-top:-50px;">
<!-- Tab panes -->
<div class="tab-content">
<h1>
<?php
extract($_POST);
if (isset($btn) && !empty($username) && !empty($password)) {
require 'includes/users.php';
login();
}
?>
</h1>
<div role="tabpanel" class="tab-pane fade in active" id="profile">
<h2>Login Below</h2>
<div class="agent-p-form">
<div class="row">
<form class="callus" action="login.php" method="POST">
<div class="col-md-12">
<div class="single-query">
<input name="username" type="text" class="keyword-input" placeholder="Username" required>
</div>
<div class="single-query">
<input name="password" type="password" class="keyword-input" placeholder="Password">
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12 text-center">
<div class="query-submit-button">
<button name="btn" type="submit" class="btn_fill">Login</button>
</div>
</div>
</form>
Users.php
<?php
function login()
{
require 'connect.php';
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
$pass = $password;
$sql = "SELECT * FROM `users` WHERE `username`='$username' AND `password`='$pass'";
$query = mysqli_query($con,$sql);
$row = mysqli_num_rows($query);
if ($row == 0) {
echo "<b style='font-size:12px; color:#FFF'>Wrong Username/Password Combination</b>";
}
elseif ($row == 1) {
$fetch = mysqli_fetch_array($query);
$type = $fetch['user_role'];
$name = $fetch['username'];
if ($type == "Administrator") {
#session_start();
$_SESSION['user_role'] = $type;
$_SESSION['admin'] = $name;
header("Location: admin/index.php");
}
elseif ($type=="User") {
#session_start();
$_SESSION['user_role'] = $type;
$_SESSION['user'] = $name;
header("Location: user/");
}
else{
echo "<b>Error</b>";
}
}
else{
echo "<b>Error</b>";
}
}
Fixed it: The problem was with the header.. it was not loading it because the output was already started, the solution was to group all the PHP at the start of the page and put the include partial/header at the very bottom of the php so that no whitespace or output can be read before the header executes.. thus the script works perfectly now, I wish to thank you all for giving me guidance to get to this desired solution!
<?php
session_start();
if (!empty($_SESSION['admin'])&&!empty($_SESSION['type'])) {
header("Location: admin/");
}
elseif (!empty($_SESSION['user'])&&!empty($_SESSION['type'])) {
header("Location: user/");
}
extract($_POST);
if (isset($btn) && !empty($username) && !empty($password)) {
require 'includes/users.php';
login();
}
include "partials/header.php";
?>
You already start a session in Login.php. Please remove #session_start(); from Users.php.
I want to display an error if a username exists, however no error is being thrown.
the function is on the User.php and im trying to display an error from that function.
i referenced this, however it is not relevant to the OOP way.
User.php
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$row['user_name'] == $username;
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Index.php
<?php
session_start();
require_once 'User.php';
$guest = new User();
if($guest->is_logged())
{
$guest->redirect('profile');
}
if (isset($_POST['btn_signup']) ){
$username = htmlentities($_POST['txt_username']);
$unpass = htmlentities($_POST['txt_password']);
$password = password_hash($unpass, PASSWORD_BCRYPT, ['cost' => 12] );
$unemail = $_POST['txt_email'];
$email = filter_var($unemail, FILTER_VALIDATE_EMAIL);
$guest = new User();
if($email == ""){
$errors[]= "Enter a Email";
}
if($username == ""){
$errors[]= "Enter a Username please";
}
if($password == ""){
$errors[]= "Enter a Password";
}
if($guest->check_user_exists($username)){
$errors[]= "Username Already Taken";
}
if($guest->signup($email,$password,$username)){
$guest->redirect('profile');
die('didnt redirect');
}
else{
$errors[]= "Invalid Entry";
}
}
$title = "Home";
require_once 'layouts/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-6">
<?php
if(isset($errors))
{
foreach($errors as $error)
{
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
}
}
else if(isset($_GET['joined']))
{
?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered <a href='index.php'>login</a> here
</div>
<?php
}
?>
<h1>Sign Up</h1>
<form action ="" method="POST">
<div class="form-group">
<label for="Email">Email address</label>
<input type="email" class="form-control" aria-describedby="emailHelp" name="txt_email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="Username">Username</label>
<input type="text" class="form-control" aria-describedby="emailHelp" name="txt_username" placeholder="Enter Username">
</div>
<div class="form-group">
<label for="Password">Password</label>
<input type="password" class="form-control" aria-describedby="emailHelp" name="txt_password" placeholder="Enter password">
</div>
<button type="submit" name="btn_signup" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
public function check_user_exists($username)
{
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username'=>$username));
return $stmt->fetchColumn() > 0; // fetchColumn return the number of rows selected
}
catch(PDOExeception $e)
{
echo $e->getMessage();
}
}
Your function doesn't actually return or do anything. Return the result of fetch(), if it returns true - a result was found. If it returns false, there was no row matching the username. You don't need to check anything after that, as the fetch() method will only be true if a result was found.
Adjusted for that, your function would look like this
public function check_user_exists($username) {
try{
$stmt = $this->db->prepare("SELECT user_name FROM users WHERE user_name=:username");
$stmt->execute(array(':username' => $username));
return $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOExeception $e) {
echo $e->getMessage();
}
}
Also, its not a good idea to output errors directly (on a testing/development environment its fine, but on a live environment you should log it (error_log()) instead.
http://php.net/manual/en/pdostatement.fetch.php
public function ifUserAlreadyExist(string $email):bool{
$sql = "SELECT 1 FROM users WHERE email= :Email";
$statment = $this->conn->prepare($sql);
if (false === $statment) {
return false;
}
$statment->execute([':Email' => $email]);
return (bool)$statment->fetchColumn();
}
//You need to just select 1 object if is already exist and in this case function hint will be so handy, can set the function to boolean and see if it return true or false.
I hope I could help.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
i was trying to make from scratch a PDO, OOP user/register system in PHP and i got stucked in the point where I don't understand why I it's trowing me the handle request error.
This is my index.php file with login and register:
<?php
require_once('inc/config.php');
if($user->is_loggedIn()!="") {
$user->redirect('account.php');
}
// login
if(isset($_POST['login-submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username, $password)) {
$user->redirect('account.php');
}
else {
$error[] = "Username or Password are not correct!";
}
}
//register
if(isset($_POST['register-submit'])) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if($username == "") {
$error[] = "You need to specify a username!";
}
else if($password == "") {
$error[] = "Please add a password!";
}
else if(strlen($password) < 6) {
$error[] = "Password must have at least 6 characters";
}
else {
try {
$stmt = $db_connection->prepare("SELECT username FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
// execute(array(':user_name'=>$username));
$row->$stmt->fetch(PDO::FETCH_ASSOC);
if($row['username'] == $username) {
$error[] = "Sorry, this username is already taken!";
}
else {
if($user->register($username, $password)) {
$user->redirect('index.php?success');
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Login/Register</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-login">
<div class="panel-heading">
<div class="row">
<div class="col-xs-6">
Login
</div>
<div class="col-xs-6">
Register
</div>
</div>
<hr>
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<?php
if(isset($error)) {
foreach($error as $error) {
?>
<div class="alert alert-danger">
<i class="glyphicon glyphicon-warning-sign"></i> <?php echo $error; ?>
</div>
<?php
// end for each
}
// end of if statement
} else if(isset($_GET['success'])) { ?>
<div class="alert alert-info">
<i class="glyphicon glyphicon-log-in"></i> Successfully registered! You can now log in!
</div>
<?php } ?>
<form id="login-form" action="#" method="post" role="form" style="display: block;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group text-center">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="login-submit" id="login-submit" tabindex="4" class="form-control btn btn-login" value="Log In">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-lg-12">
<div class="text-center">
</div>
</div>
</div>
</div>
</form>
<form id="register-form" action="#" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="username" id="username" tabindex="1" class="form-control" placeholder="Username" value="">
</div>
<div class="form-group">
<input type="password" name="password" id="password" tabindex="2" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="row">
<div class="col-sm-6 col-sm-offset-3">
<input type="submit" name="register-submit" id="register-submit" tabindex="4" class="form-control btn btn-register" value="Register Now">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
<script src="js/tabs.js"></script>
</body>
</html>
This is my config.php:
<?php
session_start();
//set timezone
date_default_timezone_set('Europe/Copenhagen');
//database credentials
define('DBHOST','localhost');
define('DBUSER','admin');
define('DBPASS','Ddy6MUXhtUz3mNpE');
define('DBNAME','notes_app');
//application address
define("BASE_URL","/");
define("ROOT_PATH",$_SERVER['DOCUMENT_ROOT'] . "/");
try {
$db_connection = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(Exception $e) {
echo "Connection failed " . $e->getMessage();
die();
}
include_once('models/user.php');
$user = new User($db_connection);
And this is my user model:
<?php
class User {
private $db;
function __construct($db_connection) {
$this->db = $db_connection;
}
public function register($username, $password) {
try {
$crypted_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO users(username, password) VALUES(:user_name, :user_pass)");
$stmt->execute(array(":user_name"=>$username, ":user_pass"=>$crypted_password));
return $stmt;
}
catch(Exception $e) {
echo $e->getMessage();
}
}
public function login($username, $password) {
try {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($username, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['id'];
return true;
}
else {
return false;
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
public function is_loggedIn() {
if(isset($_SESSION['user_session'])) {
return true;
}
}
public function redirect($url) {
header("Location: $url");
}
public function logout() {
session_destroy();
unset($_SESSION['user_session']);
return true;
}
}
I was trying for several hours to find the problem but unfortunately I couldn't find it, I cannot neither print the var_dump because my browser is receiving the internal error 500.
The problem is because of the following lines:
In your login() method of User class,
if(password_verify($username, $userRow['password'])) { ...
And on index.php page, during the processing of registration form,
$row->$stmt->fetch(PDO::FETCH_ASSOC);
So your login() method should be like this:
public function login($username, $password) {
try {
$stmt = $this->db->prepare("SELECT * FROM users WHERE username=:user_name");
$stmt->bindParam(':user_name', $username);
$stmt->execute();
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['id'];
return true;
}else{
return false;
}
}
}
catch(Exception $e) {
echo $e->getMessage();
}
}
And change this line
$row->$stmt->fetch(PDO::FETCH_ASSOC);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);