Displaying error message for specific conditions - php

I have been trying to display a specific error/warning message when a specific conditions is met. To be specific,
1) Unregistered or invalid user will get the $errMsg2 error message(I have this done)
2) Registered and 'notvoted' user will login successfully and proceed with the voting flow(I have this done)
3) Registed and 'voted' user should have something like "You have voted!" error message. Instead it kept on displaying the $errMsg2 error(Which is my main issue here).
*I have declared $stat and $stat2 respectively as it matches my mySQL db variables/structure.
I have tried playing around a lot with the if/else statement but I can't get the $stat2 conditions to meet.
Please help.
Below is my php code,
$stat='notvoted';
$stat2='voted';
//Create query
if($position=='Admin') {
$qry="SELECT * FROM admin WHERE username='$login' AND password='$password'";
}
if($position=='Student') {
$qry="SELECT * FROM students WHERE username='$login' AND password='$password' AND status='$stat'";
}
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
if($position=='Student') {
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['username'];
$_SESSION['SESS_COURSE'] = $member['course'];
$_SESSION['NAME'] = $member['name'];
session_write_close();
header("location: candidates_list.php");
exit();
}
if($position=='Admin') {
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
session_write_close();
header("location: admin/index.php");
exit();
}
}else if($stat2==TRUE){
header("location: index.php");
$_SESSION['errMsg3'] = "You have voted!";
exit();
}else{
header("location: index.php");
$_SESSION['errMsg2'] = "Invalid username or password, please re-
enter or register first";
exit();
}
}else {
die("Query failed");
}

You need to fetch the voting status from the database and compare it with 'voted'.
Here is some code you might be looking for:
//Create query
$qry = "SELECT * FROM students WHERE username='$login' AND password='$password'";
$result = mysql_query($qry);
//Check whether the query was successful or not
$result or die("Query failed");
// Check for wrong credentials
if (mysql_num_rows($result) == 0) {
header("location: index.php");
$_SESSION['errMsg2'] = "Invalid username or password, please
re-enter or register first";
exit();
}
// Login successful, fetch properties
$member = mysql_fetch_assoc($result);
if ($position == 'Student') {
// Check voting status
if ($member['status'] == 'voted') {
header("location: index.php");
$_SESSION['errMsg3'] = "You have voted!";
exit();
}
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $member['username'];
$_SESSION['SESS_COURSE'] = $member['course'];
$_SESSION['NAME'] = $member['name'];
session_write_close();
header("location: candidates_list.php");
exit();
}
if ($position == 'Admin') {
session_regenerate_id();
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
session_write_close();
header("location: admin/index.php");
exit();
}
There are however several issues remaining:
It is not clear how $position got it's value. Ideally the students table should
have this information (or a reference to it), and you should check that the connecting
user is not trying to take the administrator role without having the right to do so.
It is not enough to have some limitations on the client (HTML) side, for making
sure this does not happen. You must check again in the database that it is OK for
the user to act as administrator.
$login and $password should first be checked not to contain anything that would
turn the SELECT statement into something revealing unwanted information or
having side-effects (read about SQL injection ). One important
improvement would be to not allow the presence of a single quote in
either $login or $password.
The code uses deprecated mysql_ functions. Instead, the MySQLi or PDO_MySQL
extension should be used.
Less important: it is strange to see $_SESSION['SESS_MEMBER_ID'] being set
with a different field's value depending on the position. It seems more logical to build your
code in such a way that it always corresponds to same field: either username
or id, the session variable name suggesting it should be the second.

Related

Log In Form Is Forwarding To Database Connection Page. Not Sure Why. It's Supposed To Be Redirecting To Index2.php

I have this form programmed to log a user in. I have confirmed that it does in fact set a session for a user, but for some reason, it forwards the user to the page to connect to the database. I have this page linked in the code because I obviously need to consult the database to confirm the user has an account, but I don't understand why it goes to this page and then just stays there. Help would be appreciated. Index2.php (set as that right now so users won't see it when they go to the site) is supposed to be set as the redirected page after login. The user is supposed to be able to see the homepage even without logging in, but certain content only appears in the user is logged in.
<?php
session_start();
include("db_connect.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
//something was posted
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && !empty($password))
{
//read from database
$query = "select * from users_listers where email = '$email' limit 1";
$result = mysqli_query($conn, $query);
if($result)
{
if($result && mysqli_num_rows($result) > 0)
{
$user_data = mysqli_fetch_assoc($result);
if($user_data['password'] === $password)
{
$_SESSION['user_lister_id'];
header("Location: ../index2.php");
die;
}
}
}
echo "wrong username or password!";
}else
{
echo "wrong username or password!";
}
}
?>
Thank you for the help!

Unable to protect pages/area with password

I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session

Creating an admin only page in php

I assume this can simply be done with permissions, but I cannot seem to get it to work. I was trying to make the page check the user for a permission using the code below, otherwise it redirects to home. It always redirects though and I do not know why.
<?php
if(!isset($_SESSION))
{
session_start();
}
if ($_SESSION['permission'] == 0) {
header("Location: ./index.php");
exit;
} else {
if (!isset($_SESSION['authemail'])) {
header("Location: ./index.php");
exit;//Redirect to the index
}
Edit: I added a session dump and both the userID and permission are null. What am I missing from here as I cannot figure it out?
<?php
session_start();
include ('../config/config.php');
/* basic field validation */
$email = trim($_POST["email"]);
$password = trim ($_POST["password"]);
/* check if details are empty, redirect if they are */
if (empty($email) or empty($password)) {
$_SESSION["message"] = "You must enter your email and password";
//Redirect to index
header("Location: ../index.php");
exit;
}
/* sanitise the input */
$email = strip_tags($email);
$password = strip_tags($password);
/* SQL user selection query, with error handling for the SQL */
$query = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";
$result = mysqli_query($mysqli,$query) or exit("Error in query: $query. " . mysqli_error());
/* on query success, set sessions for email and userid */
if ($row = mysqli_fetch_assoc($result)) {
$_SESSION["authemail"] = $email;
$_SESSION["userid"] = $id;
$_SESSION["permission"] = $permission;
/* redirect the user to the secured page */
header("Location: ../loggedin.php");
} else {
/* display error if login was not successful and redirect to index */
$_SESSION["message"] = "Could not log in as $email - $query";
header("index.php");
}
?>
Try to set a flag in the database for someone who is an admin. Then on any specific page that only admins can access you should check this user variable.
if(!$user->isAdmin()){
header("Location: ./login.php");
exit;
}
If you do not have a $user object available, simply call a function that can query the database for the necessary variable.
if(!isUserAdmin()){
header("Location: ./login.php");
exit;
}
Also since both cases of yours redirect to index.php, you can combine the statements:
if($_SESSION['permission'] == 0 || !isset($_SESSION['authemail'])){
header("Location: ./index.php");
exit;
}
Make sure you are debugging to make sure the SESSION values are set/get as expected. Your code is redirecting because one of the conditions is true. Debug and find the bug.

Checking if user is admin or normal

I am having problems checking whether the user is admin or not in the database. I made it so if admin has the value 1 for the users profile then they are admin and is redirected to the admin page and if not they are redirected to the login page. However I gave my personal account the value of 1 in the database however it is still redirecting me to the login page.
I have given my code below for you to see if I have done anything wrong, please tell me as I have only just started learning PHP.
<?php
session_start();
// First we cubrid_execute(conn_identifier, SQL)te our common code to connection to the database and start the session
require("include/common.php");
$admin = $_POST['admin'];
$user = $_POST['username'];
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT *
FROM users
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
if ($admin == 1) {
$_SESSION['username'] = $user;
header("location: memberlist.php");
}
if ($admin == 0) {
$_SESSION['username'] = $user;
header("location: login.php");
}
Correct you code First:
Try this:
if ($admin == 1) {
$_SESSION['admin'] = $admin; //put you admin in session
header("location: memberlist.php");
}
if ($admin == 0) {
$_SESSION['user'] = $user; //here put your user in session
header("location: login.php");
}
if(empty($_SESSION['user'])) //if user is empty then it redirects to login page
{
header("Location: login.php");
die("Redirecting to login.php");
}
else if(!empty($_SESSION['admin'])) //if admin is not empty it goes to admin area
{
header("location: memberlist.php");
}
else if(!empty($_SESSION['user'])) //same here if user is present,then it leads to user area
{
header("Location: user.php");
}

How to prevent browser from going back to login form page once user is logged in?

I'm trying to make a website in which the admin can upload books through an admin portal. I've made a successful login but when the user gets logged in and presses the back button (on the browser) the form page appears again, and the same happens when they log out and press back button, the page that should appear only appears after they login again. I searched a lot on the internet but all in vain. Please make a suggestion about it.
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if ($username && $password) {
$connect = mysqli_connect("localhost", "root", "") or die ("Could'nt connect to database!"); //database connection
mysqli_select_db($connect, "mahmood_faridi") or die ("Could'nt find database");
$query = ("SELECT * FROM user WHERE username= '$username'");
$result = mysqli_query($connect, $query);
$numrows = mysqli_num_rows($result);
if ($numrows !== 0) {
while ($row = mysqli_fetch_assoc($result)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username == $dbusername && $password == $dbpassword) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
header('location: help.php'); //another file to send request to the next page if values are correct.
exit();
} else {
echo "Password Incorrect";
}
exit();
} else {
die("That user doesn't exists!");
}
} else {
die("Please enter a username and password");
}
?>
On the login screen, in PHP, before rendering the view, you need to check if the user is already logged in, and redirect to the default page the user should see after logged in.
Similarly, on the screens requiring login, you need to check if the user is not logged in and if not, redirect them to the login screen.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
}
You can conditionally add Javascript code to go forward to the intended page.
<script>
history.forward(1);
</script>
This might be annoying or fail when Javascript is not present and/or disabled.
index.php page you should need to add the code in the top of a php file....
<?php
include 'database.php';
session_start();
if (isset($_SESSION['user_name'])) {
header('location:home');
}
if (isset($_POST['submit'])) {
$user = $_POST['user_name'];
$password = $_POST['password'];
$query = "select count(*) as count from users where user_name= '$user' and password = '$password';";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
while ($row = mysqli_fetch_assoc($result)) {
$count = $row['count'];
if ($count == 1) {
$_SESSION['user_name'] = $user;
header('location:home');
}
}
}
?>
This is another page. home.php page you should need also to add the code in the top of a php file to check it first.
<?php
include 'database.php';
if (!(isset($_SESSION['user_name']))) {
header('location:index');
}
?>
I am just modifying #sbecker's answer, use exit() after redirecting.
I have faced the same issue, but now exit(); works for me.
// on login screen, redirect to dashboard if already logged in
if(isset($_SESSION['username'])){
header('location:dashboard.php');
exit();
}
// on all screens requiring login, redirect if NOT logged in
if(!isset($_SESSION['username'])){
header('location:login.php');
exit();
}
you can use this it's easy to use
<?php
if(empty($_SESSION['user_id'])){
header("Location: login.php");
}
else{
header("Location: dashboard.php");
}
?>
My suggestion: the login should happen when the users clicks some link/button
Once the login server side takes place, use the the php function header('url') to redirect the user to the url it should be. (be careful not to echo anything otherwise the redirect will not happen)
[Edit] You say you have the first login file an html one, that is fine to me, but you say it redirects to whatever, then you are using a redirect from client side. In my opinion you should not use that client side redirect for the login. Probably that is causing the confusion.

Categories