php mysqli non prepared to prepare statement - php

so i have a login page which works very well using php mysqli, but is non prepare so i usually use mysqli_real_escape to secure the data.
But am now migrating to using prepared statement, have manage this with my register page and this as work very well.
here is my non prepared login code:
$loginQuery = "select * from user where user_name = '$user_name' AND password = '$password'";
$result = mysqli_query($con,$loginQuery);
if(mysqli_num_rows($result)){
$row = mysqli_fetch_array($result);
// password verify
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = strtoupper($row['user_name']);
$user_type = strtolower($row['user_type']);
if(strtolower($user_type) == 'member'){
$_SESSION['user_type'] = 'member';
//header('Location: member-dashboard-home.php');
header('Location: profile.php');
}elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
$_SESSION['user_type'] = strtolower($user_type);
//header('Location: admin-dashboard-home.php');
header('Location: profile.php');
}
}else{
$_SESSION['main_notice'] = "Invalid login details!";
header('Location: '.$_SERVER['PHP_SELF']);exit();
}
And below is my effort in using prepared statement.
$stmt = $mysqli->prepare("SELECT user_name FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$stmt->bind_result($user_name);
if($res = $stmt->num_rows()){
$row = $stmt->fetch_array($res);
// password verify
if (password_verify($password, $row['password'])) {
$_SESSION['user_id'] = $row['id'];
$_SESSION['user_name'] = strtoupper($row['user_name']);
$user_type = strtolower($row['user_type']);
if(strtolower($user_type) == 'member'){
$_SESSION['user_type'] = 'member';
//header('Location: member-dashboard-home.php');
header('Location: profile.php');
// exit;
}elseif(strtolower($user_type) == 'admin' || strtolower($user_type) == 'leader'){
$_SESSION['user_type'] = strtolower($user_type);
//header('Location: admin-dashboard-home.php');
header('Location: profile.php');
//exit;
}
}else{
$_SESSION['main_notice'] = "Invalid username OR password details, please try again!";
header('Location: '.$_SERVER['PHP_SELF']);exit();
}
}
I didn't get any error code when i tried to login, but the form just return blank and didn't redirect to user profile.
I don't think this is redirection issue tho or is it?
i don't i arrange the $stmt properly, hopefully you guy see what i can't.
thanks in advance

From your comment,
i did include at the top and i receive this error Notice: Undefined variable: mysqli in /home/connection.php... ...
Look at your code here,
$con = new mysqli("localhost", "***", "***", "***");
if ($mysqli->connect_errno) {
^^^^^^^^^^^^^^^^^^^^^^
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^
}
Your connection handler is $con, not $mysqli, it should be like this:
$con = new mysqli("localhost", "***", "***", "***");
if ($con->connect_errno) {
echo "Failed to connect to MySQL: (" . $con->connect_errno . ") " . $con->connect_error;
}
Update(1): Change your code in the following way,
$stmt = $con->prepare("SELECT * FROM user WHERE user_name = ? ");
$stmt->bind_param('s', $user_name);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
// username exists
$row = $result->fetch_array();
// your code
}else{
// username doesn't exist
// your code
}

Related

How can i redirect to a new page after login is successful with php

thank you for your consideration.
I'll be short and concise, because it seems i get banned no matter what i post.
I found similar questions on here but none of the suggestions were working with my code.
i just need help after login is successful redirecting to a new page my code is.
$username = $_POST["username"];
$conn = mysqli_connect($host, $user, $pass, $db);
$query = "SELECT * FROM user WHERE username = '" .$username. "'";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)){
echo "Password Entered: " . $_POST["password"];
echo "Correct Pasword: " . $row['password'];
// See if the password is correct
if ($_POST["password"] === $row['password'])
echo "Logon Successful!";
else {
echo "Logon Failed!";
}
}
if (!mysqli_fetch_assoc($result))
echo "Invalid Username";
?>
Maybe have a bit of changes like the following:
login.php
$username = $_POST["username"];
$password = $_POST["password"];
$conn = mysqli_connect($host, $user, $pass, $db);
$query = "SELECT * FROM user WHERE username = '" . $username . "'";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)){
// See if the password is correct
if ($password === $row['password']){
header('location: login_successful.php');
}else {
// you can hide the message at QueryString via SESSION or COOKIE
header('location: login_form.php?message=FAIL_MESSAGE'); //you can detect and show login status message.
}
}
i just forgot a semicolon after the header..
$query = "SELECT * FROM user WHERE username = '" .$username. "'";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)){
// See if the password is correct
if ($_POST["password"] === $row['password']){
echo "Logon Successful!";
header("Location: index.php");
exit();
}

How to modify a Login System in msqli query to PDO? [duplicate]

This question already has an answer here:
How to convert MySQL code into PDO statement?
(1 answer)
Closed 8 months ago.
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");
if( $result->num_rows == 0 ){
// User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
} else{ // User exists
$user = $result->fetch_assoc();
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
}
}
I need to modify this code above to PDO. I tried to make some changes:
define('DB_HOSTNAME', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', null);
define('DB_CHARSET', 'utf8');
define('DB_DATABASE', 'publicacoes');
$conn = new PDO('mysql:host=' . DB_HOSTNAME . ';dbname=' . DB_DATABASE . ';charset=' . DB_CHARSET . ';', DB_USERNAME, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = $conn->prepare("SELECT * FROM users WHERE email = :email"); ###
$result->execute([':email' => $_POST['email']]); ###
if( $result->num_rows == 0 ){
// User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
} else{ // User exists
$user = $result->fetch_assoc();
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
}
}
But it's not working, I got the errors:
1 - Undefined variable: result.
2 - Fatal error: Uncaught Error: Call to a member function execute() on null.
It gets the same error if i change &result to $email.
What's wrong with the code? I'm not familiar with MYSQLi. I'm thinking that maybe i need to change all the code on this login system. I need to modify it to PDO.
Firstly, you don need to escape_string with pdo prepared statement.
Secondly, you should change your database connection compatible with pdo along with the pdo attributes PDO::ATTR_ERRMODE & PDO::ERRMODE_EXCEPTION so that you can at least catch pdo errors and exceptions. You can add other error handling attributes too in your connection statement. See http://php.net/manual/en/pdo.error-handling.php for more details.
$DATABASESERVER = "YOUR_DATABASE_SERVER_NAME";
$DATABASENAME = "YOUR_DATABASE_NAME";
$DATABASEUSERNAMNE = "YOUR_DATABASE_USERNAME";
$DATABASEPASSWORD = "YOUR_DATABASE_PASSWORD";
try {
$DatabaseCon = new PDO("mysql:host=$DATABASESERVER; dbname=$DATABASENAME", $DATABASEUSERNAMNE, $DATABASEPASSWORD);
$DatabaseCon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "$DatabaseCon-> failed: " . $e->getMessage();
}
and finally you can replace your code with:
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = trim($_POST['email']);
try{
$Query = "SELECT * FROM users WHERE email=:email";
$statement = $DatabaseCon->prepare($Query);
$statement->bindValue(':email', $email);
$statement->execute();
$user = $statement->fetch(PDO::FETCH_ASSOC);
$RowCount = $statement->rowCount();
}
catch (PDOerrorInfo $e){
die('QuerySCD Error '.$e->getMessage());
}
if( $RowCount == 0 ){
// User doesn't exist
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
} else{ // User exists
if( password_verify($_POST['password'], $user['password'])){
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
}
}
//close database connection
$DatabaseCon-> = NULL;
However, you can also use positional place holder & bindParam method in your pdo syntax. See manual for more details.
All the best.
You're code can be written like this using my PDO wrapper class called GrumpyPDO.
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//select row of results where email is posted email
//$db must be set prior to this
$user = $db->row("SELECT * FROM users WHERE email=?", [$_POST['email']]);
if(!empty($user)) { //user exists if $result is not empty
//everything from here on is the same
if(password_verify($_POST['password'], $user['password'])) {
$_SESSION['email'] = $user['email'];
$_SESSION['first_name'] = $user['first_name'];
$_SESSION['last_name'] = $user['last_name'];
$_SESSION['active'] = $user['active'];
// This is how we'll know the user is logged in
$_SESSION['logged_in'] = true;
header("location: riscar.php");
} else {
$_SESSION['message'] = "You have entered wrong password, try again!";
header("location: error-login.php");
}
} else {
$_SESSION['message'] = "User with that email doesn't exist!";
header("location: error-login.php");
}
}

How can I bypass my login script?

I've created a below script, which is intentionally not secure, in order to learn a bit more about cyber security.
session_start();
if($_SESSION['userSession']) {
header("location: home.php");
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
$con = mysqli_connect("localhost", "myUsername", "myPassword", "myDatabase");
if(!$con) {
die("Error: " . mysqli_connect_error());
}
$query = "SELECT * FROM users WHERE username = '$username' && password='$password'";
$result = mysqli_query($con, $query);
$numResults = mysqli_num_rows($result);
if($numResults == 1) {
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['userSession'] = $row['id'];
header("location: home.php");
} else {
echo "Error Logging In";
}
mysqli_close($con);
}
As you can see, I have not escaped the user input and the password has not been hashed.
Therefore, I am presuming that this should be an easily hackable login. However, I have attempted to use the below input in both of the username and password fields, but always get the output "Error Logging In".
password' OR '1' = '1'";
How can I try to bypass/hack my login script?
If we use sql statement directly to fetch username and password field then it can be bypass with ' OR '1' = '1 pattern, because when you put ' OR '1' = '1 in username and password field that values carry forward to sql statement and in that statement ' or '1' = '1 is true for all the cases and that's a reason login can bypass.

sql injection login form error

I am working on tutorial about how to make an sql injection with old php code. I have this code that I am testing on it, but I have an error that said:
Fatal error: Call to a member function fetch_assoc() on a non-object
This is the old code:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="graphic_db"; // Database name
$tbl_name="login"; // Table name
//if(!session_is_registered(myusername)){
//header("location:index.html");
$con=mysqli_connect($host,$username,$password,$db_name);
if(isset($_POST['login_submit'])){
if($_POST['username'] != '' && $_POST['password']!=''){
if(!isset($_SESSION))
{
session_start();
//session_register('username');
}
$result = mysqli_query($con, "SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
while($row = $result->fetch_assoc($result) ){
if(is_array($row)) {
$_SESSION["username"] = $row[$_POST["username"]];
$_SESSION['username'] = $_POST["username"];
header("Location:home.php");
}
else {
$message = "Invalid Username or Password!";
}
}
}
}
?>
You have mixing Object oriented style and Procedural style in your code .Use only one style as
In Object oriented style
$result = $mysqli->query( "SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
while($row = $result->fetch_assoc() ){
In Procedural style
$result = mysqli_query($con, "SELECT * FROM login WHERE username='" . $_POST["username"] . "' and password = '". $_POST["password"]."'");
while($row = mysqli_fetch_assoc($result) ){
Read http://php.net/manual/en/mysqli-result.fetch-assoc.php
try this code
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="graphic_db"; // Database name
$tbl_name="login"; // Table name
session_start();
$mysqli = new mysqli($host, $username, $password, $db_name);
if(isset($_POST['login_submit'])){
$stmt = $mysqli->prepare("SELECT * FROM login WHERE email=? AND password=? ");
$email = $_POST['username'];
$password = md5($_POST['password']);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($email, $password);
$stmt->store_result();
if($stmt->num_rows == 1) //To check if the row exists
{
while($stmt->fetch()) //fetching the contents of the row
{
$_SESSION['Logged'] = 1;
$_SESSION['Email'] = $email;
header('Location: home.php');
exit();
}
}
else
{
echo "Wrong Username or Password!";
}
$stmt->close();
$stmt->free_result();
}
Use prepared query for your sql injection code. it is best practice for it.
Prepared statements are very useful against SQL injections, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.

PHP MYSQLI login Allow capital letter

This script does work, but if I use a capital letter for the user it does not work,
In the database is the user name Tom.
And I can login if i use Tom,
But tom does not work.
How can I fix it?
<?php
$username=$_POST['username'];
$password=md5($_POST['password']);
$login=$_POST['login'];
if(isset($login)){
$mysqli = new mysqli("localhost", "root", "Tech112!", "ripper");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT * FROM login where username='$username' and password='$password'");
$row = $res->fetch_assoc();
$name = $row['name_login'];
$user = $row['username'];
$pass = $row['password'];
$rank = $row['type_login'];
if($user==$username && $pass=$password){
session_start();
if($rank=="2"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
} else if($rank=="1"){
$_SESSION['mysesi']=$user;
$_SESSION['rank']=$rank;
echo "<script>window.location.assign('index.php')</script>";
}
}
}
?>
Tom Lammers
Convert both database and $_POST username to lowercase and compare those. This will make username case insensitive.
$res = $mysqli->query("SELECT * FROM login where LOWER(`username`)='".strtolower($username)."' and password='$password'");
And edit your if to also compare with lowercase username.
if(strtolower($user) == strtolower($username) && $pass=$password){
NB! Your query is open for SQL injection, read this to fix it.
To avoid SQL injection, use bind_param.
/* Code until query */
$stmt = $mysqli->prepare("SELECT * FROM login where LOWER(`username`) = ? and password = ?");
// Add variables safely
$stmt->bind_param('ss', strtolower($username), $password);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
/* Rest of your code */

Categories