As stated in the question before this, I have a registration system on my website and I am updating my mysql statements to PDO statements. I have updated all the statements and now the script runs through but it doesn't execute any of the script and doesn't give me any errors. It redirects me back to the registration.php page.
reg.php
<?php
include("sql.php");
require("includes/password.php");
session_start(); //Start session for writing
$errmsg = array(); //Array to store errors
$noterr = array();
$errflag = false; //Error flag
function UniqueID() {
include("sql.php");
$UID = rand(); //Create unique ID
$check = $db->prepare('SELECT * FROM `users` WHERE `UID` = :UID');
$UIDarray = array(
UID => $UID
);
$check->execute($UIDarray);
if($check->fetchColumn() > 0) { //Check if it exists
UniqueID(); //Redo the function
} else {
return $UID; //return the uniqueid
}
}
$UID = UniqueID(); //Unique ID
$username = ($_POST['username']); //Username
$email = $_POST['email']; //Email
password_hash($_POST['password'], PASSWORD_BCRYPT, array("cost" => 10)); //Password
password_hash($_POST['rpassword'], PASSWORD_BCRYPT, array("cost" => 10)); //Repeated Password
//Check Username
if($username == '') {
$errmsg[] = '<span style="color: red;">Where is your username?</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Password
if($password == '') {
$errmsg[] = '<span style="color: red;">Oops! No password!</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Check Repeated Password
if($rpassword == '') {
$errmsg[] = '<span style="color: red;">Your repeated password is missing!</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure passwords match
if(strcmp($password, $rpassword) != 0 ) {
$errmsg[] = '<span style="color: red;">Passwords do not match</span>'; //Error
$errflag = true; //Set flag so it says theres an error
}
//Make sure username is availible
if($username != '') {
$qry = $db->prepare("SELECT * FROM `users` WHERE `Username` = :username"); //MySQL query
$params = array(
username => $username
);
$qry->execute($params);
if($qry->execute($params)) {
if($qry->fetchColumn() > 0) { //If username is in use
$errmsg[] = '<span style="color: red;">Sorry, that username is already in use</span>'; //Create error
$errflag = true; //Set flag so it says theres an error
}
$qry->closeCursor();
}
}
if(isset($_POST["captcha"])&&$_POST["captcha"]!=""&&$_SESSION["code"]==$_POST["captcha"])
{
}
else
{
$errmsg[] = '<span style="color: red;">That is not what the picture displayed!</span>'; // Create error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
//Create INSERT query
$query = $db->prepare("INSERT INTO `userauthenticate`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES(:UID,:username,:email,:password)");
$params2 = array(
UID => $UID,
username => $username,
email => $email,
password => $password
);
$query->execute($params2);
//Check whether the query was successful or not
if($query->execute($params2)) {
header("Location: login.php");
exit();
} else {
die("There was an error, try again later");
}
?>
sql.php
<?php
ob_start();
session_start();
//database credentials
$dbhost = 'dbhost';
$dbuser = 'dbuser';
$dbpass = 'dbpass';
$dbname = 'dbname';
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>
It might be worth adding some try/catch blocks to catch any errors if there are any
//Make sure username is availible
if($username != '') {
try {
$qry = $db->prepare("SELECT * FROM `users` WHERE `Username` = :username"); //MySQL query
$params = array(
username => $username
);
$result = $qry->execute($params);
if($result) {
if($qry->fetchColumn() > 0) { //If username is in use
$errmsg[] = '<span style="color: red;">Sorry, that username is already in use</span>'; //Create error
$errflag = true; //Set flag so it says theres an error
}
$qry->closeCursor();
}
}
catch(PDOException e) {
// write the error to the log
$errmsg = $e->getMessage();
error_log('$errmsg-> '.$errmsg);
echo $errmsg;
}
}
if(isset($_POST["captcha"]) && $_POST["captcha"] !="" && $_SESSION["code"] == $_POST["captcha"])
{
}
else
{
$errmsg[] = '<span style="color: red;">That is not what the picture displayed!</span>'; // Create error
$errflag = true; //Set flag so it says theres an error
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG'] = $errmsg; //Write errors
session_write_close(); //Close session
header("location: register.php"); //Rediect
exit(); //Block scripts
}
try {
//Create INSERT query
$query = $db->prepare("INSERT INTO `userauthenticate`.`users`(`UID`, `Username`, `Email`, `Password`) VALUES (:UID,:username,:email,:password)");
$params2 = array(
UID => $UID,
username => $username,
email => $email,
password => $password
);
$result $query->execute($params2);
}
catch(PDOException e) {
// write the error to the log
$errmsg = $e->getMessage();
error_log('$errmsg-> '.$errmsg);
echo $errmsg;
}
//Check whether the query was successful or not
if($result) {
header("Location: login.php");
exit();
} else {
die("There was an error, try again later");
}
?>
Related
Please, help me look at this code for login, I want to verify if input password matches stored harsh password. This does not work. If i comment out If (password_verify..., i will be able to login otherwise, it wont login. i dont know where i got the code wrong and it doesnt want to verify password before login
if (isset($_POST['agentlogin-btn'])) {
$username= $_POST['username'];
$password = $_POST['password'];
function Is_email($user)
{
//If the username input string is an e-mail, return true
if (filter_var($user, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
//validation
if (strlen($_POST['username']) < 1) {
$_SESSION['error'] = 'email or phone number required';
header("Location:register.php");
return;
}
if (strlen($_POST['password']) < 1) {
$_SESSION['error'] = 'password required';
header("Location:register.php");
return;
}
if (!isset($_SESSION['error'])) {
$check_email = Is_email($username);
if ($check_email) {
$sql = "SELECT * FROM agent WHERE Email= :email LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':email' => $_POST['username'],
));
} else {
$sql = "SELECT * FROM agent WHERE Phone_number= :phonenumber LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':phonenumber' => $_POST['username'],
));
}
if ($stmt->execute()) {
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$user = $result;
if (password_verify($password], $user['Password'])) {
//login success
$stmt->close();
$_SESSION['id'] = $user['User_id'];
$_SESSION['agentid'] = $user['agent_id'];
$_SESSION['firstname'] = $user['First_name'];
$_SESSION['Surname'] = $user['Surname'];
$_SESSION['phonenumber'] = $user['Phone_number'];
$_SESSION['email'] = $user['Email'];
$_SESSION['verified'] = $user['verified'];
// set flash message
$_SESSION['success'] = "You are now logged in! Continue with your upload";
header('location: profilepage.php');
return;
} else {
$_SESSION['errors'] = "Wrong username/password";
header('Location: register.php');
return;
}
}
}
}
instead of writing $stmt->execute() two times, store the result in a variable, and at second place use that variable.
I currently have a login system, which I would like to convert to PDO from Mysqli.
I currently have a website with a database attached with phpMyAdmin/MySQL.
I tried to convert everything and I will now show you the LOGIN.php part of the system since I haven't touched the signup part yet.
This is what I have.
LOGIN.INC.PHP
<?php
require_once 'dbh.inc.php';
try {
$handler = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch(PDOException $e){
echo $e->getName();
die();
}
//first we start a session
session_start();
//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {
//Then we require the database connection
//require_once 'dbh.inc.php';
//And we get the data from the login form
$name = $_POST['name'];
$password = $_POST['password'];
//Error handlers
//Error handlers are important to avoid any mistakes the user might have made when filling out the form!
//Check if inputs are empty
if (empty($name) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
}
} else {
$stmt = $db->prepare("SELECT * FROM users WHERE user_name=:name");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if ($stmt->execute()) {
header("location: ../index.php?login=error");
exit();
} else {
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//de-hashing the password
$hashedpasswordCheck = password_verify($password, $row['user_password']);
if ($hashedpasswordCheck == false) {
header("location: ../index.php?login=error");
exit();
} elseif ($hashedpasswordCheck == true) {
//Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
} else {
header("location: ../index.php?login=error");
exit();
}
}
}
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loginsystem";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$stmt = $conn->prepare("SHOW DATABASES;");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
print_r($result);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$conn = null;
When I try to login I get redirected to this url:
http://localhost/php44/includes/login.inc.php
and receive this printed message/error.
Array ( [0] => Array ( [Database] => imgupload ) [1] => Array ( [Database] => information_schema ) [2] => Array ( [Database] => loginsystem ) [3] => Array ( [Database] => mysql ) [4] => Array ( [Database] => performance_schema ) [5] => Array ( [Database] => phpmyadmin ) [6] => Array ( [Database] => test ) )
What should I do to fix this, so that my login works?
Your code is vulnerable to Html Elements Injection and session fixation attack. I have implemented strip_tags() to prevents html element injection attack and have also implemented session_regenerate_id(); to prevent session fixation attack.
Again since you are login, you only need to initialize session as soon as username and password is verified.
As for me, I prefer using PDO array method. Anyway I have provided two solution. I first work on your code and then modify it were appropriate. Ensure that database credentials is okay
Your code
<?php
//db connect starts
$db = new PDO (
'mysql:host=localhost;dbname=loginsystem;charset=utf8',
'root', // username
'' // password
);
//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$password = $_POST['password'];
if ($name =='' && $password =='') {
header("Location: ../index.php?login=empty");
exit();
}
$stmt = $db->prepare("SELECT * FROM users WHERE user_name=:name");
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if( $count == 1 ) {
$row = $stmt->fetch();
if(password_verify($password,$row['password'])){
echo "Password verified and ok";
// initialize session if things where ok.
session_start();
//Prevent session fixation attack
session_regenerate_id();
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
else{
echo "Wrong Password details";
}
}
else {
echo "User does not exist";
}
}
?>
my code
<?php
//if (isset($_POST['submit'])) {
if ($_POST['name'] !='' && $_POST['password']) {
//connect
$db = new PDO (
'mysql:host=localhost;dbname=loginsystem;charset=utf8',
'root', // username
'' // password
);
$name = strip_tags($_POST['name']);
$password = strip_tags($_POST['password']);
if ($name == ''){
echo "Username is empty";
exit();
}
if ($password == ''){
echo "password is empty";
exit();
}
$result = $db->prepare('SELECT * FROM users where user_name = :name');
$result->execute(array(
':user_name' => $name));
$count = $result->rowCount();
if( $count == 1 ) {
$row = $result->fetch();
if(password_verify($password,$row['password'])){
echo "Password verified and ok";
// initialize session if things where ok.
session_start();
//Prevent session fixation attack
session_regenerate_id();
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
else{
echo "Wrong Password details";
}
}
else {
echo "User does not exist";
}
}
?>
I've made some fixes and added comments in to explain what changed:
LOGIN.INC.PHP
<?php
//First we start a session
session_start();
//Then we require the database connection
require_once 'dbh.inc.php';
// Removed the extra database connection here.
//We then check if the user has clicked the login button
if (isset($_POST['submit'])) {
//And we get the data from the login form
$name = $_POST['name'];
$password = $_POST['password'];
//Error handlers
//Error handlers are important to avoid any mistakes the user might have made when filling out the form!
//Check if inputs are empty
if (empty($name) || empty($password)) {
header("Location: ../index.php?login=empty");
exit();
}
//Removed extra 'else' here.
$stmt = $conn->prepare("SELECT * FROM users WHERE user_name=:name"); // Changed $db to $conn to use the connection from DBH.INC.PHP
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
if (!$stmt->execute()) { // Added the ! to say "if this doesn't work, redirect to error"
header("location: ../index.php?login=error");
exit();
} else {
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//de-hashing the password
$hashedpasswordCheck = password_verify($password, $row['user_password']);
if ($hashedpasswordCheck == false) {
header("location: ../index.php?login=error");
exit();
} else if ($hashedpasswordCheck == true) {
//Log in the user here
$_SESSION['u_id'] = $row['user_id'];
$_SESSION['u_name'] = $row['user_name'];
header("location: ../index.php?login=success");
exit();
}
} else {
header("location: ../index.php?login=error");
exit();
}
}
}
DB.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "loginsystem";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
// Removed the query and print of the databases
}
catch(PDOException $e) {
echo $e->getMessage();
}
// Removed the $conn=null to keep the connection we just set up.
sorry for my bad english, im new in php.
so I have a game server, I want to make players register through the website and save the data via the Accounts.db file
my database configuration
try {
# SQLite Database
$dbh = new PDO("sqlite:/home/samp/scriptfiles/Accounts.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
my php file
$error = '';
$success = '';
if (isset($_POST['submit'])){
global $dbh;
$username = $_POST['username'];
$password = $_POST['password'];
$cpassword = $_POST['cpassword'];
$hashed = num_hash($password);
$checkusername = strpos($username, "_");
$sql = "SELECT COUNT(*) FROM `Accounts` WHERE `Username` = '$username'";
$checkexist = $dbh->query($sql);
if (!empty(trim($username)) && (!empty(trim($password)))){
//$recaptcha_secret = "6LcM1EYUAAAAAF1cINK71jkpRfoqlGec58r8bIkf";
//$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$recaptcha_secret."&response=".$_POST['g-recaptcha-response']);
//$response = json_decode($response, true);
//if($response["success"] === true) {
if ($checkusername) {
if ($password == $cpassword){
if ($checkexist->fetchColumn() == 0) {
$sql = "INSERT INTO `Accounts` (`Username`, `Password`) VALUES(?, ?)";
$insert->execute(array($username, $hashed));
if ($insert) {
$success = 'Berhasil melakukan registrasi.';
} else {
$error = 'Database error.';
}
} else {
$error = 'Username sudah digunakan.';
}
} else {
$error = 'Password yang anda masukan tidak sama.';
}
} else {
$error = 'Username akan digunakan sebagai Nama Karakter, gunakan format NamaDepan_NamaBelakang. Contoh: John_Smith';
}
//} else {
// $error= 'Apakah anda robot? Silahkan selesaikan captcha sebelum login';
//}
} else {
$error = 'You should input Username & Password!';
}
}
when I try to register on the website, it gives a successful notification but the data is not entered into the Accounts.db file. you can try it on my website
Thanks for your help
So I'm trying to make a fairly simple login system, but for some reason the hashed password that is being sent to my database is not hashing correctly. I checked my database and the stored password is not what the sha256 hashed with the generated salt appended is not what it's supposed to be. Here's my code for generating the hash that's being uploaded to the database:
<?php
include "connection.php";
//Check Connection
if ($connect->connect_error) {
echo "Failed to connect to server: " . mysqli_connect_error();
}
//Reset all Checks
$username_exists = NULL;
$email_valid = NULL;
$passwords_match = NULL;
$password_acceptable = NULL;
$password_long_enough = NULL;
$password = NULL;
//Prepare Statements
//Check for Username Existing Statement
$check_username_match = $connect->stmt_init();
$sql_check_username = "SELECT id FROM $tablename WHERE username=?";
$check_username_match->prepare($sql_check_username);
$check_username_match->bind_param("s", $username);
//Insert Into Table Statement
$register_query = $connect->stmt_init();
$sql_register = "INSERT INTO $tablename (username, email, password, token, active, level) VALUES (?, ?, ?, ?, ?, ?)";
$register_query->prepare($sql_register);
$register_query->bind_param("sssssi", $username, $email, $hashedpassword, $token, $activated, $level);
//Execute When Form Submitted
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$email = mysqli_escape_string($connect, $_POST['email']);
$password = $_POST['password'];
$confirm_password = $_POST['confirm_password'];
//Check if Username Exists
$check_username_match->execute();
$check_username_match->store_result();
$numrows = $check_username_match->num_rows;
if ($numrows==0){
$username_exists = false;
} else {
$username_exists=true;
}
//Check if Passwords Match
if ($password==$confirm_password){
$passwords_match = true;
} else {
$passwords_match = false;
}
//Check if Email Address is Valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_valid = true;
} else {
$email_valid = false;
}
//Check if Passwords Contains Special Characters
$uppercase = preg_match('#[A-Z]#', $password);
$lowercase = preg_match('#[a-z]#', $password);
$number = preg_match('#[0-9]#', $password);
//Check if Password is Long Enough
$password_length = strlen($password);
if ($password_length>8){
$password_long_enough = true;
} else {
$password_long_enough = false;
}
//Validate Password
if(!$uppercase || !$lowercase || !$number || !$password_long_enough || $password = '') {
$password_acceptable = false;
} else {
$password_acceptable = true;
}
//Register if all Validations Met
if(!$username_exists && $email_valid && $passwords_match && $password_acceptable){
//$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$token = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$activated="No";
$level = 0;
$hashedpassword = password_hash($password, PASSWORD_DEFAULT);
$register_query->execute();
$message = "Hello, welcome to the site.\r\n\r\nPlease click on the following link to activate your account:\r\nlocalhost/login_system/activate.php?token=".$token;
mail($email, 'Please Activate Your Account', $message);
header("Location: login.php");
}
}
?>
UPDATE: I changed my above code to reflect the changes I made with password_hash. However, the problem still persists.
This is my login php:
<?php
include("connection.php");
session_start();
//Reset Variables
$message = '';
$location = "/login_system/index.php"; //default location to redirect after logging in
$username = '';
$password = '';
//Check to see if user is newly activated; if he is display a welcome message.
if(isset($_GET['activated'])){
if($_GET['activated'] == "true"){
$message = "Thank you for verifying your account. Please login to continue.";
}
}
//Check to see if user is coming from another page; if he is then store that page location to redirect to after logging in.
if(isset($_GET['location'])) {
$location = htmlspecialchars($_GET['location']);
}
echo $location;
//Prepare login check statement
$check_login = $connect->stmt_init();
$sql = "SELECT id, password FROM $tablename WHERE username=?";
$check_login->prepare($sql);
$check_login->bind_param("s", $username);
//Execute Login Check
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = mysqli_escape_string($connect, $_POST['username']);
$password = $_POST['password'];
$check_login->execute();
$check_login->store_result();
$numrows = $check_login->num_rows;
$check_login->bind_result($id, $match);
$check_login->fetch();
if ($numrows==1 && password_verify($password, $match)) {
$_SESSION['login_user'] = $id;
$goto = "localhost".$location;
header("location: $goto");
$message = "Success!";
} else {
$message="Username or password is not valid."."<br>".$match."<br>";
}
}
$connect->close();
?>
You should just feed the password you want to hash into PHP's password_hash();function. Like so...
$password = $_POST['password'];
$options = [
'cost' => 12,
];
echo password_hash($password, PASSWORD_BCRYPT, $options);
Then when you want to check if the password exists in the database use password_verify(); Like so...
$password = PASSWORD_HERE;
$stored_hash = HASH_HERE;
if (password_verify($password, $stored_hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
I'm hashing a password using sha1 and it is successfully storing it in the database, however i cannot seem to properly check to see if the sha1 matches one that is in the database. I've tried numerous different iterations of the below code, but nothing seems to work - what am i missing?
Registration
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("INSERT INTO
user_info
SET
username = :user,
pass = :pass
");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
}
catch (Exception $e) {
echo "Could not create username";
}
if (isset($_POST['submit'])) {
foreach ($_POST as $field) {
if (empty($field)) {
$fail = true;
}
else {
$continue = false;
}
}
if ($field == $fail) {
echo "You must enter a username and/or password";
}
else {
echo "Your account has been successfully created.";
}
}
?>
Logging in
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$encryptedPassword = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
if ($rows) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
?>
You need to hash the password before querying the table, not afterwards:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
if ($result->fetch(PDO::FETCH_NUM)) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
?>