Invalid sql statment - php

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

Related

PHP script is saying "invalid password" when I know it's correct

I'm building an intentionally flawed application for presentation purposes for work. It's left vulnerable to demonstrate improper practices and possibly encourage those who would exploit it to do so. There is ample logging on the server so we're able to see when people poke around. I just need a simple login page that uses a PHP script to connect to the SQL database. I can verify connectivity through the SQL server logs, however, the script returns and says "invalid password" when I know the password and username I'm inputting are correct.
I have tried swapping bits of code from other resources / what I know and I get internal error 500
// POST variables
$user=$_POST['user'];
$pass=$_POST['pass'];
// MD5 hash
//$pass=md5($pass);
$sql = "SELECT * FROM login WHERE user = '$user' AND pass = '$pass'";
// Query Login
$stmt = sqlsrv_query($conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Login validation
if(sqlsrv_has_rows($stmt)) {
header('Location: landing.html');
}
else {
echo "Wrong username or password!";
}
I expect the connection to work, instead, it just throws up my "Wrong username or password!" statement
The way that your scripts is written is incorrect. To check for a correct username and password, I wouldn't check if there are rows. I understand this isn't real and it's meant to show bad scripting/coding/etc however, this is really bad. The reason why it keeps giving you "Wrong username or password!" is because there are no rows being returned. Try rewriting your script like this:
<?php
// Connect to Database Server
$server = "serverName\sqlexpress";
$connectionInfo = array("Database" => "dbName", "UID" => "username", "PWD" => "password");
$conn = sqlsrv_connect($server, $connectionInfo);
// POST variables
$user = $_POST['user'];
$pass = $_POST['pass'];
$query = 'SELECT * FROM login WHERE `user` = "' . $user . '" AND `pass` = "' . $pass . '"';
// Query Login
$statement = sqlsrv_query($conn, $query);
if ($statement) {
$rows = sqlsrv_has_rows($statement);
if ($rows === true && $rows >= 1) {
header('Location: landing.html');
} else {
echo "Wrong username or password!";
}
} else {
die(print_r(sqlsrv_errors(), true));
}

"Cant process the request", dealing with basic parameterized queries

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.

Password not right but still right?

I'm busy with creating a login for on my website, I'm stuck with this problem:
Logging in with the right or wrong password still delivers me a succesfull login...
$sql = "SELECT *
FROM `players`
WHERE `username` = '" . $_POST['username']
. "' AND `password` = '" . sha1($_POST['password'])
. "' LIMIT 1";
$result = $mysqli->query($sql);
$get = $result->fetch_object();
if (empty($_POST['username']) || empty($_POST['password'])) {
$message = "You can't leave something blank...";
}
if (!$result) {
$message = "Nope, not that one...";
}
As previously stated in comments, your script is highly prone to sql injection which is extremely dangerous ESPECIALLY when handling passwords.
Please read: Prepared statements and stored procedures
I will provide you working code that I use for my registrations and logins. I hope this helps you in what you are looking for. A couple things to note is that I use AJAX/JSON to pass some data back and forth between my front and back ends which I will comment my code below as to not confuse you.
<?php
// starts the session
session_start();
// call on db connection file to execute queries below
require 'dbconfig.php';
// register logic
if(isset($_POST['newusername']) && isset($_POST['newpassword'])) {
$query = $conn->prepare("SELECT username FROM users WHERE username = :username");
$query->bindValue(':username', $_POST['newusername']);
$query->execute();
$check = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
// check if the username exists, if not then create the new user, else, send to front end and notify the user
if($check['username'] === $_POST['newusername']) {
header('Content-Type: application/json');
echo json_encode($check);
} else {
$query = $conn->prepare("INSERT INTO users (username, password) VALUES (:newuser, :newpassword)");
$query->bindValue(':newuser', $_POST['newusername']);
$query->bindValue(':newpassword', password_hash($_POST['newpassword'], PASSWORD_BCRYPT)); // using the prepared statements to prevent injection and optimizing PASSWORD_BCRYPT for passwords
if($query->execute()) {
// log to my log db
$registerLog = "New user was registered: " . $_POST['newusername'];
$query = $conn->prepare("INSERT INTO logs (website, entry) VALUES ('contacts', :entry)");
$query->bindValue(':entry', $registerLog);
$query->execute();
}
$query->closeCursor();
}
}
// login logic
if(isset($_POST['username']) && isset($_POST['password'])) {
$query = $conn->prepare("SELECT userid, username, password, pwreset, userlvl FROM users WHERE username = :username");
$query->bindValue(':username', $_POST['username']);
$query->execute();
$auth = $query->fetch(PDO::FETCH_ASSOC);
$query->closeCursor();
// check for username and verify the password
if(count($auth > 0) && password_verify($_POST['password'], $auth['password'])) {
// if successful, initiate $_SESSION variables
$_SESSION['userid'] = $auth['userid'];
$_SESSION['userlvl'] = $auth['userlvl'];
$_SESSION['username'] = $auth['username'];
$loginLog = "User: " . $_POST['username'] . " logged in.";
$query = $conn->prepare("INSERT INTO logs (website, entry) VALUES ('contacts', :entry)");
$query->bindValue(':entry', $loginLog);
$query->execute();
$query->closeCursor();
$redirect = true;
header('Content-Type: application/json');
echo json_encode($redirect);
exit;
} else {
// if username and/or password do not match or don't exist, destroy the session.
session_unset();
session_destroy();
exit;
}
}
?>
You have to unset and destroy the session if a login attempt fails or else it will just let you in every time because the script just sees that you have set the session and beyond that, it doesn't care if it really failed, it will let the user in.
I hope this provides you with an answer you need.

PHP login code error with mysql_query()

I've been following a login system tutorial. You can find it here. There are 2 parts of coding C# and PHP. The C# part is working fine but my PHP part returning error. Here is my PHP code:
<?php
$servername = getenv('IP');
$username = getenv('C9_USER');
$passwordp = "";
$database = "game_database";
$dbport = 3306;
// Create connection
mysql_connect($servername, $username, $passwordp, $dbport)or die("Cant Connect to server");
mysql_select_db($database) or die("Cant connect to database");
// Check connection
$Email = $_REQUEST["Email"];
$Password= $_REQUEST["Password"];
if (!$Email || !$Password){
echo"Email or password must be used";
}
else{
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
$result_id = #mysql_query($SQL) or die("Database Error");
$Total = mysql_num_rows($result_id);
if ($Total){
$datas = #mysql_fetch_array($result_id);
if (strcmp($Password, $datas["Password"])){
$sql2 = "SELECT Characters FROM users WHERE Email = '" . $Email ."'";
$result_id2 = #mysql_query($sql2) or die("Database Error!!!");
while ($row = mysql_fetch_array($result_id2)){
echo $row ["Characters"];
echo ":";
echo "Success";
}
}
else{
echo "WrongPassword";
}
}else {
echo "NameDoesNotExist";
}
}
?>
It seems the error comes from $result_id but I'm not sure?
You are true, the error is from $result_id, because your SQL statement has problem and there are extra stuff to fix.
You have put users table in two single quotes, it is wrong.
Your code is:
$SQL = "SELECT * FROM 'users' WHERE Email = '" . $Email ."'";
It should be with out quotes:
$SQL = "SELECT * FROM users WHERE Email = '" . $Email ."'";
You have wrote:
if ($Total){
It should check how many users record found, typically it should find only 1 record and return 1, therefore change it to:
if ($Total == 1){
Note1:
But when this is said, it does not mean the code is perfect, you should further develop your code to fulfill nowadays requirement. I would suggest you think of password hashing, use mysqli or PDO in sted of mysql and input sensitization. I would suggest you look at this link it describes some of the things I mentioned.
Note2:
I was able to write you a total solution with mysqli/PDO etc, but I wanted only to point the errors I have catch so far in your code so you can learn from your mistakes and develop your self.
And in general read about security principles, check this page.
Link1: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Link2: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
This is another simple way where you can create user log in, it is
more secure than the one you have at the moment. And you should
protect your code from sql injections.
<?php
if (isset($_POST['email'], $_POST['password']) === true )
{
require 'connection.php';
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$sql = "SELECT * FROM users WHERE email= '$email'";
$result = mysqli_query($connection,$sql);
if (mysqli_num_rows($result))
{
if( $email == $row['email'] && $password == $row['password'])
{ //use session to check if user is logged in
if (!isset($_SESSION['loggedin']))
{
//you can set session of user's log in details
//you can redirect to user profile
}
else
//already log in, redirect to user profile
}
else
echo "Incorrect Email or Password.";
}
else
echo "Incorrect Username or Password.";
mysqli_close($connection);
}
else
{
echo "Oops, something went wrong!";
?>

registration form not not showing validation error

I am having issues getting the error to appear when a user is entering a user name that is already taken.
In the code below the database is updated when successful entry is made. However, when an entry is made with a duplicate user name, the entry is placed in the database and no error message is shown. I have looked on the net and tried a few methods and this what I have so far. Thank you for taking a look :)
<?php
// Create connection
$con = mysqli_connect('172.16.254.111', "user", "password", "database"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} //sql syntax below, first line is collumn titles on the db and second line is values from the html document
//$_post is a form of sending information in php
{
$username = strip_tags($_POST['username']);
$password = md5(strip_tags($_POST['pass']));
$password2 = md5(strip_tags($_POST['pass2']));
$fullname = strip_tags($_POST['fullname']);
$email = strip_tags($_POST['email']);
$department = strip_tags($_POST['department']);
if ($password != $password2) //password doestn equal same as password 2 then the message below is displayed (working)
{
echo "<H2>password doesn't match</H2>";
}
$usercheck = "SELECT * FROM Users WHERE username=$username";
$usercheck2 = mysql_query($usercheck);
if (mysql_fetch_assoc($usercheck2)) {
echo "<H2>This username already exists, please pick another</H2>";
} else {
$sql = "INSERT INTO Users(username, password, password2, email, fullname, department)
VALUES('$username','$password','$password2','$email','$fullname','$department')";
if (!mysqli_query($con, $sql)) {
die('Error: ' . mysqli_error($con));
}
echo "<H2>Registration was successful, please use the access console above</H2>";
}
}
?>
Excuse any comments in the code; I am a beginner at PHP and coding in general.
You're missing some quotes. Try this:
$usercheck = "SELECT * FROM Users WHERE username = '$username'";
// ----------------------------------was missing---^---------^
$usercheck2 = mysql_query($usercheck);
if (mysql_num_rows($usercheck2)) {
echo 'user exists';
}
Also, you shouldn't be using the mysql_* functions. Look into using PDO
Change $usercheck = "SELECT * FROM Users WHERE username=$username";
for this $usercheck = "SELECT * FROM Users WHERE username='$username'"; And tell me if it works.

Categories