This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I am very new to mysqli earlier i am writing queries in mysql but mysqli is more advanced so, i am first time using it.
Below is my php code.
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$email = clean($_POST['email']);
$password = clean($_POST['password']);
//$password =md5($password);
if(empty($res['errors'])) {
$result = $mysqli->query("SELECT uid FROM users where email='$email' and password = '$password'");
if($result->num_rows == 1){
$res['success'] = true;
}
else{
array_push($res['errors'], 'Invalid login details');
$res['success'] = false;
}
}else{
$res['success'] = false;
}
echo json_encode($res);
}
clean function is not working as expected because sql queries return false if i enter username and password correct.
So, it seems like this is not valid in mysqli case.
I checked this link PHP MySQLI Prevent SQL Injection and got to know that we have to prepare query.
I can see there is an example but i am not able to understand how to prepare/bind if i have to use two or more form data.
Thanks for your time.
Updated code
$result = $mysqli->prepare("SELECT uid FROM users where email=:email and password = :password");
$result->execute([
':email' => $email,
':password' => $password]);
//$result->execute();
if($result->num_rows == 1){
//if(mysqli_num_rows($result) === 1) {
$res['success'] = true;
}
else{
array_push($res['errors'], 'Invalid login details');
$res['success'] = false;
}
As already stated in comments, you need to be consistent with your API choice. You can't mix APIs in PHP.
You started out with mysqli_*, so I'll continue with that. You had some mysql_* and PDO in there, and it might not be a bad idea to use PDO over mysqli_* - but if your server supports mysqli_*, there is nothing wrong with using that. See Choosing an API and decide for yourself (just stay away from mysql_*, it's outdated).
Using mysqli_*, you connect to the database like this (you didn't show your connection).
$mysqli = new mysqli("host", "username", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$mysqli->set_charset("utf8");
As for preventing SQL injection in it self, all you need is to use prepared statements. You can still clean or sanitize your data if there are some kind of values you don't want sitting in your tables - but that's kind of another discussion.
You also need to know if your passwords are hashed in the database. They really should be, and you should be using password_hash($password, $algorithm) and password_verify($password, $hash) if you're on PHP5.5 and above (if not, look into something like password_compat).
You need to be consistent with your hashes too, you can't insert it with md5 and selecting it with no hash. It all needs to be the same. Because if you are selecting an md5 hash, and comparing it to an unhashed string, they will be different, and the query fails.
I'm showing you an example of using password_verify(), so that means that the password stored in the database will also need to be stored with password_hash() (or your query fails).
if ($stmt = $mysqli->prepare("SELECT uid, password FROM users where email=?")) {
$stmt->bind_param("s", $_POST['email']); // Bind variable to the placeholder
$stmt->execute(); // Execute query
$stmt->bind_result($userID, $password); // Set the selected columns into the variables
$stmt->fetch(); // ...and fetch it
if ($stmt->num_rows) {
if (password_verify($_POST['password'], $password)) {
// Password was correct and matched the email!
} else {
// Password was incorrect...
}
} else {
// Accountname not found
}
}
This is just a basic example, but it will get you started. Never trust user input, use prepared statements.
You can bind more variables like so:
$stmt = $mysqli->prepare("SELECT uid FROM users where email= ? and password = ?");
$stmt->bind_param('ss', $email, $password);
/* execute prepared statement */
$stmt->execute();
As you can see, you can expand on the bind_param() function. You can also add different type of variables:
i corresponding variable has type integer
d corresponding variable has type double
s corresponding variable has type string
b corresponding variable is a blob and will be sent in packets
From: http://php.net/manual/en/mysqli-stmt.bind-param.php
First of all, I suggest you learn PDO instead of MySQLi, just because it supports more drivers.
Second, you use mysql_real_escape_string, as you might see, that is a MySQL function, not a MySQLi function.
So where you have:
$result = $mysqli->query("SELECT uid FROM users where email='$email' and password = '$password'");
You should do something like:
<?php
$stmt = $dbConnection->prepare("SELECT uid FROM users where email = :email AND password = :password");
try{
$stmt->execute([
':email' => $email,
':password' => $password
]);
}
catch(Exception $e){
echo $e->getMessage(); //Remove when putting online
}
if($stmt->num_rows){
$res['success'] = true;
}
?>
You're presently mixing MySQL APIs/functions with mysql_real_escape_string(), then num_rows and then a PDO binding method where email=:email and password = :password which seems to have been taken from another answer given for your question.
Those different functions do NOT intermix.
You must use the same one from connection to querying.
Consult: Can I mix MySQL APIs in PHP?
It looks like you're wanting to setup a login script. I suggest you use the following and pulled from one of ircmaxell's answers:
Pulled from https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
It's safer and uses a safe password hashing method, rather than what you seem to want to use is MD5 $password =md5($password); and is no longer considered safe to use now.
References:
PDO connection http://php.net/manual/en/pdo.connections.php
PDO error handling http://php.net/manual/en/pdo.error-handling.php
To check if a user exists, you can see one of my answers https://stackoverflow.com/a/22253579/1415724
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting.php
Sidenote: If you do go that route, remember to read the manuals and that your password column is long enough to hold the hash. Minimum length is 60, but they recommend 255.
It is also unclear if your HTML form does have name attributes for the POST arrays, so make sure the form is using a POST method.
http://php.net/manual/en/tutorial.forms.php
I believe I have given you enough information to get started.
What you must NOT do, is to use the above with your present code and simply patching it. You need to start over.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Related
I have been on this all day and after searching many websites (including this one) i came to the conclusion that my question hasn't been asked before probably due to my incompetence.
I have a prepared statement here that i would like to update my password field in my DB depending on the username and email, the reason it is updating and not inserting is because its part of my security to not approve site photographers until they have been sent a link
<?php
if (isset($_POST['approved-photographer'])) {
require 'dbh.php';
$username = $_POST['username'];
$email = $_POST['mail'];
$password = $_POST['password'];
$password2 = $_POST['password-repeat'];
if (empty($username) || empty($email) || empty($password) ||
empty($password2))
{
header("location:signup.php?error=emptyfields&username=" . $username
. "&mail=.$email");
exit();
} elseif ($password !== $password2) {
header("location:approvedphoto.php?error=passwordcheck&username=" .
$username . "&mail=" . $email);
exit();
} else {
$sql = "SELECT Password
FROM photographers
WHERE Username= '$username'
AND Email= '$email'";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location:approvedphoto.php?error=sqlerror");
exit();
} else {
$sql = "INSERT INTO photographers (Password) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location:approvedphoto.php?error=sqlerror2");
exit();
} else {
$hashedpwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "s", $hashedpwd);
mysqli_stmt_execute($stmt);
header("location:signin.php?signup=success");
exit();
}
}
}
}
Any Help would be greatly appreciated. Thanks for reading
The short answer for your MySQLi usage is you didn't bind the parameters, which you can do using mysqli_stmt_bind_param (Future readers, this last statement is now irrelevant due to edits). Overall your sql statements post-editing seem unclear, you would typically either be updating a password (in which case you need a WHERE clause so you don't update everyone's password), or you should be inserting a new user with a password.
This is a more-or-less tangential answer, but I would like to throw my hat into the ring for the use of PDO (instead of mysqli). MySQLi works with only one form of database flavor, MySQL. Additionally it allows for a much less object-oriented solution to db interactions. Here's an example of how you could accomplish this through PDO:
//specifies the driver, ip/database etc. Swap out for your ip and database used
$driverStr = 'mysql:host=<ip>;dbname=<database>;charset=utf8';
//you can set some default behaviors here for your use, I put some examples
//I left a link below so you can see the different options
$options = [
//spew exceptions on errors, helpful to you if you have php errors enabled
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
//substite what you need for username/password here as well, $options can be omitted
$conn = new PDO($driverStr, '<username>', '<password>', $options);
Link to the aforementioned attributes
Now that we've made our connection:
//I used a "named parameter", e.g. :password, instead of an anonymous parameter
$stmt = $conn->prepare("UPDATE Photographers SET password = :password WHERE Username = :username");
//with our prepared statement, there's a few ways of executing it
//1) Using #bind*
//there's also #bindValue for not binding a variable reference
//for params, PARAM_STR is default and can be safely omitted
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
$stmt->bindParam(':username', $username);
$stmt->execute();
//2) Using execute directly
$stmt->execute(['password' => $password, 'username' => $username]);
Then, were the statement a query and not just a database update/insert, we can simply retrieve the results of the statement. By using #bindParam you can also just update the variable's values and re-execute the statement if you like, which may be useful to you for some other statements.
//see #fetch and #fetchAll's documentation for the returned data formatting
$results = $stmt->fetchAll(PDO::FETCH_OBJ); //return it as a php object
$results = $stmt->fetch(PDO::FETCH_NUM)[0]; //unsafely retrieve the first value as a number
Over the years I've found this to be much cleaner and more managable than any of the mysqli_* or even the deprecated mysql_* methods.
I want to protect some content in my site with a password and I am thinking in using this php script
Do you think is a good way to go?
Do you know something better for this task or a way to improve ( if needed) thin one ?
The code to load the content from the database is :
<?php
error_reporting(0);
include("config.php");
if (!isset($_REQUEST["p"])) {
echo 'document.write("<div id=\"protected_'.intval($_REQUEST["id"]).'\">");';
echo 'document.write("<form onsubmit=\'return LoadContent(\"'.intval($_REQUEST["id"]).'\",\"protected_'.intval($_REQUEST["id"]).'\",document.getElementById(\"pass_'.intval($_REQUEST["id"]).'\").value); return false;\'\"><input type=\'password\' size=\'30\' placeholder=\'Content is protected! Enter password.\' id=\"pass_'.intval($_REQUEST["id"]).'\"></form>");';
echo 'document.write("</div>");';
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE `id`='".intval($_REQUEST["id"])."' AND password='".mysql_real_escape_string($_REQUEST["p"])."'";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)==1) {
$row = mysql_fetch_assoc($sql_result);
echo $row["content"];
} else {
echo 'Wrong password';
}
}
?>
As I said in comments, you shouldn't be spending anymore time with what you downloaded since it's old and not safe.
You may be saving passwords in plain text which is definitely not a good idea.
It's time to step into the 21st century.
The mysql_ API is in deprecation and has been deleted from PHP 7.0 entirely.
You are best to use a prepared statement and password_hash() or the compatibility pack.
Here are a few references:
http://php.net/manual/en/book.password.php
http://php.net/manual/en/function.password-hash.php
http://php.net/manual/en/pdo.prepared-statements.php
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
N.B. The use of mysql_real_escape_string() does not fully guarantee protection against a possible SQL injection.
Consult the following Q&A on the subject:
SQL injection that gets around mysql_real_escape_string()
Here is a piece of code pulled from one or ircmaxell's answers which uses a (PDO) prepared statement and password_hash().
Pulled from: https://stackoverflow.com/a/29778421/1415724
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
I hope I formatted the code properly. I am having trouble making this if statement to work. I've searched and from what it looks like this statement should work. However, when I run it no matter the password if the username starts with kacey then it goes to echo "Logged in as: " . kacey;
Likewise, if I put the input to kaceyfeewaf, it still goes to echo "Logged in as: " . $myuser; This happens regardless of the password I put in. the line $result['username'] should validate to KACEY.
$sql = "SELECT * FROM $dbTable WHERE username = $myuser AND password = $mypass";
$result = mysql_query($sql);
if($result['username'] = $myuser && $result['password'] = $mypass;)
{
echo "Logged in as: " . $myuser;
} else {
echo "Fail ";
}
There are a few issues here.
Firstly, the variables you have in your query are strings, therefore they require to be quoted:
WHERE username = '$myuser' AND password = '$mypass'
Having or die(mysql_error()) to mysql_query() would have signaled the syntax error.
Then you're assigning instead of comparing with
if($result['username'] = $myuser && $result['password'] = $mypass;)
use two equals ==
However, that isn't how you check if those rows exist.
You need to use mysql_num_rows() or use a while loop while using a function to fetch/iterate over results found.
Here is an MySQLi example using mysqli_num_rows():
$conn=mysqli_connect("hostname","username","password","db");
$check_select = mysqli_query($conn, "SELECT * FROM `users`
WHERE email = '$email' AND pw='$pass'");
$numrows=mysqli_num_rows($check_select);
if($numrows > 0){
// do something
}
Now, we don't know where those variables have been assigned, and if from a form that it's using a POST method with matching name attributes.
I.e.:
<form action="" method="post">
<input type="text" name="username">
...
</form>
$username = $_POST['username'];
Another thing which is unknown to us is the MySQL API you're using to connect with. Make sure that you are indeed using the same one as you are using to query with, being mysql_. Different APIs do not intermix, such as mysqli_ or PDO. Use the same one from connection to querying.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
I noticed you may be storing passwords in plain text. If this is the case, it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Here is a PDO solution pulled from one of ircmaxell's answers:
https://stackoverflow.com/a/29778421/
Just use a library. Seriously. They exist for a reason.
PHP 5.5+: use password_hash()
PHP 5.3.7+: use password-compat (a compatibility pack for above)
All others: use phpass
Don't do it yourself. If you're creating your own salt, YOU'RE DOING IT WRONG. You should be using a library that handles that for you.
$dbh = new PDO(...);
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $dbh->prepare("insert into users set username=?, email=?, password=?");
$stmt->execute([$username, $email, $hash]);
And on login:
$sql = "SELECT * FROM users WHERE username = ?";
$stmt = $dbh->prepare($sql);
$result = $stmt->execute([$_POST['username']]);
$users = $result->fetchAll();
if (isset($users[0]) {
if (password_verify($_POST['password'], $users[0]->password) {
// valid login
} else {
// invalid password
}
} else {
// invalid username
}
You should use == instead of simple = for your if condition
First of all delete that if stmt and make new one where you check for num rows. If there is num rows > 0 you have valid login. And then print needed results from database od current query.
Edit:
You have = insted of == or === so stmt is always true.
I tried to fetch results from database with mysqli prepared statements and I wanted to store it in session, but I failed. I want to store id, username, password and mail to session. Can anyone review my code?
$kveri = $mysqli->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$kveri->bind_param('ss', $username, $password);
$kveri->execute();
$kveri->store_result();
$numrows = $kveri->num_rows;
if ( $numrows == 1 )
{
$kveri->bind_result($user_id, $user_username, $user_password, $user_mail);
while ( $kveri->fetch() )
{
$_SESSION['ulogovan'] = true;
$_SESSION['username'] = $user_username;
}
$kveri->close();
echo $_SESSION['username'];
}
Make sure you have turned on error reporting as follows:
mysqli_report(MYSQLI_REPORT_ALL);
You are likely to get the answer there. I ran your code flawlessly and it should work.
Note, I added the following code to the beginning to test (with constants defined but not shown here):
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS,DB_NAME);
As you can see, mysqli is quite inconvenient, if used as is. Thousand tricks, nuances and pitfalls.
To make database interactions feasible, one have to use some sort of higher level abstraction, which will undertake all the repeated dirty job.
Out of such abstractions PDO seems most conventional one:
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->execute([$username, $password]);
$user = $stmt->fetch();
if ($user) {
$_SESSION['username'] = $user['username'];
}
see - when used wisely, a code not necessarily have to be of the size of "War and Peace"
I can't figure out why the password isn't matching when attempting to login after activation. I've trimmed down the pasted code below for ease of viewing.
Here is the relevant registration code:
$salt = substr(sha1(uniqid(rand(),true)),0,20);
$password_db = hash('sha256', $salt.$password1);
$sqlinfo = mysql_query("INSERT INTO db_1 (email, password, salt)
VALUES('$email1','$password_db','$salt')") or die(mysql_error());
Here is the correlating code for login:
$email = $_POST['email'];
$password = $_POST['password'];
$sqlinfo = mysql_query("SELECT * FROM db_1 WHERE email='$email' AND emailactiv='1'");
if($sqlinfo['password'] == hash('sha256', $sqlinfo['salt'].$password)){
while($row = mysql_fetch_array($sqlinfo)){
... }
else { ...
I've done several iterations thus far to no avail. Any insight would be much appreciated.
you code, currently, is vulnerable with SQL injection. One suggestion is to reformat your code using PDO or MySQLI.
Example of PDO:
<?php
$stmt = $dbh->prepare("SELECT * FROM db_1 WHERE email = ? AND emailactiv=? ");
$stmt->bindParam(1, $email);
$stmt->bindParam(2, 1);
$stmt->execute();
?>
you didn't fetch the row that's why it's not matching anything.
add this line before the IF statement:
$rowHere = mysql_fetch_row($sqlinfo);
and use $rowHere in your IF statement.
$email = $_POST['email'];
$password = $_POST['password'];
$sqlinfo = mysql_query("SELECT * FROM db_1 WHERE email='$email' AND emailactiv='1'");
//You need to first fetch data before using it.
while($result = mysql_fetch_array($sqlinfo)) {
//Now you can use the data
if($result['password'] == hash('sha256', $result['salt'].$password)){
//matched... login correct
} else {
//not matched.. invalid login
}
}
...
Hope it's self-explanatory.
You missed one very important line!
BTW, stop using mysql_* functions as they are deprecated, use PDO or mysqli_*
EDIT: Please try now. I thought it can only hold one value (for login purpose)
You need to use mysqli_fetch_array.
Also, mysql_* functions are deprecated. Use MySQLi or PDO instead.
And you need to 'sanitize your inputs' (a common phrase) to avoid SQL injection, using mysqli_real_escape_string or PDO.
See the Bobby Tables link as per the comments on the question.