I've been stuck trying to block access to an admin page using PHP. The PHP is below but I can't figure out which combination of statement I need to use for the permission to be selected.
When I dump my session it's always null but the email session is there. It's a simple login requiring email and password. I basically want it to also get their permission from the DB.
<?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 email, permission 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["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");
}
?>
Feel free to edit some of the text out if it isn't relavent.
Related
I am building a study planner that features just a single welcome area, after logging in. I am currently trying to obtain the user ID of the currently logged in user for use in an SQL update query in this welcome area, as well as the user’s first name for use in the welcome message.
I have tried putting $_SESSION['user_id'] = userid; and $_SESSION['user_firstname'] = firstname; after $_SESSION['login_user'] = $username; ($_SESSION['login_user'] = $username; works fine by the way) but upon logging into the page, I get these errors: Notice: Use of undefined constant userid - assumed 'userid' in C:\wamp64\www\justread\session.php on line 11 and Notice: Use of undefined constant firstname - assumed 'firstname' in C:\wamp64\www\justread\session.php on line 12.
Now, I know the errors want me to do some sort of initialisation for ‘userid’ and ‘firstname’ first before using them to set up a session variable but I am not sure how to go about it, so I am wondering if someone could help me, please.
Thanking you in advance.
I can post more codes if required but the codes I believe are concerned are:
login.php:
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
// Storing Session
$user_check = $_SESSION['login_user'];
$_SESSION['user_id'] = userid;
$_SESSION['user_firstname'] = firstname;
// Test to see the content of the global session variable
print_r($_SESSION);
// SQL Query To Fetch Complete Information Of User
$ses_sql = mysqli_query($mysqli, "SELECT username FROM logins WHERE username='$user_check'");
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['username'];
if (!isset($login_session)) {
// Closing Connection
mysqli_close($mysqli);
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
In PHP, variable name starts with '$' sign. Also, in login.php, you have to fetch the data using mysqli_fetch_row or any similar function. Am assuming you are redirecting to session.php after logging in. In that case, you don't have to assign anything to the session variables. It will be there already. All you have to do is to access it.
login.php
<?php
// Start session
session_start();
// Variable to store error message
$error ="";
// If the login form (Note that the 'submit' refers to the 'name' attribute of the login form) has been submitted...
if (isset($_POST['submit'])) {
// If username or password is not provided...
if (empty($_POST['username']) || empty($_POST['password'])) {
// ...tell user that login details are invalid.
$error = "Please fill in both your username and your password";
// Else...
} else {
// ...put the provided username and password in variables $username and $password, respectively
$username = $_POST['username'];
$password = $_POST['password'];
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// set up measures to counter potential MySQL injections
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($mysqli, $username);
$password = mysqli_real_escape_string($mysqli, $password);
// Select Database
$db = mysqli_select_db($mysqli, "p00702");
// SQL query to fetch information of registerd users and find user match.
$query = mysqli_query($mysqli, "SELECT * from logins WHERE password='$password' AND username='$username'");
// Return the number of rows of the query result and put it in $rows variable
$rows = mysqli_num_rows($query);
// If rows are equal to one...
if ($rows == 1) {
$row = mysql_fetch_object($query);
unset($_SESSION['error']);
// Initialize session with the username of the user...
$_SESSION['login_user'] = $username;
// Set the user ID of the user
$_SESSION['user_id'] = $row->userid;
// Set the user first name of the user
$_SESSION['user_firstname'] = $row->firstname;
// ...and redirect to the homepage.
header("Location: welcome.php");
// Make sure that codes below do not execut upon redirection.
exit;
// Else,
} else {
// and tell user that the login credentials are invalid.
$error = "Your username or password is invalid";
$_SESSION['error'] = $error;
// redirect user to the home page (index.php)
header("Location: index.php");
}
// ...and close connection
mysqli_close($mysqli);
}
}
session.php
<?php
// Establish connection to the server
$mysqli = mysqli_connect("localhost", "root", "");
// Selecting Database
$db = mysqli_select_db($mysqli, "p00702");
// Starting session
session_start();
if (!isset($_SESSION['user_id'])) {
// Closing Connection
// Redirecting To Home Page
header('Location: index.php');
// Make sure that codes below do not execut upon redirection.
exit;
}
print_r($_SESSION);
Also, move the connection part to a seperate file and include it in all scripts, so that when your credentials change, you don't have to change it in all the files.
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.
I am trying to use the below code to create a login form. The problem being after registration when I am trying to login, getting an error message "Username or Password don't match" even though email & password are correct. I tried "$num <=1" and allows me to log in but obviously it is not authenticating the login details in that case. Any help will be appreciated.Most importantly this code is working fine on a local server like XAMPP but problem starts when using a host server like hostgator (no issue to connect with the server).
<?php
session_start(); // Starting Session
#Database connection
include('../config/connection.php');
$error=''; // Variable To Store Error Message
if (isset($_POST['submit']))
{
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = '<p class="alert alert-danger">One or either field is missing</p>';
}
else
{
// Define $username and $password
$email=$_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection for Security purpose
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
// SQL query to fetch information of registerd users and finds user match.
$q = "SELECT * FROM users WHERE email = '$email' AND password = md5(SHA1('$password'))";
$r = mysqli_query($dbc, $q)or die(mysqli_error());
$num = mysqli_num_rows($r);
if($num ==1){
$_SESSION['username'] = $email;
header('Location:Index.php');
} else {
$error = '<p class="alert alert-danger">Username or Password don\'t match</p>';
}
mysqli_close($dbc); // Closing Connection
}
}
?>
in your query the $password should not be between the quotes, cause then it will seek for the string instead of the value of the variable.
$q = "SELECT * FROM users WHERE email = '$email' AND password = 'md5(SHA1($password))'";
make sure your password is hashed in your database
I have a login form in php which I have connected to a sql database in phpmyadmin. The script I have written should get the email and password variables from the user. It should then check the database to make sure the user is registered. Then either redirect the user to their account or notify the user that their details didnt match up and ask them to try again. However no matter what way I change the code it will always redirect to the account page even if the data I submit through the form is random info.
Any help or advice would be great. Thanks.
Here is my code
<?php
//require_once 'includes/db_connect.php';//
//require_once 'includes/functions.php';//
$con=mysqli_connect("x","m","z","m");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start(); //starting a PHP session.
if (isset($_SESSION['logged'])){
header("Location:account.html");
exit();
}
$email = $_POST['email'];
$password =($_POST['password']);
$sql = mysqli_query($con,"SELECT * FROM `websiteusers` WHERE email ='" . $email . "' and password ='" . $password . "'") or die (mysqli_error($sql));
$count = mysqli_num_rows($sql);
//$row=mysqli_fetch_array($query);//
if ($count==1){
$_SESSION[logged] = 1;
$_SESSION['email'] = $email;
$_SESSION['password'] =$password;
header("location:account.html"); /* Redirect the browser */
}
else {
echo "Sorry those details are not in the database. Click here <a href=\"memberlogin.html\"</a> to try again.";
}
exit();
?>
It's because of the Session Index which you used $_SESSION[logged] and should be $_SESSION['logged']
if ($count==1){
$_SESSION['logged'] = 1;
$_SESSION['email'] = $email;
$_SESSION['password'] =$password;
header("location:account.html"); /* Redirect the browser */
}
You forgot '' in the $_SESSION[logged] variable, it should be $_SESSION['logged']
i have registration form and i want user must be activated their email once user activated their then user can login in the their account else user can't be login?
Problem
The problem is that the users can login without email activation?
Code
$email2=$_POST['email'];
$querycheck=mysql_query("select activation from students
where semail='$email2'") or die ("Query Activated Problem");
$rowcheck=mysql_fetch_array($querycheck);
$act=$rowcheck['activation'];
if($act=='activated')
{
$email=$_POST['email'];
$password=$_POST['password'];
$email = stripslashes($email);
$password= stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
$querymysql=mysql_query("select * from students where semail='$email'
and spassword='$password' ") or die ("query problem");
$row=mysql_fetch_array($querymysql);
if($row)
{
session_register("email");
session_register("password");
header('Location:index.php');
}
else {
$message="Please Check Your Login Details";
header('Location:login.php?login_error='.$message.'');
}
}
else if($act=='')
{
$actmsg="Your Email Is Not Activated Yet";
header('Location:login.php?actmsg='.$actmsg.'');
}
session_register : This function has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
Use $_SESSION directly to set variables.
Add a field tinyint field called activated. Then change your select to
select * from students where semail='$email'
and spassword='$password' "
and activated=1
You activate link should set activated to 1 for the user.
Double check your activation field in the students table. Then, lets convert your code from MySQL to MySQLi. MySQL is already deprecated.
/* ESTABLISH CONNECTION FIRST */
<?php
$connection=mysqli_connect("YourHost","YourUsername","YourPassword","DatabaseName");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$email2=mysqli_real_escape_string($con,$_POST['email']); /* LETS USE REAL ESCAPE STRING TO PREVENT A BIT OF SQL INJECTION */
$querycheck=mysqli_query($connection,"SELECT activation FROM students
WHERE semail='$email2'");
while($rowcheck=mysqli_fetch_array($querycheck)){
$act=$rowcheck['activation'];
}
if($act=='activated')
{
$email=$_POST['email'];
$password=$_POST['password'];
$email = stripslashes($email);
$password= stripslashes($password);
$email = mysqli_real_escape_string($email);
$password = mysqli_real_escape_string($password);
$querymysql=mysqli_query("SELECT * FROM students WHERE semail='$email'
and spassword='$password'");
$row=mysqli_num_rows($querymysql); /* I CHANGED THIS PART OF YOUR CODE */
if($row!=0) /* SO THIS CONDITION ALSO CHANGES */
{
session_register("email");
session_register("password");
header('Location:index.php');
}
else {
$message="Please Check Your Login Details";
header('Location:login.php?login_error='.$message.'');
}
}
else if($act=='')
{
$actmsg="Your Email Is Not Activated Yet";
header('Location:login.php?actmsg='.$actmsg.'');
}
?>