Unable to protect pages/area with password - php

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

Related

Password can be use once

I already set a password for the user to log in, in phpMyAdmin. But I want to make sure that the password is deleted once the user uses it. Therefore, the user cannot login to the system twice. But I don't know how to make an SQL statement for that. I just want to delete the password without deleting the username. Can I combine the delete code with submit button?
<?php
if(isset($_POST['submit']))
{
include("config.php");
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['login_user'] = $username;
$query = mysqli_query($mysqli,"SELECT username from logins WHERE username='$username' and password='$password'");
if(mysqli_num_rows($query) !=0)
{
echo "<script language='javascript' type='text/javascript'>location.href='home.php'</script>";
}
else
{
echo "<script language='javascript' type='text/javascript'>alert('Username or Password invalid!')</script>";
}
}
?>
Thank you.
Add an SQL UPDATE statement before your redirect your user.
And do not save the password as plain text in your DB:
Best way to store passwords in MYSQL database
But an better idea is, that you will add an timestamp to your database with the last login. If the timestamp is NULL, than the user can login. If it is not empty the user can not login.
But here the example for the given code:
(Security manuel: https://www.php.net/manual/en/mysqli.real-escape-string.php)
if(isset($_POST['submit']))
{
include("config.php");
session_start();
$username = mysqli_real_escape_string($mysqli, $_POST['username']);// add a little bit security at this point
$password = mysqli_real_escape_string($mysqli, $_POST['password']); // add a little bit security at this point
$_SESSION['login_user'] = $username;
$query = mysqli_query($mysqli,"SELECT username from logins WHERE username='$username' and password='$password' and password IS NOT NULL"); // check that the password is not empty
if(mysqli_num_rows($query) !=0)
{
// update your DB row
// if you got an ID, than do it with the ID and not with the $username and $password
mysqli_query($mysqli,"UPDATE logins SET password = NULL WHERE username='$username' and password='$password'");
// to do it better use instead of JavaScript PHP for the redirect. In this case it is important, that nothing is printed out bevore the `header()`:
header("Location: home.php");
exit;
// try to not mix it up if you are on an pure PHP page
// echo "<script language='javascript' type='text/javascript'>location.href='home.php'</script>";
}
else
{
// same as above
header("Location: login.php?tag=login-invalid");
exit;
// echo "<script language='javascript' type='text/javascript'>alert('Username or Password invalid!')</script>";
}
}
If the "password" is not NULL able, than replace the NULL through = ""

How to correctly prevent access to php page to users which are not logged in

I managed to develop a login page (index.php) which correctly redirects to another php page (welcome.php).
My goal is to prevent users to access welcome.php page if not logged in.
I already followed suggestions of other users, here's part of code:
Index.php
<?php
include("settings/dbConfig.php");
if (!isset($_SESSION))
session_start();
if($_SESSION['login_user'])
header("location: php/welcome.php");
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myemail = mysqli_real_escape_string($db,$_POST['email']);
$mypassword = mysqli_real_escape_string($db,$_POST['pass']);
$sql = "SELECT id FROM users WHERE email = '$myemail' and password = md5('$mypassword');";
$result = mysqli_query($db, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1
if($count == 1) {
$_SESSION['login_user'] = $myusername;
header("location: php/welcome.php");
}
else {
$error = "Login Failed... Please retry";
}
}
?>
Welcome.php
<?php
session_start();
if(!isset($_SESSION['login_user'])){
header("location: logout.php");
die();
}
?>
Login works good, if I try to access welcome.php page without having logged in I get immediately redirected to index.php page and that's good too.
Problem is: I get redirected to index.php even if I correctly log in with valid credentials.
I expect to be redirected back to index.php only if I'm not logged in and to be redirected to welcome.php if I'm logged in.
How should I modify provided code in order to achieve that?
try
<?php
session_start();
if(isset($_SESSION['login_user']))
header("location: php/welcome.php");
else
header("location: php/index.php");
?>
This might be a solution, but you better learn about prepared statements and PHP built-in functions for security reasons as suggested in comments.
Managed to solve problem, was easier than expected.
Issue was on line : $_SESSION['login_user'] = $myusername;
Since $myusername doesn't exists, of course session variable won't exist too.

php login system do not stop or send any error messages when users login incorrectly

When I coded my php login system (In MySQLi), I get an error that do not actually checks if username or password is wrong, idk what to do abot this. Please help me out here.
<?php
// If logged in
if(isset($_SESSION['user_id'])) {
header('Location: index.php');
}else {}
//error_reporting(0);
//MySQLi Login form
//Database connection
$con = mysqli_connect('localhost', 'root', '', 'console');
//Actual Login form
if(isset($_POST['login'])) {
session_start();
//Explainging details
$username = $_POST['username'];
$password = $_POST['password'];
//Fetching data
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(MYSQLI_BOTH);
//Logging in
$_SESSION['user_id'] = $row['user_id'];
header('Location: index.php');
}else{
$wrong = 'Username or password is wrong';
}
?>
Also i got a check.php that redirects you to /notloggedin.php if not logged in, but IF the user is logged in it will display their User_ID, but when user logsIn with wrong details then go to check.php it does not show anything and it does not redirect the users to /notloggedin.php.
So what do I do with that? Is there something I forgot to add, or something i did wrong???Can you write a example if you have any ideas?? Thanks.
EDIT:
Now instead of using MySQLi I got an idea from #christoandrew, so i made everything into functions. What the functions tells the system to do is its gonna check for the username first, if the username exists its gonna make a $_SESSION()for the username. Then again using the $_SESSION() to find the User_ID to the username then its gonna look for the password for the same User_ID. Then when its checked everything it will destroy all 'Sessions' it made and create a $_SESSION() for all information like User_ID, Email, Username, Password, Etc... Thanks for all the help i got in my way!
if(isset($_POST['login'])) {
session_start();
//Explainging details
$username = $_POST['username'];
$password = $_POST['password'];
//Fetching data
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(MYSQLI_BOTH);
// Try checking if there are actually rows that are returned
// If the rows are greater than zero then the user exists else the
// user supplied wrong credentials
if(mysqli_num_rows($row) > 0){
//Logging in
$_SESSION['user_id'] = $row['user_id'];
header('Location: index.php');
}else{
$wrong = 'Username or password is wrong';
}
// The else block below is not necessary and the validation is misplaced
}
you need start the session:
session_start();

How to make a secure session with php and mysql?

I have tried a session.php script which runs at the head of each page in my website to verify that the user has logged in before they can browse the site. However, now the process_login script won't load the secure landing page and it just reloads to the login page. I believe that my secure session is not being set correctly. Can someone further explain how this works to me?
This is the script, process_login, which executed when a user clicks login:
<?php
// Initialize session
session_start();
// Require database connection settings
require('config.inc');
// Retrieve email and password from database
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string(md5($_POST['password']));
$query = "SELECT * FROM $table WHERE email='$email' AND password='$password' LIMIT 1";
$result = mysql_query($query);
// Check email and password match
if(mysql_num_rows($result)) {
// Set email session variable
$_SESSION['email'] = $_POST['email'];
// Jump to secured page
header('Location: home.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
and this is the session.php script which is in the head of each page that requires a user to be logged in:
<?php
if (isset($_SESSION['email']) == 0) {
// Redirect to login page
header('Location: index.php');
}
?>
You need to include the code
session_start();
in the your file session.php to access your session variables
Or you should make sure that session auto start is enabled on your php configuration.

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