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.
Related
I created a login system where after login, the user will be redirected to profile.php. In the profile.php page, the heading will say Welcome [username]
Session.php:
$connection = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($connection, "id2290767_wp");
session_start();
$user_check = isset($_SESSION['login_user']);
$ses_sql = mysqli_query($connection, "select name from login where name='$user_check'");
$row = mysqli_fetch_assoc($ses_sql);
$login_session = $row['name'];
if(!empty($login_session)) {
mysqli_close($connection);
header('Location: members.php');
}
profile.php (the one with the greetings)
<?php
include('session.php');
if(!isset($_SESSION['login_user'])){
header("location: profile.php");
}
?>
<h1>Welcome <i><?php echo $login_session; ?></h1>
The signin.php linked with the login form in members.php:
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if(isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysqli_connect("localhost", "root", "");
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
// Selecting Database
$db = mysqli_select_db($connection, "id2290767_wp");
// SQL query to fetch information of registerd users and finds user match.
$query = mysqli_query($connection, "select * from login where password='$password' AND name='$username'");
$rows = mysqli_num_rows($query);
if($rows == 1) {
$_SESSION['login_user'] = $username; // Initializing Session
header("location: profile.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysqli_close($connection); // Closing Connection
}
}
members.php:
<?php
include('signin.php'); // Includes Login Script
if(isset($_SESSION['login_user'])){
header("location: profile.php");
}
But I get no text in the PHP page. It just says "Welcome".
What did I do wrong?
EDIT: Getting infinite loop after changing
$user_check = isset($_SESSION['login_user']);
to
$user_check=isset($_SESSION['login_user']) ? $_SESSION['login_user'] : "";
The isset () function is used to check whether a variable is set or not.
Change
$user_check=isset($_SESSION['login_user']);
To
$user_check=isset($_SESSION['login_user']) ? $_SESSION['login_user'] : "";
Here is the code for the login part. The problem I beleive is where this line starts ----> if (mysqli_num_rows($result) == 1)
I think that is the start of the problem as the page does not redirect to the other page upon the click.
If anybody has any ideas, that would be greatly appreciated.
<?php
session_start();
ob_start();
// connect to database
$db = mysqli_connect("localhost", "root", "", "authentication");
if (isset($_POST['login_btn'])) {
$_SESSION['message'] = "";
$username = mysqli_real_escape_string($db,$_POST['username']);
$username = $_POST['username'];
$password = mysqli_real_escape_string($db,$_POST['password']);
$password = md5($password); // remember we hashed password before storing last time
$sql = "SELECT * FROM users WHERE username ='$username' AND password='$password'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) == 1) {
$_SESSION['username'] = "You are now logged in";
$_SESSION['password'] = $username;
session_write_close();
header("location:register.php"); //redirect to home page
exit();
}else{
$_SESSION['message'] = "Username/password combination incorrect";
}
}
?>
I know this one has been asked before but have not been able to find a solution on previous questions.
Secure hash and salt for PHP passwords
Password verifying against database using bcrypt
php password_verify not working with database
I'm attempting to hash the password when registering and then verify it when trying to login. The query is retrieving the password associated with the username however isn't being verified correctly.
The problem is the way I am trying to use password_verify but no matter what I'v tried the past few hours I haven't been able to get it working. If anyone could take a look and try spot what I'm doing wrong it would be a great help.
The DB column length is set to 255 and Varchar to allow the full hash entry.
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_array($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
So I know the hash being returned from the database is being set in the $stored_hash variable correctly as if I hard code the hash returned from it and compare it, login is correct. Could it be something altering the input somewhere?
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
Function is_valid_entry($inputData,$validData)
{
$inputData_array = str_split($inputData);
$validData_array = str_split($validData);
$i = 0;
while ($i < sizeof($inputData_array))
{
if (!in_array($inputData_array[$i],$validData_array))
{
return false;
}
$i++;
}
return true;
}
//User defined global variables go here
$username = "";
$ID = "";
$errorMessage = "";
$valid_chars = "abcdefghijklmnopqrstuvwxyz
1234567890";
session_start(); //start a session
if (isset($_POST['submit'])) { //submit button has been clicked
$username = $_POST['username'];
$username = trim($username); //trim any white spaces in the input value
$username = lcfirst($username); //attempts to convert upper case to lower
$username = htmlspecialchars($username); //convert special chars to html rendering null
$username = strip_tags($username); //Strip tags from input string
$ID = $_POST['ID']; //read in the value the user has entered for the password and assign to $ID
$ID = htmlspecialchars($ID);
$ID = strip_tags($ID);
$ID = trim($ID);
if (!is_numeric($ID)) { //if $ID is not numeric redirect to login page
$errorMessage = "Invalid username or password.";
$_SESSION['error'] = $errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php');
} else if (!is_valid_entry($username,$valid_chars)) { //check that user name is a valid char
$errorMessage = "Invalid username or password";
$_SESSION['error'] = errorMessage; //sets the value of the 'errorMessage' session variable
$_SESSION['login'] = ""; //set the value of the 'login' session variable to ''
//redirect to login page & send error message
header('Location: login.php'); //redirect the user to the login page
} else { //if user name & $id are both valid
//now check if they are in the database
$mySQL_Server = "127.0.0.1";
$db_userName = "root";
$db_password = "";
$database = "projectdatabase";
//connect to the database on the MySQL server & store the connection in $conn
$conn = mysqli_connect($mySQL_Server, $db_userName, $db_password, $database);
if (mysqli_connect_errno($conn))
{
print("Error connecting to MySQL database: " . mysqli_connect_error($conn));
} else
{
print("Connected to the MySQL database");
}
$SQL_Query = "SELECT * FROM user_information WHERE userName = '".$username."'";
$result = mysqli_query($conn, $SQL_Query);
$num_rows = mysqli_num_rows($result);
//below is the algorithm being used on the registration page
//$hash = password_hash($ID, PASSWORD_BCRYPT, array('cost'=>10));
if ($num_rows > 0)
{ //if there is match for the query within the database
while($row = mysqli_fetch_assoc($result)) //attempts to retrieve the password associated with the username
{
$row['password'];
$stored_hash = $row['password'];
}
if(password_verify($ID, $stored_hash))
{
$_SESSION['login'] = "1";
$_SESSION['username']= $username;
header('Location: stats.php'); //login success
} else {
$errorMessage = "$ID, $stored_hash"; //test to ensure is reaching this statement
$_SESSION['error'] = $errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
} else {
$errorMessage = "Login Unsuccessful";
$_SESSION['error']=$errorMessage;
$_SESSION['login'] = "";
header('Location: login.php'); //redirect the user to the login page
}
mysqli_close($conn);
}
}
?>
My problem with this code is that the IF statement which is deciding what page to go to seems to default to index.php. I have made a login table in MySQL already and have username/password column, and another column with a boolean value which states if the user is admin.
session_start(); // Starting Session
$error = ''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
} else {
// Define $username and $password
$username = $_POST['username'];
$password = $_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
$count = mysql_num_rows($result);
$auth = $row['admin'];
if ($count == 1) {
if ($auth['admin'] == 1) {
session_start();
$_SESSION['admin'] = $auth;
$_SESSION['username'] = $username;
header("location: member.php");
} elseif ($auth['admin'] == 0) {
session_start();
$_SESSION['admin'] = $auth;
header("location:index.php");
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
Since you already extracted your admin value here:
$auth=$row['admin'];
You don't have to extract it here:
if($auth['admin']==1){
or here:
elseif($auth['admin']==0){
This simple change should fix your problem:
if($auth==1) {
...
} elseif($auth==0) {
...
In your original code, $auth['admin'] doesn't exist because $auth itself is just an integer, so it will pass the $auth['admin'] == 0 test since it is "falsy."
Also, it looks like you may have a case where $auth is completely undefined, in which case you should use "strict comparison" for that second condition, so you're looking for an actual zero and not just anything falsy:
} elseif($auth===0) {
I re wrote your login script. Try this. I think you'll find this will work much better for what your doing.
if(isset($_POST['username'])) {
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($username);
$password = $_POST['password'];
//$password = md5($password);
$db_host = "host"; $db_username = "username"; $db_pass = "password"; $db_name = "db_name"; mysql_connect("$db_host","$db_username","$db_pass"); mysql_select_db("$db_name"); // connect to your database only if username is set
$sql = mysql_query("SELECT * FROM login WHERE username='$username' and password='$password'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){ // if the user exists run while loop below
session_start(); // start session here (only once)
while($row = mysql_fetch_array($sql)){ // fetch the users admin from query
$auth = $row['admin'];
$_SESSION['admin'] = $auth; // set admin session variable
$_SESSION['username'] = $username; // set username session variable
if($auth == 1){
header("location: member.php"); // if user auth is 1, send to member
}else if($auth == 0){
header("location: index.php"); // if user auth is 0, send to index
}
exit();
}
} else {
header('Location: login.php'); // if user doesnt exist, reload login page.
}
mysql_close();
}
I recommend using md5 hash passwords.
When a person registers at your site, you can convert the password to md5 hash with this line $password = md5($password); prior to the db entry
Regarding your $auth above, this assumes your entry in the database is either a 0 or a 1. If you are controlling it this way, i recommend using enum in the sql database. set the type to "enum" and the type to '0', '1'
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect(" ", " ", " ", " ");
// Selecting Database
$db = mysql_select_db(" ", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = "SELECT * FROM login WHERE username='$username' and password='$password'";
$result=mysql_query($query) or die(mysql_error());
$row= mysql_fetch_array($result);
$count=mysql_num_rows($result);
$auth= (int)$row['admin'];
if($count){
if($auth == 1){
$_SESSION['admin']= $auth;
$_SESSION['username']= $username;
header("location: member.php");
exit;
}elseif($auth == 0){
$_SESSION['admin']= $auth;
header("location:index.php");
exit;
}
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
}
?>
Try
header("Location: index.php");
exit;
header("Location: member.php");
exit;
Note the Capital L and the exit;
Also try if($auth == "1") and elseif($auth == "0") respectively.
If you value the security of your login page, use PDO or mysqli instead of mysql. It is deprecated and insecure due to its vulnerability to SQL injection.
Also, take advantage of PhP's password_hash and password_verifywhen handling storage and verification of passwords. It is a lot more secure compared to md5(). If you'd like examples of usage, let me know.
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;