<html>
<head>
</head>
<body>
<form action="login_process.php" method="post">
SID: <input type="text" name="sid">
<br />
Password: <input type="text" name="pw">
<br />
<input type="submit" value="Login">
</form>
</body>
</html>
login_process.php FILE
<html>
<head>
</head>
<body>
<?php
include ("connection.php");
$sid = $_POST['sid'];
$pw = $_POST['pw'];
setcookie("username", "$sid". time()+86400);
$result = mysqli_query($con, "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'") or die('Query failed');
if(!$result){
echo "Failed";
} else {
echo "success". $_COOKIE['username'];
$_SESSION['username'] = $sid;
}
?>
</body>
</html>
I have data in my student_table. But no matter what input i give it says success. even if i click login button without any input it still says success. please help.
You should use quotes when you assign values in sql queries .
SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'
Also look forward Prepared Statements to protect yourself from sql injections.You should also add the code below to fetch selected row :
while ($row = mysqli_fetch_array($result)) {
$_SESSION['username'] = $row['SID'];
}
Start learning basic debugging:
When a query fails bad, just do this:
Instead of running it (mysql_query, or mysqli_query or whatever you have), ECHO it:
echo "SELECT SID FROM student_table WHERE SID='$sid' and password='$pw'";
After you submit the form, you will be shown the query that runs, go to phpmyadmin or whatever you use and run the query manually. See if there are errors and also see easier what's going on. Advisable when you do work like this, FIRST try the queries in phpmyadmin then apply them in the code, after you are confident they are ok.
This is not really an answer but more about how to find out what is going wrong when you code does not work as you expect.
First, always put you SQL into a variable by itself. Why, so you can 'var_dump' it and see what is happening. So, try this:
$sql = "SELECT SID FROM student_table WHERE SID=$sid and password=$pw";
var_dump($sql, 'my_query'); // you will see what PHP created.
then try the answer provided:
$sql = "SELECT
SID
FROM
student_table
WHERE
SID = '$sid' and password = '$pw'";
At least you will see what is likely to be incorrect.
var_dump($sql, 'the answer_query'); // you will see what PHP created.
$result = mysqli_query($con, $sql) or die('Query failed');
The outer quote marks must be " (double quote) not " ' " (single quote) both of which are perfectly valid PHP. the former allows variables to be replaced in strings.
The latter will treat eveything as a literal string.
Related
I am trying to create a simple search bar that allows the user to search using a user id to return a specific user.
I need to include SQL injection protection.
currently the page loads a blank screen but when I refresh the page I get the "No results found" response.
I have been reading a lot of posts about search bars but nothing is helping me.
here is the code:
<html>
<head>
<title></title>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="search" />
<input type="submit" value="Search" />
</form>
</body>
<?php
//search.php
include("DbConnect.php");
$search = $_POST['search'];
$safesearch = mysqli_real_escape_string($search);
$Query = "SELECT user_id
FROM users
WHERE user_id = '$safesearch'";
$Result = mysqli_query($DB,$Query);
$NumResults = mysqli_num_rows($Result);
if ($NumResults==1)
{
echo "<h1>results: ".$Result."</h1>";
}else{
echo "<h1>No Results found</h1>";
}
?>
You should have an if(isset($_POST['submit']{ } around your code so it only fires if they search and not when the page is loaded.
If you're doing any sort of insert,select or update with sql statements that will have variables within them you should use prepared statements.
Use a prepared statement it's a lot more safe than what you're doing:
<?php
//search.php
include("DbConnect.php");
$search = $_POST['search'];
$safesearch = mysql_real_escape_string($search);
$Query = "SELECT user_id
FROM users
WHERE user_id = ?";
$stmt = $connectionVariableName->prepare($query);
$stmt->bind_param("s",$safesearch);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
$num_rows = $stmt->num_rows;
$stmt->close();
if ($num_rows > 0)
{
echo "<h1>results: ".$result."</h1>";
}else{
echo "<h1>No Results found</h1>";
}
?>
http://php.net/manual/en/mysqli.prepare.php
You should also sanitize the search variable by testing it with regex to make sure it only contains the characters you allow in the userid and not / * ^ etc
You want partial phrase search, I presume.
Then your query must look like this:
$Query = "SELECT user_id
FROM users
WHERE user_id LIKE '%$safesearch%'";
Not very familiar with php, but % symbol seem not being a special character in the language (correct me if I'm wrong), if it by chance is - escape it.
To make it case insensitive -
$safesearch = strtolower($safesearch);
$Query = "SELECT user_id
FROM users
WHERE lowercase(user_id) LIKE '%$safesearch%'";
I know this might be a duplicate on:
php - MYSQLI_NUM_ROWS ALWAYS RETURNING 0
php - mysqli_num_rows() is always returning 0
The thing is none of them is giving me an answer for my problem.
This is an example code of my code with the same syntaxes as I used.
index.html
<html>
<head><title>GAS - Give Away System - Create User</title></head>
<body>
<script src="jquery.js"></script>
<input type="text" placeholder="Username" id="uname" /><br><br>
<p id="errors"></p>
<script>
$(document).ready(function(){
$.ajaxSetup({cache:false});
setInterval(function(){
$("#errors").load("php/errorchecking.php?c=username&v="+document.getElementById('uname').value);
}, 500);
});
</script>
</body>
</html>
php/errorchecking.php
<?php
$con = mysqli_connect('localhost', 'root', '', 'gas');
if(isset($_GET['c']) && isset($_GET['v'])){
echo 'Current value: ', $_GET['v'], '<br>This value is set for: ', $_GET['c'], '<br><br>';
if($_GET['c']==="username"){
if($_GET['v']===null){
echo "Sorry, this username is empty! Please write a username!";
}else{
// I know this is open for SQL Injection, it's not in my worries.
$query = "SELECT `username` FROM `users` WHERE `username` ='{$_GET['v']}'";
$sql = $con->query($query);
if(mysqli_num_rows($sql) > 0){
echo "Sorry, this username is already in use! Please choose something else";
}else{
echo "Username avaible!"; //This is line 17
}
}
}
}else{
echo 'This is an invalid form!';
}
?>
Now lets say I have a username in my table called User15, and someone's input is the exact same it will display the message "Username available!" from php/errorchecking.php Line:17
Why does it do that? Since it already is a user there called User15, so what it should display is "Sorry, this username is already in use! Please choose something else"
Thanks for taking time helping me! Cecilie.
That's a wrong way of query syntax. You need to use back-ticks and not 's:
$query = "SELECT username FROM `users` WHERE 'username'='".$_GET['v']."'";
//-------------------------------------------^--------^
Change it to:
$query = "SELECT `username` FROM `users` WHERE `username`='".$_GET['v']."'";
Note:
`` - For columns.
'' - For values.
You have to remove '(single quotes) around your column-name from your query like below:-
$query = "SELECT `username` FROM `users` WHERE `username`='".$_GET['v']."'";
Note:- Instead of '(single quotes) use back-ticks. because single-quotes(') used for values and back-ticks used for column-name as well as table-name too.Thanks
so I've got this code that supposedly sends you an email after you entered a valid one and answered a security question. My problem is the fact that the form won't submit the answer i've given it. It always echoes "submit" on the begging of the second php block. Also if u can spot any other errors i might have missed let me know please. Thanks anticipated.
<?php
define ('DB_SERVER','fenrir');
define ('DB_USERNAME','ArchivrTW');
define ('DB_PASSWORD','vPOZOa1txS');
define ('DB_DATABASE','ArchivrTW');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
if(!$connection)
{
die('Could not connect because: ' . mysql_error());
}
?>
<?php
$test = $_POST['email'];
$query = "SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test";
echo(strlen($query));
if(strlen($query) > 42)
{
$query1 = "SELECT 'SecurityQ' from 'USERS' WHERE 'EMAIL' =$test";
$query2 = "SELECT 'SecurityA' from 'USERS' WHERE 'EMAIL' =$test";
$result = mysqli_query($connection,$query);
$result1 = mysqli_query($connection,$query1);
$Results = mysqli_fetch_assoc($result);
$Results1 = mysqli_fetch_assoc($result1);
$Results2 = mysqli_fetch_assoc($result2);
echo($Results1);
}
?>
<form action="recover.php" method="post">
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
<p><input type="submit" name="answer" id="answer" /> </p>
</form>
<?php
$answer=$_POST['answer'];
echo($answer);
if (count($Results) >= 1 && strcmp($_POST['answer'],$Results2) == 0)
{
$REQ_STATUS = 1;
$new_passwd = rand(1,1000000);
$to = $email;
$subject = "Archivr-Forgot Password";
$msg = "Use this generated password to log in then change it using the Edit Profile Menu";
mail($to, $subject, $msg);
}
else
{
$message="Account not found or wrong security question answer";
}
if($REQ_STATUS == 1)
{
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
}
?>
</body>
</html>
The first block works, problem is the form or the second block.
You are vulnerable to sql injection attacks;
You have duplicate field names:
<p>Security Question Answer: <input type="text" name="answer" placeholder="Type your answer here" /> </p>
^^^^^^^^^^^^
<p><input type="submit" name="answer" id="answer" /> </p>
^^^^^^^^^^^^^
Since the field names are the same, the submit button overwrites/replaces the text field, and you end up submitting a blank value.
You're using the incorrect identifier qualifiers for all your tables and columns being single quotes and not wrapping the $test variable in quotes; it's a string.
This one for example:
SELECT 'EMAIL' FROM 'USERS' WHERE 'EMAIL'=$test
should read as
SELECT `EMAIL` FROM `USERS` WHERE `EMAIL`='$test'
where you may have seen a tutorial somewhere, that the ticks resembled regular single quotes. They are not the same; those are two different animals altogether.
You will then need to follow the same method above and do the same for the rest of your queries.
Using this for example:
$result = mysqli_query($connection,$query) or die(mysqli_error($connection));
would have signaled a syntax error.
Then this mysql_error() - That should read as mysqli_error($connection). You cannot mix MySQL APIs. They do not intermix with each other.
You also don't seem to be doing anything with:
$update_query="UPDATE USERS set PASSWORD =".$new_passwd." where EMAIL ='". $to ."'";
Whether it's relevant to the question or not, you're not actually executing that query.
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: Error reporting should only be done in staging, and never production.
References:
https://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
http://php.net/manual/en/mysqli.error.php
Footnotes:
Your present code is open to SQL injection. Use prepared statements, or PDO with prepared statements, they're much safer.
Plus, since you're using the entire code in one file, you will get warnings to the effect of "Undefined index xxx....", therefore you will need to use a conditional isset() and or !empty() around your executable code and for the POST arrays.
Passwords:
I'm hoping you're using a modern-day password hashing method, since this looks to me, being related to resetting passwords.
For password storage, use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Both your form field and your submit button have a name of "answer". Rename your submit button name to "submit" or something else.
So I am messing around with PHP and MySQL, I currently have a database with:
id | username | password
within it, I was wondering if there would be a way of checking if the username entered is the same as the password on the same row/ID (the ID is auto incrementing)
<form action="login.php" method="get">
login >
<input name="log_username" type="text" />
<input name="log_password" type="password" />
<input id="submit" type="submit" />
</form>
I know its possible, but I - myself as a rookie with SQL and PHP cannot figure out ^^'
Thanks in Advance
EDIT:
For those interested this is my current register code (works brilliantly)
<?php
$con=mysqli_connect(###########);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO users (username, password)
VALUES ('$_POST[reg_username]','$_POST[reg_password]')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
SELECT * FROM users WHERE username = :username AND password = :password
Where password is the encrypted version of the password they submitted, because you're totally going to re-write this to encrypt passwords, and use prepared statements to remove your SQL injection vulnerability.
Creating a user login system is such a common thing that there are literally thousands of tutorials you could find on this topic, I suggest you do some basic research.
if ((isset($_GET['log_username']) && $_GET['log_username'] != "") && (isset($_GET['log_password']) && $_GET['log_password'] != "")
{
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$query = "SELECT * FROM users WHERE username = " . $_GET['log_username'] . " AND password = " . $_GET['log_password'];
$result = mysql_query($query);
if (mysql_num_rows($result) < 1)
echo("No record found");
}
This is the simplest way, but I suggest you to use PDO because mysql_query is deprecated.
Although you have requested a PHP solution, in real-world terms this might be better solved with some javascript/jQuery, because presenting the error to the user will not require a page refresh. For your peace of mind, this is what it would look like:
jsFiddle Demo
HTML:
<form id="myForm" action="login.php" method="get">
login >
<input id="log_username" name="log_username" type="text" />
<input id="log_password" name="log_password" type="password" />
<input id="mySubmit" type="submit" />
</form>
jQuery:
$('#mySubmit').click(function(e) {
e.preventDefault();
var un = $('#log_username').val();
var pw = $('#log_password').val();
if ( un == pw ) {
alert('Sorry, username/password cannot be identical');
}else{
$('#myForm').submit();
}
});
Notes:
The above code uses jQuery, so you must reference the jQuery library, usually in the <head> tags, like this:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
Note the use of e.preventDefault, which means: Don't do what a submit button would normally do (in other words, don't submit). We control the submission ourselves, manually.
This is how we use javascript/jQuery to manually submit: $('#myForm').submit();
Note that ID attributes were added to all elements that I needed to reference. Although it is possible to format jQuery to reference elements with or without IDs, this makes it much easier and there is no downside to doing so (although you must follow the rule that all elements must use unique IDs)
Also note that one should not use the word submit for an ID name for a submit button. Doing so may cause problems later.
As described in the title, I am running into an SQL injection error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
How do I fix this? Provided below is my php code and html code
PHP:
if($_POST['submit']=='Change')
{
$err = array();
if(!$_POST['password1'] || !$_POST['passwordnew1'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['password1'] = mysql_real_escape_string($_POST['password1']);
$_POST['passwordnew1'] = mysql_real_escape_string($_POST['passwordnew1']);
$row = mysql_fetch_assoc(mysql_query("SELECT id,username FROM members WHERE username='{$_SESSION['username']}' AND pass='".md5($_POST['password1'])."'"));
if($row['username'])
{
$querynewpass = mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1'])."' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
else $err[]='Wrong Password To Start With!';
}
if($err)
$_SESSION['msg']['passwordchange-err'] = implode('<br />',$err);
header("Location: members.php?id=" . $_SESSION['username']);
exit;
}
HTML:
<form action="" method="post">
<?php
if($_SESSION['msg']['passwordchange-err'])
{
echo '<div class="err">'.$_SESSION['msg']['passwordchange-err'].'</div>';
unset($_SESSION['msg']['passwordchange-err']);
}
if($_SESSION['msg']['passwordchange-success'])
{
echo '<div class="success">'.$_SESSION['msg']['passwordchange-success'].'</div>';
unset($_SESSION['msg']['passwordchange-success']);
}
?>
<label class="grey" for="password1">Current Password:</label>
<input class="field" type="password" name="password1" id="password1" value="" size="23" />
<label class="grey" for="password">New Password:</label>
<input class="field" type="password" name="passwordnew1" id="passwordnew1" size="23" />
<input type="submit" name="submit" value="Change" class="bt_register" style="margin-left: 382px;" />
</form>
I have it working where a user is able to change/update their password, however, when they click the Change button on the form, they are directed to that error message I posted above, and if they click the refresh button, only then they are redirected back to their profile and the changes have been made. So my main question at hand is, how do I get this to fully work without that mysql error message? Any help would be much appreciated!
A few things wrong here, more than can be put in a comment. I'm sorry, I can't see exactly what your error is, but if you follow point #1, it'll go away.
Don't use the mysql library. It is deprecated, and has been removed (finally!) in PHP 5.5. It is only working for you at the moment, because your version of PHP is out of date. You should either be using PDO or MySQLi. Check out this article for information on PDO: http://net.tutsplus.com/tutorials/php/php-database-access-are-you-doing-it-correctly/
Don't put any variable that's not generated in the script you're looking at into your query, this includes SESSION variables. You just need one flaw in your application, and the user can inject data into the SESSION. Treat every variable as dirty. If you know that it isn't - 100% for certain - then treat it as dirty. If you use prepared statements with PDO or MySQLi, this isn't a problem.
You should reference users by their ID, not username. Much faster and safer.
Never ever ever ever store passwords raw or simply encrypted (like with plain md5()) in the database. At the very least, you can encrypt with something like: crypt($password, '$2a$07$sillystring' . sha1($password) . '$') and verify by recrpyting the password and see if it matches. That's a very basic, more secure way of doing it. There are many articles written on password salting that go more in depth and are worth checking out.
Except for what Connor said, you have a serious problem here:
if($row['username'])
{
$querynewpass =
mysql_query("UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'");
$result = mysql_query($querynewpass) or die(mysql_error());
}
The first inner line already performs the mysql_query and returns a resource, which is assigned to $querynewpass.
You're resending the result (a resource) to another query, as if it was a string containing the SQL command you want to perform.
This is the function's specification:
resource mysql_query ( string $query [, resource $link_identifier = NULL ] )
This is the correct usage of mysql_query (which is deprecated as people mentioned):
if($row['username'])
{
$querynewpass =
"UPDATE members SET pass='".md5($_POST['passwordnew1']).
"' WHERE username='{$_SESSION['username']}'";
$result = mysql_query($querynewpass) or die(mysql_error());
}
This code snippet could help to you
$pass1 = md5(mysql_real_escape_string($_POST['password1']));
$newpass = md5(mysql_real_escape_string($_POST['passwordnew1']));
$username = mysql_real_escape_string($_SESSION['username'])
$query = "SELECT id,username FROM members WHERE username = '$username' AND pass = '$pass1'";
$result = mysql_query($query); //that could also use , mysql_query($query,$yourconnection);
if(mysql_num_rows($result)>0)
{
$updatequery = "UPDATE members SET pass='$newpass' WHERE username='$username'";
$updateresult = mysql_query($updatequery) or die(mysql_error());
}
Please note that mysql library is deprecated in after php ver 5.5.0