How to get two fields while creating session? - php

In my login page I am using a phone number and password fields only to login, thereafter, I am creating and storing a session using the phone number.
Insted, I want to echo the username currently logged in to display the current user becasue in my case I am currently only able to display the phone number of the logged in user. How do I do that?
Here is my login script
<?php
// Starting Session
session_start();
include "../script.php";
$error=''; // Variable To Store Error Message
if (isset($_POST['signin'])) {
if (empty($_POST['signinphone']) || empty($_POST['signpassword'])) {
$error = "Phone or Password is invalid";
}
else
{
// Define $username and $password
$phone=$_POST['signinphone'];
$password=$_POST['signpassword'];
// To protect MySQL injection for Security purpose
$phone = stripslashes($phone);
$password = stripslashes($password);
$phone = pg_escape_string($db, $phone); // Set email variable
$password = pg_escape_string($db, $password); // Set hash variable
$pass_crypted = password_hash($password);
// SQL query to fetch information of registerd users and finds user match.
$sql="SELECT usr_id, usr_email, usr_first_name, usr_last_name,
usr_encrypted_password,
usr_salt, usr_stos_id, usr_pers_id, usr_username, usr_updated_at,
usr_created_at, usr_enabled, usr_role_id, usr_jbrn_id,
usr_mobile_number,
stp_acc_id, usr_location, usr_mobile_imei, usr_type
FROM js_core.stp_users
where usr_mobile_number='$phone'
AND usr_encrypted_password='$password'";
$result=pg_query($db, $sql);
$rows = pg_num_rows($result);
if ($rows == 1) {
$_SESSION['phone']=$phone; // Initializing Session
$_SESSION['username'] = pg_fetch_object($result)->usr_last_name;
header("location: ../index.php");
} else {
//echo "0 results";
echo "Try Again the credentials you entered don't much ours";
}
; // Closing Connection
}
}
?>
and Here is my sample code where I want to display the username inplace of the phone
<li>
<?php
if(isset($_SESSION['username'])) {
echo '<li>'. $_SESSION["username"] . '</li>';
echo '<li>
Log Out</li>';
} else {
echo '<a class="signing" href="#login" data-toggle="modal" data-target="#signIn">Login </a>';
}
?>
</li>

There is not one answer to your question.
I'm posting this because it contains an example of all the things that have been mentioned in the comments to your question.
Firstly, you'll notice that there is a new $db connection that uses the PDO. This is the generally accepted way to handle DB connections and is relatively easy to install (if your php version doesn't have it) - there are plenty of examples on SO. I'd assume you'd want this in your script.php since it's common.
I've also swapped out the password hashing function for the native BCRYPT password_hash() function. When you sign the user up, you would then use it like so:
$encryped_password = password_hash($_POST['signpassword'], PASSWORD_BCRYPT);
This contains a uniquely salted password with the default cost.
Following that, you can fetch the user as you were, with the small adjustment to make it a prepared statement. This provides SQL Injection protection and generally makes things cleaner.
You'll then see that after the row is fetched, you can compare the password with the password_verify() function.
Finally to your original issue - I've set the PDO mode to object, so you can access and assign as many properties as you need to in the same way. Only the properties in the SELECT clause will be available in that object.
// Starting Session
session_start(); //I'd suggest this should also go in your script.php
$db = new PDO('pgsql:dbname=mydb;host=localhost;user=myuser;password=mypass');
include "../script.php";
$error=''; // Variable To Store Error Message
if (isset($_POST['signin'])) {
if (empty($_POST['signinphone']) || empty($_POST['signpassword'])) {
$error = "Phone or Password is invalid";
}
else
{
// SQL query to fetch information of registerd users and finds user match.
$sql = 'SELECT usr_id, usr_email, usr_first_name, usr_last_name, usr_encrypted_password
usr_stos_id, usr_pers_id, usr_username, usr_updated_at,
usr_created_at, usr_enabled, usr_role_id, usr_jbrn_id,
usr_mobile_number, stp_acc_id, usr_location, usr_mobile_imei,
usr_type
FROM js_core.stp_users
WHERE usr_mobile_number = :phone_number';
$stmt = $db->prepare($sql);
$stmt->execute(['phone_number' => $_POST['signinphone']]);
if ($row = $stmt->fetch(PDO::FETCH_OBJ)){
if(password_verify($_POST['signinpassword'], $row->usr_encrypted_password)) {
$_SESSION['phone'] = $row->usr_mobile_number; // Initializing Session
$_SESSION['username'] = $row->usr_username;
header("location: ../index.php");
} else {
//valid user, invalid password
}
} else {
//Invalid user
echo "Try Again the credentials you entered don't much ours";
}
}
}
I've made the assumption that you're running at lease PHP 5.5 for the password_hash, but there is a polyfill if not.

Related

Implementing a check for user levels

I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP

Login system in PHP wont work correctly

for some reason my login script in php keeps returning invalid results, I'm using PHPMYADMIN to handle the database and mysqli to connect however whenever I submit the data though a HTML form the values always return false even if the correct username and password combo is working.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysql_connect("localhost","cnathanielwcol","","login");
if(! $con){die('Connection Failed'.mysql_error());}
$result = mysqli_query("SELECT * FROM login");
$row = mysql_fetch_array($result);
var_dump($row);
if ($row["username"]==$username) {
echo "Correct Username<br>";
} else {
echo "Wrong Username<br>";
}
if ($row["password"]==$password) {
echo "Correct Password<br>";
} else {
echo "Wrong Password<br>";
}
echo "<br><br>Username Submited Via HTML: <b>" . $username . "</b>";
echo "<br>Password Submited Via HTML: <b>" . $password . "</b>";
?>
MySQL is deprecated from new version of PHP use
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
Firstly, you need to select a single row, not all the rows in your table, you'd do that by specifying a WHERE clause, currently, you are trying to compare an array of values to a string which should be throwing an error if error reporting is enabled.
Secondly, you are mixing to different APIs, mysql_* is not mysqli_*.
Thirdly, it doesn't seems as though you are hashing your passwords, please, do so.
Fourthly, make use of prepared statements, it seems as though you are still learning so it would be best to start using them now.
Reading Material
OWASP's Password Storage Cheat Sheet
OWASP's PHP Security Cheat Sheet
Could you use mysqli_* please? You might be having a problem with your html form maybe
Change
$con = mysql_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
With
$con = mysqli_connect("localhost","cnathanielwcol","FKxIHHoWWtd4Q","login");
Your are trying to fetch the data with mysqli and your database connection is established by mysql
your full code:
$username = $_POST["username"];
$password = $_POST["password"];
$con = mysqli_connect("localhost","cnathanielwcol","","login") or die('connection is not establised'.mysqli_error($con));
$result = mysqli_query($con,"SELECT * FROM login WHERE username='$username' AND password='$password'");
$rowCheck=mysqli_num_rows($result);
if ($rowCheck>0) {
// fetch all data
//start session
echo "you are logged in ";
}
else{
echo 'username or password did not match';
}
Use hash password.your code is not safe.

Password_verify not matching database

I have looked at the other questions/answers to do with this and have tried to modify my code multiple ways to suit their answers, but have had no success. I have a register form that works fine and successfully adds the user to the database using the password_hash function. Password field is VARCHAR(255) and displays as hashed when entered.
The issue is with the login form. I have tried various ways all day with no success. Below is my current login.php script.
<?php
session_start(); // Starting Session
$error=''; // Variable To Store Error Message
if (isset($_POST['submit'])) {
//error if both boxes empty
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Please fill in both boxes";
}
else
{
// connecting, selecting database
require_once 'dbstuff.php';
include 'opendb.php';
// To protect MySQL injection for Security purpose and define $email and $password
$email = mysqli_real_escape_string($cxn,$_POST['email']);
$password = mysqli_real_escape_string($cxn,$_POST['password']);
//selects user = to email given
$sel_user = "SELECT * from Customer WHERE email='$email'";
$result = $cxn->query($sel_user);
//if matched email in DB verifies password given with hashed password in DB
if($result->num_rows ===1){
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($password, $row['password'])){
echo "match";
//$_SESSION['login_user']=$email; // Initializing Session
//header("location: index.php"); // Redirecting To Other Page
} else {
$error = "email or Password is invalid";
}
}
mysqli_close($cxn); // Closing Connection
}
}
?>
$error variable works fine but still can't see where I am going wrong with the password_verify, keep getting the 'email or password is invalid' error instead of 'match'.
I really would appreciate some feedback on what I have missed out in the code! Thanks :)

Php script doesn't check the username value in mysql table

I'm just new in PHP, I have the project which I'm still constructing and now Am working on
Administrator area.
For now I'm writing the script which Update the password in the table by looking two criteria
"username and fname" if the same with the entered one the password should change, And It does so successfully, but the problem is once I enter incorrect username it still update the password and doesn't show the message "The username you entered does not exist" as well as when I write wrong fname it doesn't show the message to, It real make me stacking where Am wrong, although I know there some where A'm wrong.
I request for any help to any one I'w be thankfully.
This my script
<?php
session_start();
//include mysqli_connect
$name = $_POST['fname'];
$newp = $_POST['newpword'];
$user=$_POST['username'];
$result = mysql_query("SELECT password FROM admin WHERE fname='$name'
AND username='$user' ");
if(!$result)
{
echo "The username you entered does not exist";
}
elseif(mysql_num_rows($result)>0)
$result=mysql_query("UPDATE admin SET password='$newp' where fname='$name'");
{
echo "Password change successfully";
echo"<br>";
echo"<a href=index.php> Click here to signin </a>";
exit;
}
{
echo "The new password and confirm new password fields must be the same";
}
?>
Your if statement and brackets are very mixed up in the code. I think I understood what you're trying to do, though... but you should really go through your own code and give everything the correct indentation.
I changed your code to use pdo.
I added a POST value for the old user password because you should really verify that, too, when updating a user password even if they are already logged in. You will need to add a field for that in the form this is being sent from. If you don't want to use it, you will just need to take the logic out of the code.
And - I really hope you aren't storing the password in plain text. If you are, please tell me what your exact PHP version is in a comment below this post and I can update my answer to show how you would go about storing and using hashed passwords. It does really depend on the version, though.
<?php
session_start();
$_POST['fname'] = 'fname';
$_POST['newpword'] = 'newpword';
$_POST['username'] = 'username';
$name = (isset($_POST['fname'])) ? $_POST['fname'] : die("\$_POST['fname'] is not set");
$newp = (isset($_POST['newpword'])) ? $_POST['newpword'] : die("\$_POST['newpword'] is not set");
$user = (isset($_POST['username'])) ? $_POST['username'] : die("\$_POST['username'] is not set");
// you should get the old password, too,
// so you can verify that it's the correct user
$_POST['oldpass'] = 'password';
$oldp = (isset($_POST['oldpass'])) ? $_POST['oldpass'] : die("\$_POST['oldpass'] is not set");
$pdo = new PDO("mysql:host=localhost;dbname=test", 'root', 'password');
$stmt = $pdo->prepare("SELECT password FROM admin WHERE fname=:fname AND username=:user");
$stmt->bindParam(':fname', $name);
$stmt->bindParam(':user', $user);
$success = $stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($success===false) {
print "an error occurred in the query <br/>".print_r($stmt->errorInfo(),true);
}
elseif ($success!==false && $result===false)
{
print "that username was not found in the database";
}
else
{
if ($result['password']==$oldp)
{
$stmt2 = $pdo->prepare("UPDATE admin SET password=:newp where fname=:fname");
/* You should really HASH this password before storing it*/
$stmt2->bindParam(':newp', $newp);
$stmt2->bindParam(':fname', $name);
$success2 = $stmt2->execute();
if ($success2!==false)
{
echo "Password change successfully";
echo"<br>";
echo"<a href=index.php> Click here to signin </a>";
}
else
{
print "an error occurred updating the password <br/>";
}
}
else
{
print "old password didn't match";
}
}
?>
I think the problem is with if($result) condition. Instead of checking $result you should check if(mysql_num_rows($result)>0)

PDO validating login data

Okay.. I am completely new to this PDO stuff.. I have tried to recreate my mysql script (working) to a PDO script (not working).. I have tested that my DB login informations is correctly programmed for PDO..
This is my PDO script...
<?
session_start();
//connect to DB
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the email and password
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
$sql -> execute();
$count = $sql->rowCount();
$result = $sql -> fetch();
// Now use $result['rowname'];
$stmt = $conn_business->prepare("SELECT * FROM members WHERE email='".$email."'");
$stmt ->execute();
$act = $stmt -> fetch();
//if email exists
if($count > 0)
{
//compare the password
if(strcmp($result["password"],$pass)==0)
{
// check if activated
if($act["activated"] == "0")
{
echo "act"; //account is not activated yet
}
else
{
echo "yes"; //Logging in
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no"; //Passwords don't match
}
else
echo "no"; //Invalid Login
?>
And this is my old mysql script...
session_start();
require_once("connect.php");
//get the posted values
$email=htmlspecialchars($_POST['email'],ENT_QUOTES);
$pass=md5($_POST['psw']);
//now validating the username and password
$sql="SELECT email, password members WHERE email='".$email."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$sql2="SELECT * FROM members WHERE email='".$email."'";
$result2=mysql_query($sql2);
$row2=mysql_fetch_array($result2);
$act = $row2['activated'];
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// check if activated
if($act == "0")
{
echo "act";
}
else
{
echo "yes";
//now set the session from here if needed
$_SESSION['email'] = $email;
}
}
else
echo "no";
}
else
echo "no"; //Invalid Login
Does anybody know, what I have done wrong? It is an automatically script.. It is called through AJAX and return data based on 'no', 'yes' and 'act' that tells the AJAX/jQuery script what to do.. As I said - the mysql script is working, so please if anyone could tell me what I have done wrong with the PDO script..
EDIT:
when it returns the data to the jQuery script, this should happen:
if yes: start session, redirect to page2.php with session started.
else if act: write in a field that the account is not activated.
else: write that email and password didn't match.
The thing is, that when I try to write the correct e-mail and password - it continues to write : "email and password didn't match" instead of redirecting.. When I say that it is not working it is because the mysql script does as described but the PDO script doesn't..
And I have tried to change the 'echo "no";' to 'echo "yes";' to see if the login would start anyway, but somehow it continues to write that the email and password didn't match..
SOLUTION:
I ahven't told this because I thought it was unnecessary, but the reason for it not to work was because of that i have had my old mysql code in comment marks on top of the page, so that the session_start command didn't work.. After deleting the old code it worked, but then I found something else to change, and that is in the PDO script when it is validating it says:
$sql - $conn_business->prepare( "SELECT email, password FROM members WHERE email='".$email."'");
and then I just changed the '-' after $sql to '=' and now, everything works perfectly... Anyhow thank you everybody.. hope this code can help others..
Did you even read the manual before you "started using" PDO?
That is not how prepared statements are supposed to be used! Your code is filled with SQL injections.
Why are you selecting same row twice ?
The strcmp() is not for checing if one string is identical to another.
And hashing passwords as simple MD5 is just a sick joke.
session_start();
//very stupid way to acquire connection
require_once("connect.php");
//get the posted values
$email = htmlspecialchars($_POST['email'],ENT_QUOTES);
if (filter_var( $email, FILTER_VALIDATE_EMAIL))
{
// posted value is not an email
}
// MD5 is not even remotely secure
$pass = md5($_POST['psw']);
$sql = 'SELECT email, password, activated FROM members WHERE email = :email';
$statement = $conn_business->prepare($sql);
$statement->bindParam(':email', $email, PDO::PARAM_STR);
$output = 'login error';
if ($statement->execute() && $row = $statement->fetch())
{
if ( $row['password'] === $pass )
{
// use account confirmed
if ( $row['activated'] !== 0 ) {
$output = 'not activated';
$_SESSION['email'] = $email;
}
$output = 'logged in';
}
}
echo $output;
i believe the second query in your scripts is not necessary you could simple do
SELECT * FROM members WHERE email=:EMAIL AND password=:PWS;
use bindParam method
$qCredentials->bindParam(":EMAIL",$EMAIL);
$qCredentials->bindParam(":PWS",$PWS);
then do more understable outputs rather than yes or no..
try "Unable to login: Invalid credentials supplied" for invalid types of values or "Unable to login: Invalid credentials, couldn't find user" for invalid user credentials.
You could try to start the session after the user has been successfully logged in your IF condition returning yes, and the methods
$PDOstatement->debugDumpParams()
$PDOstatement->errorInfo()
$PDOstatement->errorCode()
will help you understand what went wrong with a query!

Categories