Restrict access to pages using sessions - php

I have used a login system on my website using sessions.
This is how it looks,
<?php
session_start();
ob_start();
include 'includes/db.php';
$idadm=$_POST['idadm'];
$passadm=$_POST['passadm'];
$idadm = stripslashes($idadm);
$passadm = stripslashes($passadm);
$idadm = mysql_real_escape_string($idadm);
$passadm = mysql_real_escape_string($passadm);
$sql="SELECT * FROM admin WHERE aid='$idadm' and password='$passadm'";
$result = $conn->query($sql);
$count = $result->num_rows;
if($count == 1) {
$_SESSION['idadm'] = $idadm;
$_SESSION['passadm'] = $passadm;
if ($_SESSION['idadm'] == 'admin') {
header("location:admin/index.php");
} else {
header("location:subadmin/index.php");
}
} else {
header("location:index.php");
}
ob_end_flush();
?>
db.php has the database credentials.
This is the code that is on top of the protected pages,
<?php
session_start();
if (!isset($_SESSION['idadm'])) {
header('location:/index.php');
die;
}
?>
The login script works fine except for one problem, logged in users can access both admin and subadmin pages.
There is only one admin user and the ID for that user in the database is 'admin'. Admin should be able to access only 'admin/index.php' and other users should be able to access 'subadmin/index.php'.
How do I modify the script to make this happen?

So, first up, get the $_SESSION["idadm"] and $_SESSION['passadm']...
So firstly in your admin page would be this:
<?php
session_start();
if (!isset($_SESSION['idadm'])) {
header('location:/index.php');
die;
} else {
$username = $_SESSION["idadm"];
$password = $_SESSION['passadm']; // Also storing passwords in session vars is not a good idea. :/
Then open up a DB connection:
$pdo = new PDO($dsn, $DBUsername, $DBPass):
// or
$mysqli = mysqli_connect($host, $DBUsername, $DBPass, "admin")
Then check if current username and password is there in the DB...
I am doing it in PDO:
$sth = $pdo->prepare("SELECT COUNT(*) AS number_of_users FROM table_name WHERE aid = :username AND password = :password");
$sth->bindParam(":username", $username, PDO::PARAM_STR);
$sth->bindParam(":password", hash("YOUR_HASHING_ALGO", $password), PDO::PARAM_STR); // If you have not hashed the password you can remove the hash method, but not hashing a password is a horrible idea
$result = $sth->fetch(PDO::FETCH_ASSOC);
if( (int) $result["number_of_users"] >= 1 ) {
// yay he is an admin, do somethin'
} else {
// nope, he is not allowed to enter, what to do with him?
}
And at last close the else block with :
}
In the connection string's you have to use your own specific credentials and DB.
Hope it helps you!

Related

admin and user login php mysql form

Hey guys this is my php file named login.php. so whats my question. I want to have 2 user members: 1 admin and 1 user. admin and user must have different pages. In my code i have only user and if you will type normal users username and password it will lead you to the users page, but i cant do same on admins username and password it shows nothing.Help me guys to make admins login too.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$tbl_name = "users";
$tbl_name1 = "admins";
mysql_connect($host, $user, $pass) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());
if(isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1 ";
$res = mysql_query($sql);
if(mysql_num_rows($res) == 1) {
header("location:update.php");
echo "You have successfuly logged in.";
exit();
} else {
// session_register("username");
// session_register("password");
echo "Invalid logind information. Please return to the previous page";
header("location:login.php");
exit();
}
}
?>
Firstly, get rid of mysql, and use mysqli. mysql is deprecated and has been removed in PHP 7.
Secondly, assuming you have switched to mysqli, you can store groups inside your user database in a new column that you can check for.
if($row["group"] == 'admin') {
//Display admin webpage
} else {
//Display user webpage
}

PHP-MySQL Login system

This is the first time I'm using PHP and MySQL to make a login system where a person can enter username and password and the php scripts checks if the username and password exists in the database.
When the user enters the correct info It displays the "SUCCESSFULLY LOGIN TO USER PROFILE PAGE..." message which is all good. But if the user enters in the wrong info, the "SORRY...YOU ENTERED WRONG ID AND PASSWORD...PLEASE RETRY..." message should appear but the page is blank. Why is that?
<?php
define('DB_HOST','localhost');
define('DB_NAME','test'); //name of database
define('DB_USER','root'); //mysql user
define('DB_PASSWORD',''); //mysql password
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
$db = mysqli_select_db($con,DB_NAME) or die(mysqli_connect_error());
/*
$ID = $_POST['user'];
$Password = $_POST['pass'];
*/
function SignIn(mysqli $con){
session_start(); //starting the session for user profile page
if(!empty($_POST['user'])){ //checing the 'user' name which is from Sign-in.html, is it empty or have some text
$query = mysqli_query($con,"SELECT * FROM UserName where userName = '$_POST[user]' AND pass = '$_POST[pass]'") or die(mysqli_connect_error());
$row = mysqli_fetch_array($query) or die(mysql_error());
if(!empty($row['userName']) AND !empty($row['pass'])){
$_SESSION['userName'] = $row['pass'];
echo "SUCCESSFULLY LOGIN TO USER PROFILE PAGE...";
}
else{
echo "SORRY...YOU ENTERED WRONG ID AND PASSWORD...PLEASE RETRY...";
}
}
}
if(isset($_POST['submit'])){
SignIn($con);
}
?>
Firstly, I have to state that your code is highly prone to SQL injection <= do read that, not to mention storing passwords in plain text which is highly discouraged.
Do not store passwords in plain text, you will eventually get hacked.
Consult my footnotes about all of the above, regarding injection and password storage.
You're also mixing MySQL APIs with mysql_error() which doesn't intermix with mysqli_ functions. It needs to be mysqli_error($con).
Now, your code is failing because of this line:
if(!empty($row['userName']) AND !empty($row['pass']))
Even though a person enters a wrong or inexistant username and/or password, it will still remain TRUE because those rows are NOT empty.
Therefore it never gets to enter the else part of your script.
To get you started, here is what you need to do:
Replace:
if(!empty($row['userName']) AND !empty($row['pass']))
with:
$row = mysqli_fetch_array($query);
$username = $row['userName'];
$pw = $row['pass'];
if($user==$username && $pass==$pw) {
// $user and $pass are from POST
// $username and $pw are from the rows
$_SESSION['userName'] = $row['pass'];
echo "Successfully logged in.";
}
else { echo "Invalid."; }
While using the following inside the SignIn() function:
$user = mysqli_real_escape_string($con,$_POST['user']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
and replacing your query with:
$query = mysqli_query($con,"SELECT * FROM UserName
where userName = '$user'
AND pass = '$pass'")
or die(mysqli_connect_error());
Footnotes:
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function.
For PHP < 5.5 use the password_hash() compatibility pack.
Plus, in regards to SQL injection, use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
Edit:
Oh yea and also I changed my code to yours, but now everytime I login It displays Invalid, even with the right username and password. Any ideas?It seems to be failing the if($user==$username && $pass==$pw) if statement.
Here's what I used to test it with, you can replace the DB credentials with your own and other adjustments, since I did not use a form, but hard-coded values.
This did in fact jump in the else if an incorrect user/password was entered.
<?php
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME) or die(mysqli_connect_error());
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
}
function SignIn($con){
$_POST['user'] = "John";
$user = $_POST['user'];
$_POST['pass'] = "12345";
$pass = $_POST['pass'];
// session_start(); //starting the session for user profile page
if(isset($_POST['user'])){
$query = mysqli_query($con,"SELECT *
FROM UserName where userName = '$_POST[user]'
AND pass = '$_POST[pass]'")
or die(mysqli_connect_error());
$row = mysqli_fetch_array($query);
$username = $row['userName'];
$pw = $row['pass'];
if($user==$username && $pass==$pw) {
echo "Successfully logged in.";
}
else { echo "Invalid"; }
} // brace for isset post user
} // brace for function
if(isset($_POST['submit'])){
echo SignIn($con);
}
?>
Before I get to the actually answer to you question, I would recommend you to use mysqli_real_escape_string() for both username and password. You could use PDO which does it all for you and in my opinion is less work.
The problem you have is that your forgot to add another else block on the first if statement.
if(!empty($_POST['user'])) {
// first block
if(!empty($row['userName']) AND !empty($row['pass'])) {
// first inner block
} else {
}
} else {
// this else is what your missing
}

PHP How to also check if active

I have a problem with my code. Or rather don't know how to implement what I would like to have.
I would like; Also in this code, check if the username have a 1 in active column. and if so the proceed to login protected page else return to login page.
<?php
session_start();
function validateUser(){
session_regenerate_id ();
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
$username = $_POST['username'];
$password = > $_POST['password'];
require('config.inc.php');
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$stmt = $db->prepare("SELECT password_hash FROM users WHERE username =:username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR,32);
$stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC);
$db=null;
$dbhash = $result['password_hash'];
if ($dbhash == crypt($password, $dbhash)){
validateUser();
header('Location: ../main.php');
}else{
header('Location: ../index.php?invalidcreds=1');
die();
}
?>
So what you guys think? I have tried everything but can't get it to work.
Also I would like to have a admin column no/0 or yes/1 so I can protect certain links or text in my page. But first thing first.
You can add an is_active column in your db then use:
SELECT is_active, password_hash FROM users where username=:username
In your php just use:
if($result['is_active'])
{
//Send to restricted login
}
else
{
//Send to normal login
}
Also, like I said in a comment, you have a stray > when you initialize your password variable. It may be a reason why your code isn't working.
Okay so this is the code and it work perfect. And the > was just a typo sorry. Thanks Bun for your super easy code.
Does this look okay? Or just plain wrong. I'm a bit unsure of the if code or is this the way to go!?
<?php
session_start();
function validateUser(){
session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
}
$username = $_POST['username'];
$password = $_POST['password'];
require('config.inc.php');
$db = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$stmt = $db->prepare("SELECT active, password_hash FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR, 32);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$db =null;
if($result['active']){
$dbhash = $result['password_hash'];
if ($dbhash == crypt($password, $dbhash))
validateUser();
header('Location: ../main.php');
}
else{
header('Location: ../index.php?invalidcreds=1');
die();
}
?>
But now if I would like to do a admin column too and try to implement this here, how would I do this? I know there needs to be added perhaps a bit more code in other places also. Nothing pretty or advanced. It's just a simple login so. Any advice where I should direct my eyes at, private/public classes (I've tried this but I got lost in the code totaly)

Retrieve data from mysql database

I have made a database with columns Email, FirstName, LastName, Password.. etc
My login page uses email and password for logging in
I want to retrieve the name typed in LastName column in the same row as Email
I would like to know how to do so
My code looks like this:-
$query=mysql_query("SELECT * FROM Users WHERE email='$email' AND
`password`='$encrypted_pass' ");
After this, I want to be able to assign a variable to the LastName so I could create a session along with login
Then you specify the column in the column list:
SELECT LastName
FROM Users
WHERE email = '$email'
...
You then need fetch the result set to assign it to a variable.
mysql_ functions are officially deprecated and no longer maintained/safe to use.
You should use PHP's PDO instead as it is a safer and more object-oriented approach.
Just fill in DB_NAME, DB_USER_NAME, and DB_USER_PASS with your specific credentials and this code should work for you.
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME;charset=UTF-8', 'DB_USER_NAME', 'DB_USER_PASS' );
$query = $database->prepare( "SELECT * FROM Users WHERE `email` = ? AND `password` = ? " );
$query->bindValue( 1, $email );
$query->bindValue( 2, $encrypted_pass );
$query->execute();
if( $query->rowCount() > 0 ) { # If rows are found for query
$result = $query->fetch( PDO::FETCH_ASSOC );
echo $result[ 'LastName' ]; # <-- The LastName field you were looking for!
}
else { echo "No Rows Returned!"; }
For more information of PHP PDO, please see http://www.php.net/manual/en/book.pdo.php
I think this covers everything you asked for. Starts a session, checks if it is good, setup a couple of variables for our post data, do some data validation, setup the query, query the db, check results, set var lastname in session.
<?php
header('Content-type: text/html');
session_start();
if (session_id() === '') {
echo 'session_id is null!';
exit;
}
$myemail = null;
$mypassword = null;
if (isset($_POST['Submit']) == true) {
//assuming you have a db connection
//mysql_connect($host, $user, $password) || die(mysql_error());
//mysql_select_db($database) || die(mysql_error());
if ((isset($_POST["username"]) === false)||
(isset($_POST["password"]) === false)) {
echo 'Please fill in all fields';
exit;
} else {
// get the post data
$myemail = ($_POST["username"]);
$mypassword = ($_POST["password"]);
}
// check the form in database
$sql = "SELECT * FROM Users WHERE email = '".$myemail."'
AND password = '".$mypassword."'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$_SESSION['loggedin'] = false;
if ($count === 1) {
$userrecord = mysql_fetch_array($result);
$_SESSION['username'] = $userrecord['username'];
$_SESSION['password'] = $userrecord['password'];
$_SESSION['loggedin'] = true;
$_SESSION['lastname'] = $userrecord['lastname'];
// assign last name to a session var
echo 'You have been logged in successfully";
} else {
echo 'Wrong username or password';
exit;
}
} else {
echo "No form post detected.<br><br>";
}
?>
Here's some basic stuff using Mysqli since mysql_ commands are deprecated. Again, it uses some common names so adjust accordingly.
/********************************/
// using mysqli (untested but should work)
/********************************/
$mysqli = new mysqli("localhost", "dbuser", "dbpassword", "default_dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// ecsape the query params
$myemail = $mysqli->real_escape_string($myemail);
$mypassword = $mysqli->real_escape_string($mypassword);
if ($mysqli->query("SELECT * FROM Users WHERE email = '$myemail'
AND password = '$mypassword'")) {
printf("%d Rows returned.\n", $mysqli->affected_rows);
// here is where you can set the $_SESSION vars
// and do any other work you want to do on login.
}
$mysqli->close();
/********************************/
//end mysqli
/********************************/
One last thing. Get yourself a GitHub.com repository setup so you can easily rollback to a prior version. It really is a must have IMO.

PHP/MySQL mysql_num_rows not returning values

I'm new to PHP and programming in general, but am working on doing a login. I've got the signup page completed, and my database populates the records fine. However, when this code gets output it says I have 0 rows from the mysql_num_rows($result);... when, it should be coming back successfully showing 1 row when I input the correct username/password. Whether I put in a successful user/pass combo or not, it outputs the same.
I appreciate any help you can provide, code is listed below:
$SQL = "SELECT * FROM account WHERE username = $username AND password = md5($password)";
$result = mysql_query($SQL);
$num_rows = mysql_num_rows($result);
echo $result;
echo $num_rows;
// CLOSE CONNECTION
mysql_close($db_handle);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($result) {
if ($num_rows > 0) {
session_start();
$_SESSION['login'] = "1";
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $num_rows;
EDIT: Complete rewrite
Try this:
<?php
$host = "host";
$user = "user";
$password = "password";
$database = "database";
$username = 'jack'; /* Insert $_Post [''] here with username variable you pass. You could sanitize and validate with for example filter_var (), clean (), etc */
$password_user = 'password from jack'; // same here.
$link = mysqli_connect($host, $user, $password, $database);
IF (!$link){
echo ("Unable to connect to database!");
}
ELSE{
$query = "SELECT * FROM account WHERE username ='$username' AND password = md5('$password_user')";
$result = mysqli_query($link, $query);
$num_rows = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
// COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS PAGE
if ($row) {
session_start();
$_SESSION['login'] = "1"; // pleae not that 1 is converted into a string value
$_SESSION['username'] = $username; // added username, just to test.
header ("Location: page1.php");
}
else {
$error_message = "Login failed. Please try again.";
echo $error_message;
}
// CLOSE CONNECTION
mysqli_close($link);
}
?>
Sample data:
CREATE TABLE account (
id INT auto_increment primary key,
username VARCHAR(30),
password VARCHAR(50)
);
INSERT INTO account(username, password)
VALUES
("bob", md5('password from bob')),
("jack", md5('password from jack')),
('joe', md5('password from joe'));
SQL FIDDLE DEMO
Sample page1
<?php
session_start();
$login = $_SESSION['login'];
$username = $_SESSION['username'];
echo '<h1>It WORKS, <i>'.$username.'</i>!!!</h1>';
?>
Important to note is that I have used the MYSQLI library instead of the MYSQL library. If you have more than one column in you table you should select your output per column. For example, $result['id'].
I found that you didn't escape variable in and out in you SQL statement. I have to note that I didn't debug the part below COMPARE $num_rows TO SEE IF A SUCCESSFUL LOGIN, THEN DIRECT TO MEMBERS. I think you can manage that on your own.
W.R.T. the santization and validation you have to do some more work. I don't know how you data is past via the user login in form. Let say you will use POST. In that case you can start at the top of you page with first retrieving all the posted variable using $_POST. Then filter them to make sure you code in is not open for SQL injection. E.g. $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);

Categories