Please help with my logout script. I am sorry for dumb mistakes I am very new to php. Please provide me with details and examples of how to fix this. Thank you so much.
Login Page: There are 4 types of users. Each user will get a separate home page.
<?php
session_start();
require_once('common/config.php');
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM `users` WHERE username='".$username."' and password='".$password."'";
$result = mysql_query($sql) or die(mysql_error());
$fetched = mysql_fetch_array($result);
if ($fetched['user_type'] == "admin")
{
header('location: adminhomepage.php');
}
else if ($fetched['user_type'] == "po")
{
header('location: pohomepage.php');
}
else if ($fetched['user_type'] == "pw")
{
header('location: pwhomepage.php');
}
else if ($fetched['user_type'] == "ps")
{
header('location: pshomepage.php');
}
else
{
header('location: invalid.php');
exit();
}
}
?>
Home Page: For instance this is the admin home page.
<?php
session_start();
if (isset($_SESSION['username']) && ($_SESSION['username'] !== 1))
{
header('Location: login.php');
}
?>
Logout Page
<?php
session_start();
$_SESSION['username'] =0;
?>
Logout Button
<form action = "logout.php">
<input id="logoutbutton" type="submit" value="Logout">
</form>
logout page
<?php
session_start();
unset($_SESSION['susername']);
$_SESSION['susername'] = "";
session_destroy();
header("location:index.php");
?>
login.php
session_start();
if (isset($_SESSION['uname']) == "")
{
require_once('index.php');
}
$user_name = $_POST['user_name'];
$user_pass = $_POST['user_pass'];
$_SESSION['susername'] = $user_name; // or other value
logout page -
<?php
session_start();
$_SESSION['username'] =0;
?>
you have to start the session first before accessing it.
In your logout.php please update this code...
<?php
session_start();
if(isset($_SESSION['username']))
{
unset($_SESSION['username']);
header('Location: login.php');
}
?>
use unset($_SESSION['susername']) or session_destroy
Edit:
With your new information, it's clear you never actually set the $_SESSION['username'] value.
if ($fetched['user_type'] == "admin")
{
$_SESSION['username'] = $username;
header('location: adminhomepage.php');
}
else if ($fetched['user_type'] == "po")
{
$_SESSION['username'] = $username;
header('location: pohomepage.php');
}
else if ($fetched['user_type'] == "pw")
{
$_SESSION['username'] = $username;
header('location: pwhomepage.php');
}
else if ($fetched['user_type'] == "ps")
{
$_SESSION['username'] = $username;
header('location: pshomepage.php');
}
else
{
header('location: invalid.php');
}
exit();
Your problem is your comparison.
if ($_SESSION['username'] != 1)
This is true if $_SESSION['username'] is not set, null, a string, false, etc...
This might be more what you are looking for.
if (isset($_SESSION['username']) && is_string($_SESSION['username']) && strlen($_SESSION['username']))
And you need to fix your SQL injection problem here
$sql = "SELECT * FROM `users` WHERE username='".$username."' and password='".$password."'";
Escape variables with mysql_real_escape_string or use PDO with proper prepared statements.
You should also store passwords as hashes with password_hash(). Fetch the user, compare stored hash to password with password_verify.
if (!password_verify($password, $fetched["password"])) {/* wrong password, show error or something */}
Related
hi i want to block direct URL access to my pages using below php codes but if I include it to my forms I can't login even after typing my username and password it's like I'm locked out of my application. can someone help please
that's my security.php file
<?php
if(!isset ($_SESSION['user']))
{
header ('location:user_login.php');
}
?>
and the user login file
<?php
if (isset($_POST['btnLogin']))
{
$user = $_POST['user'];
$password = $_POST['password'];
//sql injection security
$user = mysqli_real_escape_string($con,$user);
$password = mysqli_real_escape_string($con,$password);
//select database
$db = mysqli_select_db($con,'nesthet');
$query = "SELECT * from users where user='$user' AND password='$password'";
$query_run = mysqli_query($con,$query);
$role = mysqli_fetch_array($query_run);
//user redirection base on user role
if($role['role'] == "admin"){
session_start();
$_SESSION['user'] = $user;
header('location: admin.php');
}
else if($role['role'] == "user") {
$_SESSION['user'] = $user;
header('location: mdi_parent.php');
}
else {
$_SESSION['status'] = "Username or password is invalid";
header('location: index.php');
}
}
?>
In security.php you should execute session_start() before using $_SESSION variable
<?php
if(!isset ($_SESSION['user']))
{
header ('location:user_login.php');
}
?>
In your code, you just only start session when role is admin
if($role['role'] == "admin"){
session_start();
$_SESSION['user'] = $user;
header('location: admin.php');
}
else if($role['role'] == "user") {
$_SESSION['user'] = $user;
header('location: mdi_parent.php');
}
else {
$_SESSION['status'] = "Username or password is invalid";
header('location: index.php');
}
I want to make a login form which can be used by normal users and admins. The code should tell the difference between normal users and admins and based on it, start a new session after user is logged in (admin or user session). In my database table, I added "level" column which should determine if user is an admin or not (for ex.: if the user level is 3, then they are admin).
Here is my login.php file:
if (isset($_POST['submit'])) {
include_once 'database.php';
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
header('Location: login.php');
} else {
$execution = "SELECT level FROM users WHERE name = '$username' AND password = '$password';";
$result = mysqli_query($database, $execution);
if (mysqli_num_rows($result) == 1) {
session_start();
$_SESSION['user'] = $username;
header('Location: login.php');
exit();
} elseif (mysqli_num_rows($result) == 3) {
session_start();
$_SESSION['admin'] = $username;
header('Location: index.php');
exit();
} else {
header('Location: login.php');
exit();
}
}
}
The code does not work because when I try to log in with a user that has LEVEL 3 in database, it still starts the normal user session and does not go through the elseif statement that I wrote above. How do I fix this? Maybe I am doing this completely wrong and there is another way to do this admin/user login thing?
Btw: I do understand that I'm storing passwords in plain text here, but right now I am only experimenting with the code and do not plan to upload it to a website.
Because you aren’t checking the user’s level at all.
Your first if block only checks if the result has one row.
Also, you should use prepared statements to prevent injection.
This is the correct code:
if (isset($_POST['submit'])) {
include_once 'database.php';
$username = $_POST['username'];
$password = $_POST['password'];
if (!$username or !$password) {
header('Location: login.php');
} else {
$execution = mysqli_prepare($database, "SELECT level FROM users WHERE name = ? AND password = ?;";
mysqli_stmt_bind_param($execution, "ss", $username, $password);
mysqli_stmt_execute($execution);
$result = mysqli_stmt_get_result($execution);
if (mysqli_num_rows($result) == 1) {
$row = mysqli_fetch_assoc($result);
session_start();
if ($row['level'] == 1) {
$_SESSION['user'] = $username;
header('Location: login.php');
}
elseif ($row['level'] == 3) {
$_SESSION['admin'] = $username;
header('Location: index.php');
}
exit();
echo "$result";
} else {
header('Location: login.php');
exit();
}
}
}
Here is your code updated.
You need to get the value of level in order to apply the permissions.
session_start();
if ($result->num_rows > 0){
if($row['level'] == 1){
$_SESSION['user'] = $username;
header('Location: login.php');
exit();
}elseif( $row['level'] == 3){
$_SESSION['admin'] = $username;
header('Location: index.php');
exit();
}else{
header('Location: login.php');
exit();
}
}
Hope it helps.
Hello i have created login system but its not working for some reason , i start session after some one login and then made some check if session are isset and if session are no more then 1 hour :
this is my login script on index.php :
<?php
require 'mysql.php';
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] > 3600){
session_start();
session_unset();
session_destroy();
}
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] < 3600){
header('Location: main.php');
}
if (isset($_POST["login"])){
$username = $_POST["username"];
$password = $_POST["password"];
$stmt = $connect->prepare("SELECT username, password FROM users WHERE username=? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$rowcount = $result->num_rows;
if ($rowcount > 0){
while ($row = $result->fetch_assoc()) {
if ($row["username"] == $username && $row["password"] == $password){
if(!isset($_SESSION)) {
session_start();
}
$_SESSION["username"] = $username;
$_SESSION["usertype"] = $row["usertype"];
$_SESSION["userid"] = $row["id"];
$_SESSION["CREATED"] = time();
header('Location: main.php');
} else {
$error_msg2 = "Username or password does not mach";
$error2 = "error";
}
}
} else {
$error_msg2 = "No such user";
$error2 = "error";
}
echo $error_msg2;
$stmt->close();
$connect->close();
}
?>
and this is main.php code :
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] > 3600){
session_start();
session_unset();
session_destroy();
header('Location: index.php');
}
so ones you login you will by redirected to main.php and if session are set u should be unable to access index.php cuz if you will try u and session are not expired you will get redirected back you main.php same with main if session are expired you will get redirected back to index.php to login , but no matter if you are logged in or no you can walk between them freely
You should call session_start in any case - it fills $_SESSION with values. Also it's enough to unset $_SESSION['username'], no need to destroy whole session - PHP can take care of that. Here is code that should work:
index.php
<?php
require 'mysql.php';
session_start();
if (isset($_SESSION['username'])) {
if ($_SESSION['CREATED'] < 3600) {
header('Location: main.php');
exit;
}
unset($_SESSION['username']);
}
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $connect->prepare('SELECT username, password FROM users WHERE username=? LIMIT 1');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$rowcount = $result->num_rows;
if ($rowcount > 0) {
$row = $result->fetch_assoc();
if ($row['username'] == $username && $row['password'] == $password) {
$_SESSION['username'] = $username;
$_SESSION['usertype'] = $row['usertype'];
$_SESSION['userid'] = $row['id'];
$_SESSION['CREATED'] = time();
header('Location: main.php');
exit;
} else {
$error_msg2 = 'Username or password does not mach';
$error2 = 'error';
}
} else {
$error_msg2 = 'No such user';
$error2 = 'error';
}
echo $error_msg2;
$stmt->close();
$connect->close();
}
main.php
session_start();
if (!isset($_SESSION['username']) || time() - $_SESSION['CREATED'] > 3600){
unset($_SESSION['username']);
header('Location: index.php');
exit;
}
You have to call session_start() before you can use $_SESSION.
<?php
require 'mysql.php';
session_start();
if(isset($_SESSION["username"]) && time() - $_SESSION["CREATED"] > 3600){
session_unset();
session_destroy();
}
I have a suggestion. Create a session validation function.
function sessionValidate($username,$id=NULL)
{
$status = session_status();
if($status == PHP_SESSION_NONE)
{
//There is no active session
session_start();
}
if(!isset($_SESSION[$username]))
{
return false;
}
$id = $_SESSION[$roleid];
if((time()- $_SESSION["created"]) >= 3600)
{
session_destroy();
return false;
}
return $id;
}
and check it in every page or use this in header page.
if(!($userid=sessionValidate($username)))
{
error_log("No session logging out ....");
header('Location: index.php');
}
UPDATE ::
Definition
session_status — Returns the current session status
Return Values
PHP_SESSION_DISABLED- if sessions are disabled.
PHP_SESSION_NONE - if sessions are enabled, but none exists.
PHP_SESSION_ACTIVE - if sessions are enabled, and one exists.
I'm trying to fix my login page...
It works fine on the login.php with redirecting but on the index it doesn't redirect even if the session is empty. Any pointers? I'm new to this, so forgive me if it's really obvious.
<?php
require_once('../includes/config.php');
session_start();
if(!isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='no'){
// not logged in
header("location: login.php");
exit();
} else {
$_SESSION['loggedin'] = 'yes';
}
?>
<?php
include("../includes/config.php");
$error = NULL;
$atmpt = 1;
if (!isset($_SESSION)) {
session_start();
}
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin']=='yes'){
// logged in
header("location: index.php");
exit();
}
if(isset($_POST['login']))
{
/* get username and password */
$username = $_POST["username"];
$password = $_POST["password"];
/* MySQL Injection prevention */
$username = mysqli_real_escape_string($mysqli, stripslashes($username));
$password = mysqli_real_escape_string($mysqli, stripslashes($password));
/* check for user in database */
$query = "SELECT * FROM admin_accounts WHERE username = '$username' AND password = '$password'"; // replace "users" with your table name
$result = mysqli_query($mysqli, $query);
$count = $result->num_rows;
if($count > 0){
//successfully logged in
$_SESSION['username']=$username;
$_SESSION['loggedin']='yes';
$error .= "<div class='alert alert-success'>Thanks for logging in! Redirecting you..</div>";
header("refresh:1;url=index.php");
} else {
// Login Failed
$error .= "<div class='alert alert-danger'>Wrong username or password..</div>";
$_SESSION['loggedin']='no';
$atmpt = 2;
}
}
?>
The line
session_start();
should be the very first line in the php script.
Just modify first three lines.
As session_start() should be put before any output has been put on the browser (even space).
<?php
session_start();
require_once('../includes/config.php');
if (empty($_SESSION['loggedin']) && $_SESSION['loggedin']=='no') {
...
I'm writing a login code for my control panel for my website. I've made the login script. But for some reason the session doesn't save, here is the parts of my code I use:
index.php
session_start();
if(isset($_POST['username']) && isset($_POST['password'])) {
require('scripts/validateLogin.php');
}
if($_SESSION['login'] == 1) {
$loginOkay=1;
echo "Logged in";
} else {
$loginOkay=0;
echo "Not logged in";
}
validateLogin.php
require('mysql_connect.php');
$username = htmlspecialchars(strtolower($_POST['username']));
$password = md5(htmlspecialchars($_POST['password']));
$result = mysqli_query($con, "SELECT username,password FROM tb_mods WHERE username = '$username';");
while($row = mysqli_fetch_array($result)) {
if ($row['username'] == $username && $row['password'] == $password) {
$_SESSION['login'] == 1;
}
}
I call session_start(); before I load my loginValidation.php so session_start(); is active in both pages.
I keep getting: Not logged in as result.
I think the line $_SESSION['login'] == 1; is wrong, you need only one equal character to add value to the session variable. I hope it will help.