Page restrictions with normal user and admin - php

Well, on my small site, which I use for practice I created pages where I saved my data from tables from the database, also, I have normal users and admin. I created admin through my sql and I can create a normal user through a registration form on the page. What I want to do is, As I said I have a page where I saved my data from tables, I want to make so user cant see that page while admin can see that page. I just want to make those restrictions. However, I don't know how to start with that in code, I will post here the code that I think you will need for helping me, so, If you need something more, I'm here!
login.php: `
<?php include('functions.php') ?>
<!DOCTYPE html>
<html>
<head>
<title>Prijavi se</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="header">
<h2>Prijavi se</h2>
</div>
<form method="post" action="login.php">
<?php echo display_error(); ?>
<div class="input-group">
<label>Korisnicko ime</label>
<input type="text" name="username" >
</div>
<div class="input-group">
<label>Lozinka</label>
<input type="password" name="password">
</div>
<div class="input-group">
<button type="submit" class="btn" name="login_btn">Prijavi se</button>
</div>
<p>
Jos uvek nemate nalog? Registruj se
</p>
</form>
`
functions.php: `
$db = mysqli_connect('localhost', 'root', '', 'it210projekat');
$username = "";
$email = "";
$errors = array();
if (isset($_POST['register_btn'])) {
register();
}
if (isset($_POST['login_btn'])) {
login();
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: ../login.php");
}
function register(){
global $db, $errors;
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
if (empty($username)) {
array_push($errors, "Unesite ime");
}
if (empty($email)) {
array_push($errors, "Unesite email");
}
if (empty($password_1)) {
array_push($errors, "Unesite lozinku");
}
if ($password_1 != $password_2) {
array_push($errors, "Lozinke se ne poklapaju");
}
if (count($errors) == 0) {
$password = md5($password_1);
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "Uspesno ste napravili nalog!!";
header('location: login.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id);
$_SESSION['success'] = "Uspesno ste se prijavili";
header('location: login.php');
}
}
}
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
function login(){
global $db, $username, $errors;
$username = e($_POST['username']);
$password = e($_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Uspesno ste se prijavili";
header('location: pocetna.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "Uspesno ste se prijavili";
header('location: pocetna.php');
}
}else {
array_push($errors, "Pogresno korisnicko ime ili lozinka");
}
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
?>`
I have this on top of page where I want to make restrict for normal users:
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<div class="profile_info">
<div>
<?php if (isset($_SESSION['user'])) : ?>
<strong><?php echo $_SESSION['user']['username']; ?></strong>
<?php endif ?>
</div>
</div>
</div>

In your functions file, you are setting $_SESSION['user'] to the data from the database row for the user; this means you just have to check if $_SESSION['user']['user_type'] is admin or not.
So, it's simple, on the page you only want admins to see (at the top, below your functions.php call), do this:
if($_SESSION['user']['user_type'] != 'Admin') {
//could redirect page here
die('This page is not available to non-administrators.');
}
I noticed a couple of other issues in your login/register code.
1) NEVER use md5() for passwords, it's considered just as bad as plaintext. Instead, use password_hash() and password_verify() PHP functions.
2) Your mysql queries are at risk of SQL Injection attacks, you should convert these to parameterized queries.

Related

pass value from php to another php file

i have a server.php file witch handle the registration form.
The server.php looks like:
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$ig_name = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'secret', 'secret', 'test');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$ig_name = mysqli_real_escape_string($db, $_POST['ig_name']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "A Felhasználónév mező nem lehet üres."); }
if (empty($ig_name)) { array_push($errors, "Az IG név mező nem lehet üres."); }
if (empty($password_1)) { array_push($errors, "A Jelszó mező nem lehet üres."); }
if ($password_1 != $password_2) {
array_push($errors, "A két jelszó nem egyezik.");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM users WHERE username='$username' OR ig_name='$ig_name' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "A felhasználónév már regiszrálva van.");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO users (username, ig_name, password)
VALUES('$username', '$ig_name', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "Sikeresen bejelentkeztél.";
$_SESSION['ig_name'] = $user['ig_name'];
header('location: index.php');
}
}
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$ig_name = mysqli_real_escape_string($db, $_POST['ig_name']);
if (empty($username)) {
array_push($errors, "A Felhasználó mező nem lehet üres");
}
if (empty($password)) {
array_push($errors, "A Jelszó mező nem lehet üres.");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "Sikeresen bejelentkeztél.";
header('location: index.php');
}else {
array_push($errors, "Hibás adatot adtál meg.");
}
}
}
?>
i wanna get the $ig_name variable as value from SQL the the rows name is "ig_name" then use it in settings.php
my settings.php looks like:
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>CDS - Adatbázis</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<span style="margin-left:30px;top:10px;position:relative;font-size:30px;cursor:pointer;color:white;" onclick="openNav()">☰ open</span>
<div id="mySidenav" class="sidenav">
×
Főoldal
<div w3-include-html="content.html"></div>
Keresett személy / Jármű
Ismert rendszámok
Beállítások
Kijelentkezés
</div>
<script>
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
}
$(function(){
$("#includedContent").load("b.html");
});
</script>
<div class="header">
<h2>Beállítások</h2>
</div>
<div class="content">
<!-- notification message -->
<?php if (isset($_SESSION['success'])) : ?>
<div class="error success" >
<h3>
<?php
echo $_SESSION['success'];
unset($_SESSION['success']);
?>
</h3>
</div>
<?php endif ?>
<!-- logged in user information -->
<?php if (isset($_SESSION['username'])) : ?>
<?php include('server.php') ?>
<div>
<table style="width: 60%;" border="0" cellpadding="5">
<tbody>
<tr>
<td> Felhasználónév:</td>
<td> <strong><?php echo $_SESSION['username']; ?></strong></td>
</tr>
<tr>
<td> IG neved:</td>
<td> <strong><?php $ig_name =$_GET['ig_name']; echo $ig_name; ?></strong></td>
<td> </td>
</tr>
<tr>
<td> Jelszó:</td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</div>
<?php endif ?>
</div>
</body>
</html>
Some html string is hungarian, so dont care of it.
How should i get, then send the "ig_name" rows in settings? i dont wanna use a new sql connection, just in server.php
You have already made a session of $ig_name in your server.php on this line $_SESSION['ig_name'] = $user['ig_name']; so you only need to replace
<?php $ig_name =$_GET['ig_name']; echo $ig_name; ?>
with
<?php echo $_SESSION['ig_name']; ?>
in your settings.php
Include your server.php file at the top of settings.php file
include "server.php"
now you can access the "ig_name" variable

Not Displaying the Validation Message for Login Error in PHP

I have login form with username and password.If i am entering wrong username or password it is showing blank page not displaying any error messages.it just showing in URL as website.com/Admin/#. Here is the code which i have written:
<form action="#" method="post" role="form" enctype="multipart/form-data">
<?php if ( $msg != '' ) { ?>
<div class="alert alert-success">
<?php echo $msg; ?>
</div>
<?php } ?>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Email</div>
<input type="text" placeholder="User Name" id="username" name="user_name" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Password</div>
<input type="password" placeholder="Password" id="password" name="password" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="button-box">
<input type="submit" name="submit_login" value="Sign In" class="theme-btn btn-style-one">
</div>
</form>
PHP Code:
<?php
session_start();
include 'db.php';
if ( isset( $_POST['submit_login'] ) ) {
if ( !empty( $_POST['user_name'] ) && !empty( $_POST['password'] ) ) {
$get_user_name = mysqli_real_escape_string( $conn, $_POST['user_name'] );
$get_password = mysqli_real_escape_string( $conn, $_POST['password'] );
// Encrypting the password from text//
$get_password = md5( $get_password );
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'";
if ( $result = mysqli_query( $conn, $sql ) ) {
while ( $rows = mysqli_fetch_assoc( $result ) ) {
if ( mysqli_num_rows( $result ) == 1 ) {
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if ( $_SESSION['user_role'] === 'admin' ) {
header( 'Location:property-list.php' );
}
} else {
$msg = 'User name or Password was Wrong!';
$msgclass = 'bg-danger';
}
}
} else {
$msg = 'There is somekind of Database Issue!';
$msgclass = 'bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass = 'bg-danger';
}
} else {
}
?>
If i give correct username and password its working fine their was no issue in that the only problem is with if i enter wrong username or password or else submitting directly without giving any data it is not displaying message
You need to echo the $msg all the time remove the if in the form then declare mgs and msgclass before the submit action then just echo
<?php
session_start();
include 'db.php';
$msg =""; // declare message
$msgclass =""; //classs
if(isset($_POST['submit_login'])){
if(!empty($_POST['user_name']) && !empty($_POST['password'])){
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
if($result = mysqli_query($conn,$sql)){
while($rows = mysqli_fetch_assoc($result)){
if(mysqli_num_rows($result) == 1){
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if($_SESSION['user_role'] === 'admin'){
header('Location:property-list.php');
}
}
else{
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}
}
}
else {
$msg = 'There is somekind of Database Issue!';
$msgclass='bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
}else {
}
?>
Then
<form action="#" method="post" role="form" enctype="multipart/form-data">
<div class="alert <?php echo $msgclass;?>">
<?php echo $msg;?>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Email</div>
<input type="text" placeholder="User Name" id="username" name="user_name" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="field-label">Password</div>
<input type="password" placeholder="Password" id="password" name="password" required>
</div>
<div class="form-group col-md-12 col-sm-12 col-xs-12">
<div class="button-box">
<input type="submit" name="submit_login" value="Sign In" class="theme-btn btn-style-one">
</div>
</form>
NB : You should use prepared statements to prevent sql injections.
Never use md5() as means of password encrption rather use
password_hash() and password_verify()
First you need to target your php file in the action attribute of your form
action="/path/tofile.php"
Most user friendly validation is done with javascript, so the page doesn't have to reload,
but if you really want to use PHP, one way to do it is with sessions.
You can add the $msg and $msgclass to the session variable:
$_SESSSION['response'] = ['message' => $msg, 'class' => $msgclass];
After that use header function to redirect back to your html:
header('Location: /pathtoformfile');
exit;
Note: be careful not to echo or print anything in the script before header.
Finally, in the form file do this:
// add this at THE TOP of the file
session_start();
// check session variable
if(!empty($_SESSION['response']) {
// display the message
echo $_SESSION['response']['message'];
}
Redirect to your login page again. Suppose, LoginForm.php
Updated code:
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login']))
{
if(!empty($_POST['user_name']) && !empty($_POST['password']))
{
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
if($result = mysqli_query($conn,$sql))
{
while($rows = mysqli_fetch_assoc($result))
{
if(mysqli_num_rows($result) == 1)
{
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if($_SESSION['user_role'] === 'admin')
{
header('Location:property-list.php');
}
}
else{
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}
}
}
else {
$msg = 'There is somekind of Database Issue!';
$msgclass='bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
header("Location:Login.php");
}
?>
If the user enters a wrong password or blank one you are not redirecting it to anywhere.
see updated code.
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login'])){
if(!empty($_POST['user_name']) && !empty($_POST['password'])){
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
if($result = mysqli_query($conn,$sql)){
while($rows = mysqli_fetch_assoc($result)){
if(mysqli_num_rows($result) == 1){
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $rows['user_role'];
if($_SESSION['user_role'] === 'admin'){
// redirect to members area or login area
header('Location:property-list.php');
exit();
}
}
else{
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}
}
}
else {
$msg = 'There is somekind of Database Issue!';
$msgclass='bg-danger';
}
} else {
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
}else {
}
// redirect to error page or login page..
header("redirect:error.php?msg=$msg&c=$msgClass");
exit();
?>
Some developers pass the variables with get others set a session and read the session. Is your choice I prefer sessions, but if you use GET or POST please always sanitize the user input.
On the query you should update your code to use prepared statements to eliminate possibilities of SQL injection.
On the password you are using MD5 if you are going to use it or either hashing protocol you should salt it so your passwords are stronger in case your sql is expose and the hashes are obtain.
$salt = "s0meRand0mStr1ng..Long..difficult...etc."; // must be longer than 20 chars at least.
$get_password=md5($get_password . $salt);
This worked fine for me
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login'])){
if(!empty($_POST['user_name']) && !empty($_POST['password'])){
$get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
$get_password = mysqli_real_escape_string($conn,$_POST['password']);
// Encrypting the password from text//
$get_password=md5($get_password);
$sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password' limit 0,1" ;
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1){
$_SESSION['user'] = $get_user_name;
$_SESSION['password'] = $get_password;
$_SESSION['user_role'] = $row ['role'];
if($_SESSION['user_role'] === 'admin'){
header('Location:property-list.php');
exit;
}
}
else{
header('Location:index.php?msg=1');
exit;
}
} else {
header('Location:index.php?msg=3');
exit;
}
}
if(isset($_GET['msg']) && !empty($_GET['msg'])){
if($_GET['msg']==1){
$msg = 'User name or Password was Wrong!';
$msgclass='bg-danger';
}else if($_GET['msg']==2){
$msg = 'User name or Password was empty!';
$msgclass='bg-danger';
}
}
?>

How to add success message when registration is completed

How do i make an success message when form is submitted
here is the code:
server.php
<?php
session_start();
$username = "";
$errors = array();
$db = mysqli_connect('localhost', 'root', '', 'reg_user');
// REGISTER USER
if (isset($_POST['reg_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
$user_check_query = "SELECT * FROM users WHERE username='$username' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
}
if (count($errors) == 0) {
$password = md5($password_1);
$query = "INSERT INTO users (username, password)
VALUES('$username', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: register.php');
}
}
index.php
<div class="card-body">
<p><?php include('errors.php'); ?></p>
<form method="POST" action="register.php" class="needs-validation" novalidate="">
<div class="form-group">
<label for="username">Username</label>
<input id="username" type="username" class="form-control" name="username" tabindex="1" required autofocus>
</div>
here is the code of error.php which it pops up a error message when username is taken
error.php
<?php if (count($errors) > 0) : ?>
<div class="alert alert-danger alert-dismissible show fade">
<div class="alert-body">
<button class="close" data-dismiss="alert">
<span>×</span>
</button>
<?php foreach ($errors as $error) : ?>
<p><center><b><?php echo $error ?></center></b></p>
<?php endforeach ?>
</div>
</div>
<?php endif ?>
I want to add success message just like the error.php but what is the code to perform an success message?
You can do it like:
if (!$errors)
{
header("Location: success.php");
exit;
}
or modify this part from your code:
if (count($errors) == 0) {
$password = md5($password_1);
$query = "INSERT INTO users (username, password)
VALUES('$username', '$password')";
mysqli_query($db, $query);
$_SESSION['username'] = $username;
$_SESSION['success'] = TRUE;
header('location: success.php'); exit;
}
Are you looking for something like this?
<?php if($_SESSION['success'] != '' ) : ?>
<label> <?php include('success.php'); ?></label>
<?php endif; ?>

How to fix PHP saying boxes are empty

PHP saying theres nothing in the boxes when I put stuff in.
Tried putting var_dump($_POST); die(); at the top of register.php and it showed what I put in the boxes
Not sure what's going on here.
Any help is appreciated. Thanks in advance.
I've spent a while trying to figure this out.
Will login work aswell?
Thanks,
Jon
functions.php
<?php
session_start();
// connect to database
$db = mysqli_connect(:-));
// variable declaration
$username = "";
$email = "";
$errors = array();
// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
register();
}
// REGISTER USER
function register(){
// call these variables with the global keyword to make them available in function
global $db, $errors, $username, $email;
// receive all input values from the form. Call the e() function
// defined below to escape form values
$username = e($_POST['username']);
$email = e($_POST['email']);
$password_1 = e($_POST['password_1']);
$password_2 = e($_POST['password_2']);
// form validation: ensure that the form is correctly filled
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($email)) {
array_push($errors, "Email is required");
}
if (empty($password_1)) {
array_push($errors, "Password is required");
}
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
if (isset($_POST['user_type'])) {
$user_type = e($_POST['user_type']);
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', '$user_type', '$password')";
mysqli_query($db, $query);
$_SESSION['success'] = "New user successfully created!!";
header('location: home.php');
}else{
$query = "INSERT INTO users (username, email, user_type, password)
VALUES('$username', '$email', 'user', '$password')";
mysqli_query($db, $query);
// get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
}
// return user array from their id
function getUserById($id){
global $db;
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
// escape string
function e($val){
global $db;
return mysqli_real_escape_string($db, trim($val));
}
function display_error() {
global $errors;
if (count($errors) > 0){
echo '<div class="error">';
foreach ($errors as $error){
echo $error .'<br>';
}
echo '</div>';
}
}
function isLoggedIn()
{
if (isset($_SESSION['user'])) {
return true;
}else{
return false;
}
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['user']);
header("location: login.php");
}
if (isset($_POST['login_btn'])) {
login();
}
// LOGIN USER
function login(){
global $db, $username, $errors;
// grap form values
$username = e($_POST['username']);
$password = e($_POST['password']);
// make sure form is filled properly
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
// attempt login if no errors on form
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) { // user found
// check if user is admin or user
$logged_in_user = mysqli_fetch_assoc($results);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: admin/home.php');
}else{
$_SESSION['user'] = $logged_in_user;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
// ...
function isAdmin()
{
if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
return true;
}else{
return false;
}
}
register.php
<?php
include('functions.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>Register | Vex Radio</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<form method="post" action="register.php">
<p><?php echo display_error(); ?></p>
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" class="btn" name="register_btn">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
PHP to save the items in a DB and allow me to login

PHP registration/login error [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 4 years ago.
I'am trying to create register/login system. However, I've faced some problems. I can't understand where's the mistake in my code.
Here's my server.php & register.php. Browser shows that mistake is in line 65. "Parse error: syntax error, unexpected ';'". In my opinion ; must be there.
<?php
session_start();
$username = "";
$email = "";
$errors = array();
// Connect to the database
$db = mysqli_connect('localhost', 'root', '', 'lead2pro');
// If the register button is clicked
if(isset($_POST['register'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db ,$_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// Ensure that form fields are filled properly
if(empty($username)) {
array_push($errors, "Username is required!");
}
if(empty($email)) {
array_push($errors, "Email is required!");
}
if(empty($password_1)) {
array_push($errors, "Password is required!");
}
if($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// If there are no errors, save user to database
if(count($errors) == 0) {
$password = md5($password_1); // Hashin the password before storing in database
$sql = "INSERT INTO users (username, email, password) VALUES('$username', '$email', '$password')";
mysqli_query($db, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: ../system.php'); // Redirect to game location
}
}
// log user in from login page
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
// Ensure that form fields are filled properly
if(empty($username)) {
array_push($errors, "Username is required!");
}
if(empty(password)) {
array_push($errors, "Password is required!");
}
if(count($errors) == 0){
$password = md5($password); // Encrypt password before comparing this one with the one in database
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($db, $query);
$if (mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: ../system.php'); // Redirect to main page location
} else {
array_push($errors, "Wrong username/password combination");
header('location: ../php/login.php');
}
}
}
//logout
if(isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header('location: ../php/login.php');
}
?>
Here's my register.php
<?php include('../includes/server.php');?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manager | Register</title>
<link rel="stylesheet" href="../css/reg.css">
</head>
<body>
<div class="header">
<h2>Register</h2>
</div>
<!-- Display validation errors here! -->
<?php include('../includes/errors.php'); ?>
<form action="register.php" method="post">
<div class="input-group">
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="text" name="email" value="<?php echo $email; ?>">
</div>
<div class="input-group">
<label>Password</label>
<input type="password" name="password_1">
</div>
<div class="input-group">
<label>Confirm Password</label>
<input type="password" name="password_2">
</div>
<div class="input-group">
<button type="submit" name="register" class="btn">Register</button>
</div>
<p>
Already a member? Sign in
</p>
</form>
</body>
</html>
The problem is on a different line:
$if (mysqli_num_rows($result) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: ../system.php'); // Redirect to main page location
}
That $ should not be there in front of the if.

Categories