What am I doing wrong? (PHP and MYSQL) - php

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.

Related

Adding function to differentiate between user and admin login page

Im currently working on this project for my assignment.i need to differentiate between user and admin on the login page. What changes should i made for the login page can differentiate between the user and admin ? these codes working just fine.
index.php
<?php
require_once 'php_action/db_connect.php';
session_start();
if(isset($_SESSION['userId'])) {
header('location: http://localhost/managementsystem/dashboard.php');
}
$errors = array();
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password)) {
if($username == "") {
$errors[] = "Username is required";
}
if($password == "") {
$errors[] = "Password is required";
}
} else {
$sql = "SELECT * FROM users WHERE username = '$username'";
$result = $connect->query($sql);
if($result->num_rows == 1) {
$password = md5($password);
// exists
$mainSql = "SELECT * FROM users WHERE username = '$username' AND password='$password'";
$mainResult = $connect->query($mainSql);
if($mainResult->num_rows == 1) {
$value = $mainResult->fetch_assoc();
$user_id = $value['user_id'];
//set session
$_SESSION['userId'] = $user_id;
header('location: http://localhost/managementsystem/dashboard.php');
} else {
$errors[] = "Incorrect Username or Password combination";
}
}else {
$errors[] = "Username does not exists";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Log-in Page</title>
<!-- bootstrap -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap.min.css">
<!-- bootstrap theme -->
<link rel="stylesheet" type="text/css" href="assets/bootstrap/css/bootstrap-theme.min.css">
<!-- font awesome -->
<link rel="stylesheet" type="text/css" href="assets/font-awesome/css/font-awesome.min.css">
<!-- custom css -->
<link rel="stylesheet" href="custom/css/custom.css">
<!-- jquery -->
<script type="text/javascript" src="assets/jquery/jquery.min.js"></script>
<!-- jquery ui -->
<link rel="stylesheet" href="assets/jquery-ui/jquery-ui.min.css">
<script src="assets/jquery-ui/jquery-ui.min.js"></script>
<!-- bootstrap js -->
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row vertical">
<div class="col-md-5 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-info">
<div class= "panel-heading text-center">
<h3 class= "panel-title">MH ALLIM Management System</h3>
</div>
<div class="panel-body">
<div class="messages">
<?php if($errors) {
foreach ($errors as $key => $value) {
echo '<div class="alert alert-warning" role="alert">
<i class="glyphicon glyphicon-exclamation-sign"></i>
'.$value.'</div>';
}
} ?>
</div>
<form class="form-horizontal" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST" id="loginForm">
<div class="form-group">
<label for="inputUser3" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" name="username" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default"> <i class="glyphicon glyphicon-log-in"></i>
Sign in</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Session.php
<?php
session_start();
require_once 'db_connect.php';
//echo $_SESSION['userId'];
if(!$_SESSION['userId']) {
header('location: http://localhost/managementsystem/index.php');
}
?>
should i modify the session so the normal user cannot access to the admin page ?
Thanks :)
You should have something that makes user and admin different. So, you can simply add a new column to your table with the name "role" (for example). If the user is a User, then the role will be "user". Same thing with any Admin, the role will be "admin".
And you can write the following code to your admin's page to prevent any login from unauthorized users. Use the same code with the user's page to prevent any login from any admin to the user's page "change this part to: $_SESSION['role'] != 'user')"
<?php
session_start();
require_once 'db_connect.php';
if( (empty($_SESSION['userId'])) || ($_SESSION['role'] != 'admin') ) {
echo "<script>window.open('index.php','_self');</script>";
}
else {
$userId = $_SESSION['userId'];
}
?>
Use if and else to separate it:
if(type="admin")
{
do somethg
}
else
{
do somethg
}

PHP Header Exceptions

I have a seperate navigator.php included on top of every page that I have for public.And it has a login form.If users have an account,they can login and be sent to the current page that they are at.
I pass the current URL adress to a hidden input as it's value.And post it to giris.php(login).Then redirecting the user with Header.
But when it comes to register.php(when no sessions were set);Im trying to login there and it still sends me back to the register.php.But SESSION is being set.Thats where I need an exception and want to send user to the index.php through register.php.
navigator.php
<div id="top">
<ul class="topnav" id="myTopnav">
<li>Anasayfa</li>
<li>İletişim</li>
<li>Hakkımızda</li>
<?php
if (isset($_SESSION["giris"]))
{
echo '<li>Panel</li>
<li>Çıkış Yap</li>';
}
else
{
$url= $_SERVER["REQUEST_URI"];
echo '<li>Kayıt Ol</li>
<li id="log">
<form method="post" action="giris.php"><div id="login">
<input type="hidden" name="location" value="'.$url.'">
<input type="text" name="username" placeholder="Kullanıcı Adı" class="loginField" required>
<input type="password" name="password" placeholder="Şifre" class="loginField" required>
<input type="submit" name="login" value="Giriş" id="logBut">
</form>
</li>';
}
?>
<li class="icon">
☰</li>
</ul>
</div>
<div id="banner">
<div id="title">
<h1>Topluluk Bloğu</h1>
<br/>
<h5>Community Blog</h5>
<br/>
<?php if(isset($_SESSION["giris"])){echo '<p id="username">Hoşgeldin '.$_SESSION["kullanici"].'</p>'; }?>
</div>
</div>
giris.php
<?php
session_start();
ob_start();
include 'func/constr.php';
if(isset($_POST["login"]))
{
$kullanici = $_POST['username'];
$password = $_POST['password'];
$URL = $_POST["location"];
$query = mysqli_query($connect,"SELECT * FROM kullanicilar where kullanici_adi='$kullanici' and sifre='$password'");
$count = mysqli_num_rows($query);
if ($count == 1)
{
$_SESSION["giris"] = true;
$_SESSION["kullanici"] = $kullanici;
$_SESSION["sifre"] = $password;
header("Location:$URL");
}
else
{
$invalid = "Kullanıcı adı ya da şifre yanlış";
$_SESSION["invalid"] = $invalid;
header("Location:index.php");
}
}
ob_end_flush();
?>
try this but not tested, if your other code is ok and redirect problem then
header("Location:$URL");
to
header('Location: ' . $URL);

How to login using Bootstrap and PHP?

I am currently building a small application to manage the amount of comic books I have at the present. I am using MVC in notepad++, I would have used a framework however it isn't a large application so didn't see the need of one. I am using PHP backend and Twitter Bootstrap as the front end however I am having a snag when logging in using Sessions. I have registered using the application which works no problem however when I try to login with the credentials it just keeps loading index.php instead of login.php.
View
header.phtml
<!DOCTYPE html>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<html>
<head>
<link href="css/custom.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<title>My Comics</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body onload="initialize()" style="background-color: #D3D3D3;">
<!-- If email is does not equal email in database then remain in index page -->
<?php if (isset($_SESSION['Email']) && $_SESSION['Email'] <> ''): ?>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<?php endif; ?>
<div class="container">
<!-- If email does equal the one given in database login to profile -->
<?php if (isset($_SESSION['Email'])): ?>
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php endif; ?>
<a class="navbar-brand" href="index.html">My Comics</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
</ul>
<!-- Display logout button along with users email -->
<?php if (isset($_SESSION['Email']) && $_SESSION['Email'] <> ''): ?>
<div class="navbar-search navbar-brand pull-right">
<?php if (isset($_SESSION['Email'])): ?>
<form action="logout.php" method="post">
<!-- Welcome message for user with logout button -->
<?php if ($_SESSION['Email'] != "") echo "Welcome " . $_SESSION['Email']; ?>
<input type="submit" value="Logout" name="submit" class="btn-danger"/>
</form>
<?php endif; ?>
</div>
</div>
<!-- Login Form for users -->
<?php else: ?>
<form class="navbar-form navbar-right" action="login.php" method="post">
<div class="form-group">
<input name="Email" value="Email" id="Email" type="text" class="form-control" placeholder="Enter Username">
</div>
<div class="form-group">
<input name="Password" value="Password" id="Password" type="password" class="form-control" placeholder="Enter Password">
</div>
<button name="submit" type="submit" name="submit" id="submit" class="btn btn-default">Login</button>
</form>
<?php endif; ?>
<!--/.nav-collapse -->
</div>
</div>
<div class="container">
Model
LoginData.php
<?php
class LoginData {
protected $Name, $Email, $Password;
public function __construct($dbrow) {
$this->Name = $dbrow['Name'];
$this->Email = $dbrow['Email'];
$this->Password = $dbrow['Password'];
}
function getName() {
return $this->Name;
}
function getEmail() {
return $this->Email;
}
function getPassword() {
return $this->Password;
}
function logout() {
$_SESSION = array();
session_destroy();
}
}
LoginDataSet.php
<?php
require_once('Model/Database.php');
require_once('Model/LoginData.php');
class LoginDataSet {
protected $_dbHandle, $_dbInstance = null;
public function __construct() {
$this->_dbInstance = Database::getInstance();
$this->_dbHandle = $this->_dbInstance->getdbConnection();
}
public function fetchLoginDetails($Email, $Password) {
$Password = crypt($Password, $Email);
$sqlQuery = "SELECT * FROM users WHERE Email=:u AND Password=:p"; //basic SQL Query
$statement = $this->_dbHandle->prepare($sqlQuery); //Prepare PDO statement
//SQL Injection
$statement->execute(array(
':u' => $Email,
':p' => $Password
)); //Executes PDO statement
$dataSet = [];
while ($row = $statement->fetch()) { //Fetches the next row matching the query
$dataSet[] = new LoginData($row);
}
return $dataSet;
}
public function fetchProfileDetails($Name) {
$sqlQuery = "SELECT * user WHERE Name='" . $Name . "'";
$statement = $this->_dbHandle->prepare($sqlQuery); //Prepare PDO statement
$statement->execute(); //Executes PDO statement
$dataSet = [];
while ($row = $statement->fetch()) { //Fetches the next row matching the query
$dataSet[] = new LoginData($row);
}
return $dataSet;
}
}
?>
Controller
<?php
//session start will always be an email
session_start();
$view = new stdClass();
$view->pageTitle = 'LoggedIn';
require_once ('Model/LoginDataSet.php');
//if submit is pressed
if (isset($_POST['submit'])) {
//check the email and password against the one in the database.
$LoginDataSet = new LoginDataSet();
//if email and password matches one in the database
$view->LoginDataSet = $LoginDataSet->fetchLoginDetails($_POST['Email'], $_POST['Password']);
//get the variables below using the functions of logindataset
if (count($view->LoginDataSet) == 1) {
$_SESSION['Email'] = $_POST['Email'];
$_SESSION['Name'] = $view->LoginDataSet[0]->getName();
//continue on to profile page
header("Location:home.php");
} else {
//if incorrect return to index page with error
$_SESSION['error'] = "logindetails";
header("Location:index.php");
}
}
require_once('View/home.phtml');
This is what it looks like at the present
This is what it should look like
I had designed the website first in HTML and then dynamically in PHP which I usually do. However it isn't going to the login.php controller it just keeps refreshing index.php, Is there anything particular that anyone notices that could rectify this so it does login and also that doesn't get rid of the Name of the application and button ?
Any help would be greatly appreciated.

Different user page for multiple user level

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.

My form won't work within my bootstrap

I've written code to make a login page, this worked fine. However when I implemented it into my modified bootstrap-template, it wouldn't work anymore.
edit: it will just not give any result, if I understand firebug correctly the submit button does work but the rest of it doesn't, (atleast, it gives me an output in the firebug console) it doesn't seem to send a username or password, and it does sertainly not redirect me to the page set in action=" "
Here is my code:
<div id="login" class="container" style="color:#f7f7f7; background-color:#222222">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Login</h2>
</div>
</div>
<div class="row text-center">
<div class="col-md-4 col-md-offset-4">
<form method="POST" action="passwordunhash.php">
<p> username: <input type="text" name="username" value="username"></p>
<p> password: <input type="password" name="password" value=""></p>
<p> <input type="submit" value="Inloggen"></p>
</form>
</div>
</div>
</div>
<?php
if (empty($_POST['username']) && empty($_POST['password']) ){
echo " ";
}
else {
$query = "SELECT rank FROM users WHERE username='$username'";
if (!$resultaat = mysql_query($query) ){
$boodschap .= "query \"$query \" mislukt";
// echo "Dit is de boodschap: ".$boodschap." einde boodschap ";
echo "username not found";
}
else {
$rij = mysql_fetch_array($resultaat);
$_SESSION['rank'] = $rij["rank"];
}
$query = "SELECT password FROM users WHERE username='$username'";
if (!$resultaat = mysql_query($query) ){
$boodschap .= "query \"$query \" mislukt";
// echo "Dit is de boodschap: ".$boodschap." einde boodschap ";
echo "username not found";
}
$rij = mysql_fetch_array($resultaat);
$hash = $rij["password"];
if (password_verify($password, $hash)){
$_SESSION['loggedin'] = true;
header("Location: /index.php");
exit();
}
else {
echo 'username or password is incorrect';
session_unset();
session_destroy();
}
}
?>
this is the part I think the problem should be in.
I tried various things, including using the bootstrap form functions and leaving the action blank.
Sorry for the dutch words in it.
This is also my first question on stackoverflow, so if I missed any critical info you might need, please tell me.

Categories