I have tryed this many many times and i don't get why this don't work. Because of this my registeration pages pass all usernames. I have no idea what is wrong. Sorry about my bad english i am really tired and desperate
function user_exists($username){
$username = htmlspecialchars($username);
$sql = "SELECT username FROM ***** WHERE username = '$username'";
$result = mysqli_query($GLOBALS['$db'], $sql);
if(mysqli_num_rows($result) > 0){
$errors[] = 'Käyttäjätunnus \''. $_POST['username'] . '\' on jo otettu.';
}
}
I am calling that function like this:
if(user_exists($_POST['username']) === true){
$errors[] = 'Käyttäjätunnus \''. $_POST['username'] . '\' on jo otettu.';
}
Well, let's clean this up some
function user_exists(mysqli $db, $username){
$username = htmlspecialchars($username);
$sql = "SELECT username FROM ***** WHERE username = ?";
$prep = $db->prepare($sql);
$prep->bind_param('s', $username);
$prep->execute();
$result = $prep->get_results();
$errors = [];
if($result->num_rows > 0){
$errors[] = 'Käyttäjätunnus \''. $username . '\' on jo otettu.';
}
return $errors;
}
First, you need to inject your DB connection into the function. Avoid using globals.
Second, we're switching to a prepared statement. Solves the SQL injection problem.
Third, we're returning an array. Your errors will never show up the way you were doing it. You can pick how/what gets returned, but, again, we don't want globals.
Related
I am trying something I found online (Extremely new to this) and none of it works. It's some random science project I decided to learn more about yet I am stuck on part 2 of the "procedures". https://www.sciencebuddies.org/science-fair-projects/project-ideas/Cyber_p008/cybersecurity/sql-injection#procedure
I watched videos but they only consist of just a user_ID and not a username and password. NOTE: Only the code dealing with login.php is causing problems.
<?php
include("global.php");
include("db.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password are sent in the form
$username = $_POST['username'];
$password = $_POST['password'];
// Check if the username and password exist in the database
$sql = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$stmt = msqli_stmt_init($db);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "SQL Statement Failed";
} else {
mysqli_stmt_bind_param($stmt, "ss", $username, $password );
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);}
// If username and password matched then there is one row in the result
if ($count != 0) {
$_SESSION['login_user'] = strtolower($username);
header("location: search.php");
}
else {
$error = "Your Username or Password is invalid";
}
}
?>
It should have prevented a basic " 'or''=' " injection attack but it decided not to work entirely.
If you use query parameters — which is definitely a good idea — you must leave placeholders in your query. Use ? as the placeholder.
Like this:
$sql = "SELECT username FROM users WHERE username = ? AND password = ?";
You later bind variables to those parameters. You must bind the same number of variables as the number of parameter placeholders.
You got the error you described because you tried to bind variables to a query that had no parameter placeholders.
I'm trying to conduct an experiment using a pre-coded project which inside this link here.
I'm using xampp as a web server with mysql. Whenever I run through the authentication page which has this code:
<?php
include_once("zSessionStart.php");
include_once("zConfig.php");
include_once("zDB.php");
$password = $_REQUEST["password"];
$userID = $_REQUEST["userID"];
$isAdmin = false; //is administrator or not
$askDemo = false;
//authenticate the login data from login.php
$query="select userID, isAdmin, askDemo from $_usersTable where (password= '$password') and (userID='$userID');";
$rs=mysql_query($query) or die ("Invalid sql.");
if ( mysql_num_rows($rs) > 0 ) //correct password
{
$array = mysql_fetch_array($rs);
if(strcmp($array["isAdmin"], "y")==0){
$isAdmin=true;
}
if(strcmp($array["askDemo"], "y")==0){
$askDemo=true;
}
if(!$isAdmin){
$query="select userID from usertests where userID='" . $userID . "'";
$rs2=mysql_query($query) or die ("Invalid sql.");
if(mysql_num_rows($rs2) > 0){ //already take test
$array2 = mysql_fetch_array($rs2);
echo "<h2> You have already taken the task. Please contact your administrator if you " .
" feel you need to re-take this task again.</h2>";
die();
}
}
$_SESSION['userID'] = $array["userID"];
session_unregister('loginErr');
if($isAdmin){
header("Location: transfer.php?" . SID);
}else{
if($askDemo){
header("Location:demo.php?" . SID);
}else{
header("Location: index.php?" . SID);
}
}
}
else
{
$_SESSION['loginErr'] = "true";
header("Location: login.php");
}
mysql_close($db);
?>
I receive an error that says "Invalid sql.". Inside my database I have a table called users which has credentials such as userID and password. I've already set the username to be admin and password to be pass. However, I haven't had any luck figuring out what the issue might be.
Your Query is invalid because you are using wrong table name that is even no variable syntax i.e. $_usersTable. And also you are ending your query with multiple semi colons and even single/double quotes are not properly used.
You need to update your select query like below to resolve your issue:
$query="select userID, isAdmin, askDemo from usersTable where password = '".$password."' and userID ='".$userID."';
I strongly recommend you to use MySqli Prepared Statement Query to make it more Secure like below:
$mysqli = mysqli_connect($host, $username, $password, $db);
$query = "SELECT userID, isAdmin, askDemo from `usersTable` WHERE userID=?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $userID);
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_all();
To learn more about it, follow link http://php.net/manual/en/mysqli.prepare.php
This question already has an answer here:
I cannot get my login form to connect interact properly with mySQL database [closed]
(1 answer)
Closed 6 years ago.
I am very new to php and I am trying to create a login system. Here is my code
<?php
$con=mysqli_connect("XXXXXXX","XXXXXXXX","XXXXXXXXX","XXXXXXXXXX");
if (!$con)
{
echo "failed to connect";
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT userID FROM users WHERE username = $username and password = $password;";
if (!$sql) {
echo 'query invalid'.mysql_error();
}
$result = mysql_query($sql);
echo "$result";
$row = mysqli_fetch_array($sql, MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
mysql_close($con);
?>
I am sure there is no problem with the connection. But my result is not showing up and there is no error message. Previously I had an IF statement that perform further action if the result comes back. Since I am trying to figure out what is going on, I just deleted that part. Somebody please help. Many thanks
You're missing the single quotes around the variables, and also you're using mysql mixed with mysqli, which will not work.
$sql = "SELECT userID FROM users WHERE username = '$username' and password = '$password';";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_assoc($sql); // same as fetch_array with MYSQLI_ASSOC
$active = $row['active'];
$count = mysqli_num_rows($result);
You don't need mysql_close at the end, but if you want to use it, it's mysqli_close($con);
Keep in mind this is unsafe.
Use this function to filter user input:
$username = mysqli_real_escape_string($con, $_POST['username']);
$password = mysqli_real_escape_string($con, $_POST['password']);
Read this to make sure your code follows the security standards.
I recommend this.
$sql = "SELECT userID FROM users
WHERE username = " ._sql($username) ." and password = " ._sql($password);
// generate sql safe string function
function _sql($txt) {
if ($txt === null || $txt === "")
return "NULL";
if (substr($txt, 0, 2) == "##")
return substr($txt, 2);
//$txt = str_replace("'", "''", $txt);
$txt = mysql_real_escape_string($txt);
return "'" . $txt . "'";
}
I send a password to php to get compared to the hash stored in the database.
my php is:
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
$query = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$passHash = mysql_result($query, 0);
if(password_verify($enteredPass, $passHash)){
echo "success";
}else{
echo "failure";
}
I also tried using mysqli_fetch_array() as well, but it still doesn't work. Does anyone know why this isn't working? thanks in advance to anyone who can help. (on a side note, $passHash returns null)
You are mixing two extensions, mysqli and mysql - mysqli_query and then mysql_result.
You are also open to SQL injection and should be sanitising your POST input before passing it directly to MySQL.
mysqli_query returns a result object and you then need to fetch the results from that object.
mysqli_fetch_row will return one row.
$enteredUser = $_POST["username"];
$enteredPass = $_POST["password"];
//...
$resultset = mysqli_query($con, "SELECT passhash FROM user WHERE `username` = '$enteredUser'");
$result = mysqli_fetch_row($resultset);
if(password_verify($enteredPass,$result[0])){
echo "success";
}else{
echo "failure";
}
I did solve my own problem with a simple while loop, i guess it will work fine, thanks everyone for your input:
$passHash = '';
while ($row = mysqli_fetch_array($query)) {
$passHash .= $row["passhash"];
}
Give this a try:
$enteredUser = mysqli_real_escape_string($con,$_POST["username"]);
$enteredPass = mysqli_real_escape_string($con,$_POST["password"]);
$sql = "SELECT * FROM `user` WHERE `username` = '$enteredUser'";
$result = $con->query($sql);
if ($result->num_rows === 1) {
$row = $result->fetch_array(MYSQLI_ASSOC);
if (password_verify($enteredPass, $row['passhash']))
{
echo "Success";
}
else {
echo "Sorry";
}
im new at programing and php, and i want to create an error on my registration system that when the user creates an account with the same username already existing in the database it says something like this: "Username already in use" and then if it isnt an existing username it says "Registation Complete"
I tried this code:
<?
require ("conect.php");
$user = $_POST['user'];
$pass = $_POST['password'];
$email = $_POST['email'];
$email_check = $_POST['email_check'];
$register = mysql_fetch_array;
if($user = $register[user]) {
echo"Username already in use";
}
else
{
$insert = mysql_query("INSERT INTO registration (user, password, email)
VALUES('$_POST[user]','$_POST[password]','$_POST[email]')");
echo "The account $user was successfully created.";
}
?>
But it didnt work, can someone help please
As pointed out by the other users, you should be using prepared statements through PDO (or mysqli, but I definitely prefer PDO)
You're storing the POSTS in variables, but then in the database query you are just using the $_POST variable again?
I'm not sure what your doing with the $register = mysql_fetch_array part, but to get the desired functionality you should use a select query to count the number of users using the username.
You're not using any secure hash format to store the password. I switched it to use password_hash().
Try something like this (I haven't tested the code yet though, so there might be errors):
<?php
//Put all POSTS in variables
$user = $_POST['user'];
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$email = $_POST['email'];
$email_check = $_POST['email_check'];
//Database config- probably should store in a separate file
$database_host = "";
$database_name = "";
$database_user = "";
$database_password = "";
$conn = new PDO("mysql:host=$database_host;dbname=$database_name",$database_user,$database_password);
//Find out if the username is taken.
$sql = "SELECT count(*) FROM `registration` WHERE user = :user";
$q = $conn->prepare($sql);
$q->execute(array(':user' => $user));
$number_of_rows = $q->fetchColumn();
//Clear $sql and $q so you can use them again
$sql = NULL;
$q = NULL;
if ($number_of_rows > 1) {
//Username already taken
echo "Username already taken";
}
else {
$sql = "INSERT INTO registration (user,password,email) VALUES (:user,:password,:email)";
$q = $conn->prepare($sql);
$q->execute(array(':user'=>$user, ':password'=>$password, ':email'=>$email));
echo "The account " . $user . " was successfully created";
}
?>
You really, really need to read about prepared statements. The method you are using is very old, incredibly insecure, and generally a bad-practice by today's standards.
Your code isn't even worth fixing for these reasons, it should be re-written using prepared statements.