I am having some problem connecting properly to the MySQL server using the PDO function.
I can't query what I need from the database and I am not quite sure what PDO functions to use.
I GET 0 as a result of this.
I wish to verify the password and username I enter via the database and make an if statement that launches the session if the information is correct.
Here is my UPDATED code:
<?php
// if a value is given
if (isset($_POST['username' && 'password'));
{
// starts the session created if login info is correct
session_start();
// connectivity to MySQL server
$db = new PDO('mysql:host=host;dbname=name', 'username', 'password');
// information entered in form made into a variable
$username = PDO::quote($_POST['username']);
$password = PDO::quote($_POST['password']);
// after pressing login, checking if the variables exist in the database
if ($_POST['button'] == 'Login')
{
$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query = $db->fetch(PDO::FETCH_OBJ))
{
echo "No records found";
}
else
{
header("Location: members.php");
$_SESSION['username'] = $_POST['username'];
}
}
// After pressing register, stores variable and adds it in register field
else if ($_POST['register'] == 'Register')
{
header("Location: register.php");
$_SESSION['usernamereg'] = $_POST['username'];
}
// If no button is pressed, send to index
else
{
header("Location: http://www.gjertgjersund.com");
}
// closes the if value is given statement
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Folder </title>
<link rel="stylesheet" type="text/css" href="frontpage.css">
</head>
<body>
<div id="box">
<div id="wrap">
<center>
<img src="./img/logo.png" alt="logo">
<form action='index.php' method='POST' autocomplete='off'>
<div class="usernameform">
<input type='text' name='username' style='border: none; font-size: 20px;'>
</div>
<br />
<div class="passwordform">
<input type='password' name='password' style='border: none; font-size: 20px;'>
</div>
<br />
<div class="registerlogin">
<input type='submit' name='button' value='Login' class='input'>
<input type='submit' name='register' value='Register' class='inputtwo'>
</div>
</form>
</center>
</div>
</div>
</body>
</html>
That's a very good question, partially because it demonstrates a lot of bad practices that, sadly, exist to this day, almost a decade since this question has been posted. Let's sort them out
Connection
I am having some problem connecting properly to the MySQL server using the PDO function.
That's a fair question and nowhere the connection is just a single line of code. Мany important options have to be set, see a canonical connection example I wrote. You can store the connection code in a separate file and then just include it in your scripts.
Password hashing
You should never store plain passwords in your database. Instead, password must be hashed, using a dedicated function made for the purpose - password_hash().
Then, to verify the password, you've go to use password_verify()
Don't move any further until you have your passwords properly hashed. Note that the field size for the hashed password must be 60 characters long.
The code to verify username and password
Finally, now we can write the code. It could be much simpler, just a few lines. Actually, only one condition is needed. We shouldn't provide any details as to whether login or username not found - just "Login and password don't match". So here it goes:
<?php
if (isset($_POST['username']))
{
// get the PDO instance
include 'pdo.php';
// getting the record for the given username
$stmt = $pdo->prepare("SELECT * FROM login WHERE username=?");
$stmt->execute([$_POST['username']]);
$user = $stmt->fetch();
// verifying the password
if ($user && password_verify($_POST['password'], $user['password']))
{
// starts the session created if login info is correct
session_start();
$_SESSION['username'] = $user['username'];
header("Location: members.php");
exit;
} else {
$error = "Login and password don't match";
}
}
Here, we are checking whether such a user exists and whether the password matches in a single condition.
You should not have to use ' in prepared statement and $username is string not integer
$query = $db->query("SELECT * FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
$row_count = $query->rowCount();
//{ remove it
Your if condition is wrong change
// if a value is given
if (isset($_POST['username' && 'password'));
{
to
// if a value is given
if (isset($_POST['username']) and isset($_POST['password']))
{
Codepad
Some databases may return the number of rows returned by a SELECT statement. However, this behaviour is not guaranteed for all databases and should not be relied on see Manual. You can use COUNT(*) and fetchColumn() as in following query to emulate rowCount().
$query = $db->query("SELECT COUNT(*) FROM login WHERE username=:username AND password=:password");
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);
$query->execute();
// Check the number of rows that match the SELECT statement
if($query->fetchColumn() == 0) {
echo "No records found";
}else{
//CODE FOR Success
//Etc
}
Related
<?php
ini_set('display_errors', '1');
require_once 'core/init.php';
if(logged_in() === TRUE) {
header('location: dashboard.php');
}
if($_POST) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "") {
echo "Username Field is Required <br />";
}
if($password == "") {
echo "Password Field is Required <br />";
}
if($username && $password) {
if(userExists($username) == TRUE) {
$login = login($username, $password);
if($login) {
$userdata = userdata($username);
$_SESSION['id'] = $userdata['id'];
header('location: dashboard.php');
exit();
} else {
echo "Incorrect username/password combination";
}
} else{
echo "Username does not exists";
}
}
} // /if
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles1.css">
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<title>Login</title>
</head>
<body class="container">
<div class = "login-box">
<img src = "image/person1.png" class = "avatar">
<h1 id = "login-header">Login</h1>
<form id=registration_form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
<div>
<label for="username">Username</label>
<input type="text" name="username" id="form_username" autocomplete="off" placeholder="Username" />
<span id="username_error"></span>
</div>
<br />
<div>
<label for="password">Password</label>
<input type="password" name="password" id="form_password" autocomplete="off" placeholder="Password" />
<span id="password_error"></span>
</div>
<br />
<div>
<input type="submit" name="btnLogin" value = "Login">
</div>
Not yet a member? Register
</form>
</body>
</html>
Can somebody help me regarding to my PHP. I'm very new in PHP. My website must have a multi-login user. But I try to do it and I failed. I don't received any error. But the problem is when I press the login button nothing happen. If the user_type is equal to admin I want to link it to adminPanel.php and if user_type is equal to user I want to link it to userPanel.php. Can somebody fix my code below. I really appreciate it.
function login($username, $password) {
global $connect;
$userdata = userdata($username);
if($userdata) {
$makePassword = makePassword($password, $userdata['salt']);
$sql = "SELECT * FROM tbl_user WHERE username = '$username' AND password = '$makePassword'";
$query = $connect->query($sql);
if($query->num_rows == 1) {
$logged_in_user = mysqli_fetch_assoc($query);
if ($logged_in_user['user_type'] == 'admin') {
$_SESSION['user'] = $logged_in_user;
header('location: adminPanel.php');
}else{
$_SESSION['user'] = $logged_in_user;
header('location: userPanel.php');
}
}
}
$connect->close();
// close the database connection
}
Forword
I feel generous tonight...
This may not fix your issue. As I said in the comments, there are many things that can be wrong. Without more information on what is happening, how you do things there is no way to tell.
These are things that are important (things to check)
how you submit the post (the form)
fields could be named wrong, form could be setup wrong etc.
the form action could simply be wrong
the form method could simply be wrong
how you handle that submission
variables could be sent to login() incorrectly, login($password,$username) instead of login($username,$password)
vairables could simply be translated wrong, for example you could have $_POST['user'] insead of $_POST['username']
you could be doing validation checks on input, which may or may not remove data, could be wrong.
how you handle starting the session
you can't use session until you start it
what if any output you have when handling the submission
output before header location will prevent the redirect
header location does not exit the current code scope, stuff after it can run so you should call exit after doing a redirect.
how you connect to the DB
you may have DB error
what if any errors you get, what error reporting do you have
you could have errors your not reporting for any of the above, and many things I didn't mention.
You probably shouldn't roll you own login system until you have a better handle on the security implications ( and other things).
Password/Security
The makePassword function is not included (in your code), but in any case you should use the built in (PHP5.4+) password function. It's much more secure and saves a lot of work:
function makePassword($plaintext){
return password_hash($plaintext, PASSWORD_DEFAULT);
}
This will return a 60 char long hash, but it's recommended to use VARCHAR(255).
It will look something like this in the DB:
//$2y = BCRYPT (default), $10 Cost or iterations (default), that's all I can remember.
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
Then for login (MySqli):
//session_start(); //make sure this is called
function login($username, $password, \mysqli $connect) //use type hinting
{
//can fail because of syntax errors, missing privileges
$stmt = $connect->prepare('SELECT * FROM tbl_user WHERE username = ?') OR die($connect->error);
//can fail because of incorrect number of arguments, invalid types
$stmt->bind_param("s", $username) OR die($stmt->error);
//can fail for various reasons
$stmt->execute() OR die($stmt->error);
$result = $stmt->get_result();
if($result->num_rows == 1) {
$user = $result->fetch_assoc($query);
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error
}
}else{
//username error
}
}
Personally I only use PDO these days. It's been several years sense I used MySqli (so forgive me if I got anything wrong here).
For PDO, this is how I connect with it:
$dsn = 'mysql:dbname=database;host=localhost';
$user = 'user';
$pass = 'pass';
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
try{
$PDO = new PDO($dsn, $user, $pass, $options);
}catch(PDOException $e){
//only show end user error codes
die("Error[{$e->getCode()}] connection to DB");
}
The options turn on, Exception error reporting and set the default fetch mode to fetch associative array. With those settings the same thing as above can be done like this:
//session_start(); //make sure this is called
function login($username, $password, \PDO $Pdo) //use type hinting
{
try{
$stmt = $Pdo->prepare('SELECT * FROM tbl_user WHERE username = :username');
$stmt->execute([':username' => $username]);
if($stmt->rowCount()){
$user = $stmt->fetch();
if(password_verify($password, $user['password'])){
$_SESSION['user'] = $user;
header('location: '.$user['user_type'].'Panel.php');
exit;
}else{
//password error, return an error, or throw an exception etc.
}
}else{
//username error
}
}catch(PDOException $e){
//only show end user error codes
die("Database Error[{$e->getCode()}]");
}
}
If you notice it takes around 5 calls to MySqi, and PDO takes only 3 calls. Besides that MySqi is dealing with 3 objects (mysqli, mysqli_stmt, mysqli_result), PDO deals with only 2 (PDO, PDOStatment). Error reporting is also much cleaner.
A few other notes.
use password_hash($plaintext, algo) to create hashes
use password_verify($plaintext, $hash) to check passwords (note plaintext)
use prepared statements
Do not lookup by password, it's not a secure way of verifing 2 hashes are the same (casing, encoding etc...)
use session_start() before using $_SESSION
Do not output anything (not even a single space) before using header
call exit; after using header as it doesn't exit the script it's called in, so it can run code beneath it and produce unexpected results
avoid using global it can be hard to debug your code, instead use dependency injection (pass in the DB connection)
use DRY principals (Dont Repeat Yourself)
And there is probably a bunch of stuff I am forgetting.
UPDATE
Based on the code you added, the part that handles the form submission can be done like this:
<?php
error_reporting(E_ALL); //unclear
ini_set('display_errors', '1');
require_once 'core/init.php';
if(true === logged_in()) { //put constant values on the left
header('location: dashboard.php');
}
if('POST' == $_SERVER['REQUEST_METHOD']){ //put constant values on the left
//ternary condition (shorthand if then)
$username = empty($_POST['username']) ? false : $_POST['username'];
$password = empty($_POST['password']) ? false : $_POST['password'];
//PHP7+ null coalescing can be used instead of above
//$username = $_POST['username'] ?? false;
if(!$username) {
echo "Username Field is Required <br />";
}
if(!$password) {
echo "Password Field is Required <br />";
}
if($username && $password) {
login($username, $password);
//don't forget the connection, if you use the functions without
//it as a global, (which I refuse to use). I once spent a week
//tracking down changes to a global variable in some code I was fixing, never again.
// global $connect;
// login($username, $password, $connect);
}
}
You don't need to do redirects after calling login it's already doing them. You don't need to check if the user exists because you are already checking when fetching there saved password. If you need to know that information there you can either throw exceptions (to much to cover) or you can have the login function return them. In the case that the login is successfule the code will exit before the errors can return.
Summery
My best guess, barring any errors (and assuming the session is started) is that this is happening
form submission, to self
call to login()
everything works, call to header('location: adminPanel.php'); (with no exit)
code returns to the form page (because no exit)
call to header('location: dashboard.php'); And exit();
But that is just a guess, because when yo say "when I press the login button nothing happen" that can mean many things.
One of these days I will put a tutorial for something like this on my website, but it will be more comprehensive.
Anyway, hope it helps you.
I'm trying to create a login page that queries the database to check if the username and password are valid and allowing access to the following pages using sessions. Currently, I'm just using XAMPP to test the login. This is the following code I have in a PHP page.
<?php
include("config.php");
session_start();
// Check for POST method
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = stripslashes($_POST['username']);
$username = mysqli_real_escape_string($con, $username);
$password = stripslashes($_POST['password']);
$password = mysqli_real_escape_string($con, $password);
//Search database for username and password
$stmt = $con->prepare("SELECT * FROM users
WHERE username = ? LIMIT 1"); // Prepared statement
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_object();
if(password_verify($_POST['password'], $user->password)) {
echo("working");
$_SESSION['loggedin'] = true;
$_SESSION['user'] = $user->username;
header("Location: index.php");
} else {
echo("no user");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Login</title>
</head>
<body>
<form id="loginForm" method="post" action="">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>
I added an echo statement just to see if it would output "no user" for both user/passwords sets in the database and not in it. They both display "no user" so I don't think I'm searching the database correctly. I'm sort of new to PHP and I used this code.
UPDATE
Thanks to comments, fixed passwords so that they were hashed.
When it still was not working:
Set password datatype in database to VARCHAR(60), recommended VARCHAR(255)
I realized it was because I had password datatype set to VARCHAR(40). Since I was using bycrypt to hash, it is a 60 character string. I set my password to the recommended VARCHAR(255) in case I decided to use PASSWORD_DEFAULT in the future. I failed to realize this is all mentioned in password_hash() documentation when initially creating the database and fields.
Added session_start() to all pages referencing $_SESSION[]
Echoed var_dump() to display the result of password_verify() that returned true when I entered the correct information, however, the page stil kept redirecting me to login. In the PHP I was redirecting to I had this section of code:
<?php
if($_SESSION['loggedin'] == false) {
header("Location: login.php");
} else {
}
?>
I forgot to put session_start(); in the PHP page so it kept redirecting me to the login.
I'm trying to use the following form to log in, but it always jump to invalid username. Am I missing anything in here?
Database Connection:
$link = mysqli_connect("localhost","X","X","X");
if($link == false) {
die("Error" .mysqli_connect_error());
}
Login Script:
<?php
if (!isset($_POST['submit'])) {
?>
<!-- The HTML login form -->
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>
<?php
} else {
// Include database credentials
include('../db_connect.php');
$mysqli = new mysqli($link);
// check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * from admin WHERE admin_email LIKE '{$username}' AND admin_password LIKE '{$password}' LIMIT 1";
$result = $mysqli->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
}
?>
I'm not 100% sure, but I think getting rid of the {} around the $username and $password should fix the issue, and yea, using LIKE for login is bad. I could then type %abijeet% in my username and %p% in the password field and get logged in as long as there is someone called abijeet in the system and has a password with the letter p in it.
Using PDO
Also, filtering the input from the $_POST is a good idea. In general, I'd ask you to drop using mysqli and look into PDO - http://php.net/manual/en/book.pdo.php
Using PDO properly with parameters will secure you against SQL Injection attacks.
Hashing the password
Don't store the password in plain test, hash it before saving. Check here - http://php.net/manual/en/function.password-hash.php
UPDATE -
OK, so as pointed out the {} are ok. Another thing that looks suspicious to me is the condition checking.
I would change it to this -
// Check the condition checking below!
if ($result->num_rows !== 1) {
echo "<p>Invalid username/password combination</p>";
} else {
echo "<p>Logged in successfully</p>";
// do stuffs
}
It could be an operator precedence issue and is anyways more confusing.
I have a PHP site that I made that has an option to edit your account. On the edit account page, I have the username, Real Name, email, and password displayed. Everything display's perfectly except for the real name, which comes up as a blank. It displays fine on my memberlist page.
Here is my code
<html>
<head>
<title>Site</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: login.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to login.php");
}
// This if statement checks to determine whether the edit form has been submitted
// If it has, then the account updating code is run, otherwise the form is displayed
if(!empty($_POST))
{
// Make sure the user entered a valid E-Mail address
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
die("Invalid E-Mail Address");
}
// If the user is changing their E-Mail address, we need to make sure that
// the new value does not conflict with a value that is already in the system.
// If the user is not changing their E-Mail address this check is not needed.
if($_POST['email'] != $_SESSION['user']['email'])
{
// Define our SQL query
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
// Define our query parameter values
$query_params = array(
':email' => $_POST['email']
);
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Retrieve results (if any)
$row = $stmt->fetch();
if($row)
{
die("This E-Mail address is already in use");
}
}
// If the user entered a new password, we need to hash it and generate a fresh salt
// for good measure.
if(!empty($_POST['password']))
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
}
else
{
// If the user did not enter a new password we will not update their old one.
$password = null;
$salt = null;
}
// Initial query parameter values
$query_params = array(
':email' => $_POST['email'],
':user_id' => $_SESSION['user']['id'],
);
// If the user is changing their password, then we need parameter values
// for the new password hash and salt too.
if($password !== null)
{
$query_params[':password'] = $password;
$query_params[':salt'] = $salt;
}
// Note how this is only first half of the necessary update query. We will dynamically
// construct the rest of it depending on whether or not the user is changing
// their password.
$query = "
UPDATE users
SET
email = :email
";
// If the user is changing their password, then we extend the SQL query
// to include the password and salt columns and parameter tokens too.
if($password !== null)
{
$query .= "
, password = :password
, salt = :salt
";
}
// Finally we finish the update query by specifying that we only wish
// to update the one record with for the current user.
$query .= "
WHERE
id = :user_id
";
try
{
// Execute the query
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Now that the user's E-Mail address has changed, the data stored in the $_SESSION
// array is stale; we need to update it so that it is accurate.
$_SESSION['user']['email'] = $_POST['email'];
// This redirects the user back to the members-only page after they register
header("Location: private.php");
// Calling die or exit after performing a redirect using the header function
// is critical. The rest of your PHP script will continue to execute and
// will be sent to the user if you do not die or exit.
die("Redirecting to private.php");
}
?>
<h1>Edit Account</h1>
<div class="body">
<form action="edit_account.php" method="post">
Name:<br />
<b><?php echo htmlentities($_SESSION['user']['name'], ENT_QUOTES, 'UTF-8'); ?>
</b>
<br><br>
Username:<br />
<b><?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?></b>
<br /><br />
E-Mail Address:<br />
<input type="text" name="email" value="<?php echo htmlentities($_SESSION['user']
['email'], ENT_QUOTES, 'UTF-8'); ?>" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" /><br />
<i>(leave blank if you do not want to change your password)</i>
<br /><br />
<input type="submit" value="Update Account" />
</form>
</div>
</body>
</html>
I'm having some trouble with my login feature. I've been searching for hours and I could'nt find any problem. I hope you guys will help me.
I want to get users' login and check if it exists in my DB. Problem is it keeps returning me : "Password was probably incorrect!".
I tried an "echo ($count)", it doesn't return anything. Same thing for "echo($result)".
I'm pretty lost right, I can't understand why this doesn't work...
PS : I'm french so you might see some french words.
Here's my login form :
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Applications</title>
<!--Chargement des feuilles de style-->
<link rel="stylesheet" type="text/css" href="./css/style.css" />
<link rel="stylesheet" type="text/css" href="./css/styleLogin.css" />
<script src="./js/login/modernizr.custom.63321.js"></script>
</head>
<body>
<div class="container">
<header></header>
<section class="main">
<form class="form-2" id="loginForm" action="./controller/checkLogin.php" method="post">
<h1><span class="log-in">Se connecter</span></h1>
<p class="float">
<label for="loginLabel"><i class="icon-user"></i>Nom d'utilisateur</label>
<input type="text" name="login" id="login">
</p>
<p class="float">
<label for="passwordLabel"><i class="icon-lock"></i>Mot de passe</label>
<input type="password" name="password" class="showpassword" id="password">
</p>
<p class="clearfix">
<input type="submit" name="submit" value="Se connecter">
<input type="button" name="submitVisit" value="Accès utilisateur">
</p>
</form>
</section>
</div>
</body>
And here's my checkLogin.php :
<?php
session_start();
try {
$bdd = new PDO('mysql:host=localhost;dbname=stage','root','');
}
catch (Exception $e){ //en cas d'erreur de connexion, afficher le message
die('Erreur : '.$e->getMessage());
}
if(isset($_POST['submit'])){
// username and password sent from form
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = 'admin'";
$result = mysql_query($qry);
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
if($count == 0){
die("Password was probably incorrect!");
}
// If result matched $myusername and $mypassword, table row must be 1 row
elseif($count == 1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['login'] = $login;
header("location: ./login_success.php");
}
else {
echo "Wrong Username or Password";
}
}
mysql_close($bdd);
?>
I want to log in with this couple : admin/admin.
Thank you in advance.
There are a few problems with your script.
First off, you start by using PDO to connect to the database, then you use mysql_* functions (which are deprecated, stick to PDO !!!). Plus, you are not properly escaping your data, and your code is potentially vulnerable to SQL injection.
Secondly, the query you are using is ... not good.
// this is not checking for either the user input data !!!
$qry = "SELECT login FROM users WHERE login = 'admin'";
Your verification code should be something like this:
$ps = $bdd->prepare("SELECT COUNT(*) FROM users WHERE login = :login AND pass = :password");
$params = array("login" => $_POST['login'], "password" => $_POST['password']);
$ps->execute($params);
$status = (bool) $ps->fetchColumn(0);
if ($status) {
// login successful
} else {
// login failed
}
Read up on PDO and prepared statements (they automatically escape your data, so you don't have to).
Note:
If you don't use prepared statements in future code, remember to always escape input from users and pretty much any other source of information.
1) You are mixing mysql and PDO which is a disaster. Mysql_ interface is deprecated use mysqli or pdo please...
2)
"SELECT login FROM users WHERE login = 'admin'";
finds only users with login admin... So you have to
"SELECT login FROM users WHERE login = '$login'";
3) $_POST variables are not safe. Users can inject malicious code...
For instance If you use mysqli then
$login = mysqli_real_escape_string($_POST['login']);
To sanitize login entry and do the same for password too.
since everybody gave advice on general issues i cut to the chase
change:
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = 'admin'";
assuming the password ist saved to a database field named "passwort" to:
$login = $_POST['login'];
$pass = $_POST['password'];
$qry = "SELECT login FROM users WHERE login = '".mysql_real_escape_string($login)."' and password= '".mysql_real_escape_string($password)."'";
mysql_real_escape_string keeps you from beeing hacked and the database query now uses the values from the post ...
The problem is, that you are mixing mysql_* functions and PDO.. the code should looks like this:
Note the prepare function which binds parameters to your SQL query - it prevents SQL injections.
session_start();
try {
$pdo = new PDO('mysql:host=localhost;dbname=stage','root','');
}
catch (Exception $e){ //en cas d'erreur de connexion, afficher le message
die('Erreur : '.$e->getMessage());
}
if(isset($_POST['submit'])){
// username and password sent from form
$login = $_POST['login'];
$pass = $_POST['password'];
$sql = "SELECT login FROM users WHERE login = :login AND password = :password";
$params = array( 'login' => $login, 'password' => $pass );
$sqlprep = $pdo->prepare($sql);
if($sqlprep->execute($params)) {
$count = $sqlprep->rowCount();
if($count != 1){
die("Incorrect login!");
} else {
$_SESSION['login'] = $login;
header("location: ./login_success.php");
}
}
}