I have a login, where i need to pull data given the email, i do this with a select and pdo. But it isn't working.
I get the password and email given from a form. Then i check if there not empty, then i want to get the password from the database to check it with the given password. If this is good, then i give the account id and username in a session.
If it was not good, i set the header and give a error message
try {
$connect = new PDO("mysql:host=$hostnaam; dbname=$databasenaam", $gebruikersnaam, $wachtwoord);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connectie mislukt: " . $e->getMessage();
}
<?php
ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ob_start();
if(isset($_REQUEST['password']))
{
require 'connect.php';
$password = $_REQUEST['password'];
$mail = $_REQUEST['email'];
if(empty($mail) || empty($password)){
header('location: ../login.php?error=empty');
exit();
}
else{
$sql = "SELECT * FROM account WHERE email = $mail";
$result = $connect->prepare($sql);
$result->execute();
$row = $result->fetchAll(PDO::FETCH_ASSOC);
$passwordCheck = password_verify($password_hashed, $pdo['wachtwoord']);
if($passwordCheck == false ){
header("Location: ../login.php?error=passwordWrong");
exit();
}
else if($passwordCheck == true){
session_start();
$_SESSION['userId'] = $row['account_id'];
$_SESSION['username'] = $row['gebruikersnaam'];
header("Location: ../index.php?login=succes");
exit();
}
else{
header("Location: login.php?error=noUser");
exit();
}
}
}
else{
header("Location: ../login.php?error=fail");
exit();
}
Related
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.
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");
}
}
Recently i developed a small school management software everything is fine in localhost but when i move the file to online server and try to login my (role) than it shows me a message and change the url mydomain/authenticate.php
The bizedu.co.in page isn’t working
bizedu.co.in is currently unable to handle this request.
500
Authenticate.php code here-
<?php
require 'connection.php';
ob_start();
session_start();
$id = "";
$password = "";
if (isset($_POST['id'])) {
$id = $_POST['id'];
}
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
echo $id . " : " . $password;
$q = 'SELECT * FROM account WHERE id=:id AND password=:password';
$query = $conn->prepare($q);
$query->execute(array(':id' => $id, ':password' => $password));
if ($query->rowCount() == 0) {
header('Location: index.php?err=1');
} else {
$row = $query->fetch(PDO::FETCH_ASSOC);
session_regenerate_id();
$_SESSION['sess_user_id'] = $row['id'];
$_SESSION['sess_username'] = $row['username'];
$_SESSION['sess_userrole'] = $row['role'];
echo $_SESSION['sess_userrole'];
session_write_close();
if ($_SESSION['sess_userrole'] == "admin") {
header('Location: school_admin_home1.php');
} elseif ($_SESSION['sess_userrole'] == "employee") {
header('Location: school_employee_home.php');
} elseif ($_SESSION['sess_userrole'] == "parent") {
header('Location: parent_home.php');
} else {
}
}
?>
Connection.php code here-
<?php
//database credentials
define('DBHOST','localhost');
define('DBUSER','bizeduco_portal ');
define('DBPASS','password123');
define('DBNAME','bizeduco_school');
try {
//create PDO connection
$conn = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//show error
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
?>
Please give me a solution.
this is the login form....it says that it cannot modify header information and I tried everything to fix but I cant...can someone help me with my codes..thanks in advance
<?php
$loginpopup = 'Login Success';
$failpopup = 'Wrong Username or Password';
if(!$con)
{
die("Error connection" . mysqli_connect_error());
}
if (isset($_POST['submitlogin']))
{
$login = "SELECT * from admin where username = '$_POST[user]' AND password ='$_POST[pass]'";
$getuser = mysqli_query($con,$login) or die(mysql_error());
while($row = mysqli_fetch_array($getuser))
{
if($row==0)
{
echo "<SCRIPT>alert('$failpopup');</SCRIPT>";
header("location:index.php");
}
else
{
echo "<SCRIPT>alert('$loginpopup');</SCRIPT>";
header("location:home.php");
}
}
}
?>
if the query failed to run your script will Die because of or die(mysql_error);
which won't output anything after $getuser
modify your code to this
include('movieshub/includes/config.php');
if ($getuser = mysqli_query($con,$login)) { // check if the query succeeded running
$count = mysqli_num_rows($getuser);
if ($count == 0 ) {
echo "<SCRIPT>alert('$failpopup');</SCRIPT>";
header("location:index.php");
} else {
while($row = mysqli_fetch_array($getuser))
{ //output data }
echo "<SCRIPT>alert('$loginpopup');</SCRIPT>";
header("location:home.php");
}
}
} else {
echo "query failed to run";
}
Try the code below:
<?php
//if your are using wamp then let $servername,$username and $password be same as below otherwise change them.
$servername = "localhost"; //insert your severname at the place of localhost
$username = "root"; //insert your username at the place of root
$password = ""; //insert your password at the place of ""
// Create connection
$con = mysqli_connect($servername, $username, $password);
//select database
mysqli_select_db($con,"test"); //here enter your database name at the place of test
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$loginpopup = 'Login Success';
$failpopup = 'Wrong Username or Password';
if (isset($_POST['submitlogin']))
{
$user=$_POST["user"];
$pass=$_POST["pass"];
$login = "SELECT * from admin where username=$user AND password=$pass";
$getuser = mysqli_query($con,$login);
$row=mysqli_affected_rows($con);
if($row>1)
{
echo "<SCRIPT>alert('$loginpopup');</SCRIPT>";
header("location:home.php");
}
else
{
echo "<SCRIPT>alert('$failpopup');</SCRIPT>";
header("location:index.php");
}
}
?>
im doing a system for school which by the user will be admin, teacher and parents.
im having problem to differentiate two user right now which is admin and parents.
i cant make sure that admin will directly go to admin.php and parent type will be on parent.php
any helps will be great! thanks in advance.
and the problem now is that the authentication for the user went wrong if the user enter a wrong username/password, they still can make it to the system.
<?php
session_start();
require("conection/connect.php");
$msg="";
if(isset($_POST['btn_log'])){
$uname=$_POST['unametxt'];
$pwd=$_POST['pwdtxt'];
$type=$_POST ['type'];
$sql=mysql_query("SELECT * FROM users_tbl
WHERE username='$uname' AND password='$pwd' AND type='$type'
");
$cout=mysql_num_rows($sql);
if (isset($type))
{
$_SESSION['Parent'] = $type;
header("location: parent.php");
}
else {
$_SESSION['Admin'] = $type;
header("location: admin.php");
exit;
}
}
?>
First don't use mysql_ it's deprecated.
I assume... $type = a means admin and p means oarent.
$sql=mysql_query("SELECT * FROM users_tbl WHERE username='$uname' AND password='$pwd'");
$count=mysql_num_rows($sql);
if($count>0)
{
if ($type=='p')
{
$_SESSION['Parent'] = $type;
header("location: parent.php");
}
elseif($type=='a') {
$_SESSION['Admin'] = $type;
header("location: admin.php");
exit;
}
}
else
{
echo "Wrong username or password";
}
here some solutions. You didn't check if the 'cout' was > 0 (mean found) !
mysql_ driver
Here a solution with your driver (mysql_) :
<?php
session_start();
require("conection/connect.php");
$msg = "";
if(isset($_POST['btn_log'])){
if(isset($_POST['unametxt'], $_POST['pwdtxt'], $_POST['type'])) {
$uname = mysql_real_escape_string($_POST['unametxt']);
$pwd = mysql_real_escape_string($_POST['pwdtxt']);
$type = mysql_real_escape_string($_POST['type']);
$sql = mysql_query("SELECT * FROM users_tbl WHERE username = '$uname' AND password = '$pwd' AND type = '$type'");
$cout = mysql_num_rows($sql);
if($cout > 0){
$_SESSION['type'] = $type;
if($type == "parent")
header("location: parent.php");
else if($type == "admin")
header("location: admin.php");
exit();
}
}
}
PDO version
The mysql_ driver is deprecated and you should use PDO instead. So I did the script for PDO driver too :
<?php
session_start();
require("connection/connect.php"); // PDO connection on $db variable
$db = connect();
// Function to connect an user
function login($db, $uname, $password){
$req = $db->prepare("SELECT * FROM users_tbl WHERE username = :username AND password = :password");
$req->bindParam("username", $uname, PDO::PARAM_STR);
$req->bindParam("password", $password, PDO::PARAM_STR);
$req->execute();
$user = $req->fetch();
if(isset($user['username'])){
$_SESSION['user'] = $user; //store all user datas (including type !)
return true;
}
return false; // fail connection
}
// logic to handle connection form
if(isset($_POST['btn_log'], $_POST['unametxt'], $_POST['pwdtxt'], $_POST['type'])){
if(login($db, $_POST['unametxt'], $_POST['pwdtxt'])){
if(isset($_SESSION['user']['type']) AND $_SESSION['user']['type'] == "admin")
header("location: admin.php");
else
header("location: parent.php");
exit();
}
else
echo "A problem occured !";
}
connect.php (pdo)
define("SQL_USER", "root"); // user
define("SQL_HOST", "localhost"); // host
define("SQL_PASS", ""); // password
define("SQL_DBNAME", ""); //db name
function connect(){
try {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$pdo_options[PDO::ATTR_DEFAULT_FETCH_MODE] = PDO::FETCH_ASSOC;
return new PDO('mysql:host='.SQL_HOST.'; dbname='.SQL_DBNAME, SQL_USER, SQL_PASS, $pdo_options);
}
catch (Exception $e){
die("Error connecting to database");
}
}