I am having problem with the code.
It suppose to allow admin to view only admin page
and user to view user page only.
my admin still able to view user page.
below is my landing page
<?php
error_reporting(0);
include("config.php");
$host = "localhost"; //DB host
$username = "root"; //DB Username
$password = ""; //DB Password
$db_name = "hklcanet_pha"; //DB Name
$tbl_name = "users"; //Table name, where users are stored
$dbconfig = mysqli_connect($host,$username,$password,$db_name);
$username = $_POST['username']; //Get username from login form
$password = $_POST['password']; //Get password from login form
$username = stripslashes($username); //Makes string safe
$password = stripslashes($password); //Makes string safe
$username = mysqli_real_escape_string($dbconfig, $username); //Makes string safer
$password = mysqli_real_escape_string($dbconfig, $password); //Makes string safer
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; //SQL Query
$result = mysqli_query($dbconfig, $sql); //Executes Query
$rows = mysqli_num_rows($result); //Count rows selected (1 if a username/password combo can be found)
if($rows == 1){
session_start(); //Starts a PHP session
$_SESSION['username'] = $username; //Allows $username to be used later
header("location: interphase1.php");
$query = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($dbconfig, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$permissions = $row['permissions']; //Gets the permissions of the user
$id = $row['id']; //Gets the ID of the user
}
$_SESSION['permissions'] = $permissions; //Allows $permissions to be used later
$_SESSION['id'] = $id; //Allows $id to be used later
$_SESSION['authenticated'] = 1; //Allows $id to be used later
echo("Login Succesful");//Prints success message
}
else
{
//echo("Invalid Username/Password");
}
?>
user page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
echo("You must be logged in");
header("location:landing.php");
}
else
{
if($permissions < 0)
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
admin page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
header("location:landing.php");
echo("You must be logged in");
}
else
{
if($permissions < 1 )
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
thanks and appreciate if somebody can help me on this, still new with the PHP code.
Related
am working with login form but it doesn't work, when am trying to var_dump my sql
<?php
session_start();
include ('database.php');
if (isset($_POST['login'])) {
$user = $_POST['username'];
$pass = sha1($_POST['pass']);
$sql = "SELECT * FROM users WHERE pass = sha1('$pass')
AND username = '$user'";
$query = mysqli_query($conn,$sql);
$results = mysqli_num_rows($query);
//die(var_dump($results));
if ($results == 1) {
$_SESSION['username']=$user;
}
header('location: index.php');
}
?>
I have a login form. I have in my table of the database two records: admin and user. If you login if admin you must go to admin_area.php. this is not working, he always log in if user.
If you login if user this works.
The first part of the script is not working and don't run.
Can someone help me?
thanks in advance.
<?php
//first part: this is not working
session_start();
//if (isset($_POST['submit'])) {
$a_username = $_POST ['username'];
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
{
include 'connect.php';
$sqli = "SELECT * FROM users WHERE username='$a_username' AND password='$a_password' ";
$numrows = mysqli_query($link, $sqli) or die(mysqli_error());
$username = 'username';
$password = 'password';
//Add some stripslashes
$username = stripslashes($username);
$password = stripslashes($password);
//Check if username and password is good, if it is it will start session
if ($username == $a_username && $password == $a_password)
{
$_SESSION['username'] = 'true';
$_SESSION['username'] = $username;
//Redirect to admin page
header("Location: admin_area.php");exit();
}
}
//second part: this works
$username = $_POST ['username'];
$password = md5( $_POST ['password']);
if($username&&$password)
{
include 'connect.php';
$query = "SELECT * FROM users WHERE username='$username' AND password='$password' ";
$numrows = mysqli_query($link, $query) or die(mysqli_error());
if ($numrows != 0)
{
/
while ($row = mysqli_fetch_assoc ($numrows))
{
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($username==$dbusername&&$password==$dbpassword)
{
echo "you are log in <a href='user.php'>click here for contine</a>, after 4 seconds"; header('Refresh: 4;url=user.php');
$_SESSION ['username'] = $username;
}
else
echo "<h3>incorrect password, <a href='index.php'>click here</a></h3>";
}
else
die ("text");
}
else
die ("text");
//}
?>
$a_password = md5( $_POST ['password']);
if($a_username == "admin" && $a_password=="intel")
This condition is not valid, because
$a_password = md5( $_POST ['password'])
is first converted to md5 format and then checked $a_password=="intel"
$a_password is now in md5 format and intel is normal string. For this first try to match normal $a_password like
$a_password = $_POST ['password']
and write your variable into your condition as like
$a_password = md5( $_POST ['password'])
Hi i've made a login script, but it won't log me in, and keeps telling me incorrect match. Here's my code:
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT * FROM user WHERE username = '$usname' AND usertype = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row['username'];
$dbPassword = $row['password'];
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
The username is admin, and passcode is PPsleep1 and the usertype is 1, you can try yourself: http://daltyapps.com/daltyapps/portfolio/paypal/log/index.php
With the current situation, I can suggest you following fixes in the code:
<?php
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
// use both username and password to retrieve records from table
$sql = "SELECT * FROM user WHERE username = '$usname' AND password = '$paswd' AND usertype = '1'";
$query = mysqli_query($dbCon, $sql);
if($query) // check if query runs properly or is having any error
{
if(mysqli_num_rows($query) == 1) // check if ony one user with 'USERNAME - PASSWORD' pair exists in database
{
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[INDEX_OF_USERNAME_FIELD];
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
}
else
{
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
}
else
{
echo "Error in query ".mysqli_error($dbCon);
}
?>
Use below code,
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT * FROM user WHERE username = '$usname' AND usertype = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_array($query); /*comment - have replace row with array*/
$uid = $row[0];
$dbUsname = $row['username'];
$dbPassword = $row['password'];
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
Second option to use,
include_once("dbConnect.php");
// Set the posted data from the form into local variables
$usname = strip_tags($_POST['username']);
$paswd = strip_tags($_POST['password']);
$usname = mysqli_real_escape_string($dbCon, $usname);
$paswd = mysqli_real_escape_string($dbCon, $paswd);
$sql = "SELECT * FROM user WHERE username = '$usname' AND usertype = '1' LIMIT 1";
$query = mysqli_query($dbCon, $sql);
$row = mysqli_fetch_row($query);
$uid = $row[0];
$dbUsname = $row[1]; /*comment - if column username after column id in table */
$dbPassword = $row[2]; /*comment - if column password after column username in table*/
// Check if the username and the password they entered was correct
if ($usname == $dbUsname && $paswd == $dbPassword) {
// Set session
$_SESSION['username'] = $usname;
$_SESSION['id'] = $uid;
// Now direct to users feed
header("Location: user.php");
} else {
echo "<h2>Oops that username or password combination was incorrect.
<br /> Please try again.</h2>";
}
This is my auth file
i got a db with
username
password
email
positief(here is a "1" or a "0", a "1" if you got admin rights)
I want my code to recognize the "1" and give you acces to a page if you have the 1""
if you dont you can't enter it.
<html>
<body>
<?php
session_start(); // Create the session, Ready for our login data.
$username = $_POST['username']; // Gets the username from the login.php page.
$password = $_POST['password']; // Gets the plain text password.
$database = "cmict_test";
// Connect to your database
mysql_connect("","","") or die(mysql_error());
mysql_select_db("$database");
$query = "SELECT * FROM users WHERE password = '$password' LIMIT 1";
$username = mysql_real_escape_string($username); // just to be sure.
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$resusername = $row['username']; // username from DB
$respassword = $row['password']; // password from DB
$resemail = $row['email']; // email from db
$admin = $row['positief'];
}
// Are they a valid user?
if ($resusername == $username && $respassword == $password) {
// Yes they are.
// Lets put some data in our session vars and mark them as logged in.
$_SESSION['loggedin'] = "1";
$_SESSION['email'] = $resemail;
$_SESSION['username'] = $resusername;
header("location:navigra.php");
}else{
// No, Lets mark them as invalid.
$_SESSION['loggedin'] = "0";
echo "Sorry, Invalid details.<br>";
die ('klik hier om opnieuw te proberen.');
}
if ($admin == 1) {
$_SESSION['logadmin'] = "1";
} else {
$_SESSION['logadmin'] = "0"
echo "You are no admin";
die ('klik hier');
}
?>
</body>
</html>
and this is what i put on top of the page
to check if you are loggedin and if you got admin rights
<?php
session_start(); // Start the session
$loggedin = $_SESSION['loggedin']; // Are they loggedin?
$logadmin = $_SESSION['logadmin']; // Are they admin?
// They are not logged in, Kill the page and ask them to login.
if ($loggedin != "1") {
die('Sorry you are not logged in, please click Here to
login');}
if ($logadmin != "1") {
die ('You have no POWER here');}
?>
Can someone help me with this? i would appreciate it alot.
Thank you in advance!
Greetings,
DTcodedude
<html>
<body>
<?php
session_start(); // Create the session, Ready for our login data.
$username = addslashes($_POST['username']); // Gets the username from the login.php page.
$password = addslashes($_POST['password']); // Gets the plain text password.
$database = "cmict_test";
// Connect to your database
mysql_connect("","","") or die(mysql_error());
mysql_select_db("$database");
$query = "SELECT * FROM users WHERE username = '$username' and password = '$password' LIMIT 1";
$username = mysql_real_escape_string($username); // just to be sure.
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$resusername = $row['username']; // username from DB
$respassword = $row['password']; // password from DB
$resemail = $row['email']; // email from db
$admin = $row['positief'];
}
// Are they a valid user?
if ($resusername == $username && $respassword == $password) {
// Yes they are.
// Lets put some data in our session vars and mark them as logged in.
$_SESSION['loggedin'] = "1";
$_SESSION['email'] = $resemail;
$_SESSION['username'] = $resusername;
$_SESSION['logadmin'] = $admin;
header("location:navigra.php");
}else{
// No, Lets mark them as invalid.
$_SESSION['loggedin'] = "0";
echo "Sorry, Invalid details.<br>";
die ('klik hier om opnieuw te proberen.');
}
?>
</body>
</html>
EDIT :
-added check on username in sql query (as suggested by Jason)
-added addslashes for basic protection against SQL injection.
After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;