Making MySQL queries safe for database insertion (strings) [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Practises for getting information from $_GET/$_POST and saving it to a database?
Just wondering what exactly I should look out for with regards to safety in MySQL database insertions for users entering strings.
Currently all I'm doing is mysql_real_escape_string($string) for every $_GET or $_POST input I wish to put in the database. Is that cool? What else do I need to do?

$stmt = mysqli_prepare($con,"INSERT INTO friend_request (ToUID, FromUID) VALUES (?,?)");
mysqli_stmt_bind_param($stmt, "ii", $fid, $uid); //i-> Integer, S -> string
mysqli_stmt_execute($stmt);
if (mysqli_stmt_affected_rows($stmt))
echo 'Request Sent';
else
echo 'Something went wrong !';

This is my process:
//check to see if the request came from your server or not
$server = substr($_SERVER[HTTP_REFERER],0,LENGTH OF INCOMING PAGE);
$prevPage = ""; //the incoming page
if ($server != $prevPage) {
header("Location: $prevPage");
exit;
} else {
//pull and sanitize the data
include('link.php'); //include the link to your database
$var = $link->mysql_real_escape_string($_POST['data']);
//check for null values in required fields
//run the data through a regular expression check
//then store the information
There is so much more you could do to validate the data being entered.

Related

Why is my prepared statement on my login page not working? [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 2 years ago.
I have created a login page however I'm having a hard time authenticating the user. I am able to establish a connection however my sanitation is not working. I'm not sure if its the select statement or HTML related. I've played around with different SELECT statements and troubleshooted the code further up but that doesn't seem to be the problem.
<?php
// Now I check if the data from the login form was submitted, isset() will check if the data exists.
if (!isset($_POST['username'], $_POST['user_password'])) {
echo 'error2';
// Could not get the data that should have been sent.
exit('Please fill both the username and password fields!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare("SELECT id, username, user_password FROM user_info WHERE username = ?")) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $user_password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if (password_verify($_POST['user_password'], $user_password)) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = true;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
} else {
echo 'error3';
}
You're selecting 3 columns in SELECT id, username, user_password but you're only binding two variables in $stmt->bind_result($id, $user_password);. This mismatch will cause an error.
There's no need to select username since that's the column you're matching in the WHERE clause. Change the select list to SELECT id, user_password to match the variables you're binding.

ForgotPassword PHP and Mysql [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 5 years ago.
I am writing a login form with PHP and Mysql.
I did everything its just the forgot password that is not working.
It sends me email confirmation but it does not update the password in the database.
First is the forgot page, then sends an email and redirect me to the confirm_pass.html page where is the form for the two passwords and on this page executes the confirm_pass.php where is doing everything, except updating the password in the database.
Please help.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Make sure the two passwords match
if ( $_POST['newpassword'] == $_POST['confirmpass'] ) {
$new_password = password_hash($_POST['newpassword'], PASSWORD_BCRYPT);
$email = $mysqli->escape_string($_POST['email']);
$confirm_code = md5(rand().$password);
$result = "UPDATE `mv_db`.`users` SET `password`='$new_password', `confirm`='$confirm_code' WHERE `email`='$email'";
if ( $mysqli->query($result) ) {
header("location: login.html");
}
}
else {
$_SESSION['message'] = " The two passwords you entered don't match, try again!";
header("location: error.php");
}
}
?>
Your $_POST['email'] is not defined, because there is no "email" field in your HTML form.
So nothing is updated in database, because there is no matching record.

PHP exception handling after SQL insert [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 2 years ago.
I am creating a very simple registration form in php, currently when the user tries to register there will popup a javascript alert with a succes or fail message.
Now I want to catch the sql exception to show if the username or email already excists in the database instead of a standard fail message.
This is the code I have so far:
if(isset($_POST['btn-signup']))
{
$uname = mysql_real_escape_string($_POST['uname']);
$email = mysql_real_escape_string($_POST['email']);
$upass = md5(mysql_real_escape_string($_POST['pass']));
if(mysql_query("INSERT INTO user(username,password,email) VALUES('$uname','$upass','$email')"))
{
?>
<script>alert('successfully registered ');</script>
<?php
}
else{
?>
<script>alert('error while registering you...');</script>
<?php
}
}
?>
How can I check if the email or username already excists in the database? Both variable's are already unique in the database.
From Comments:
I don't want 2 queries while the database can return an exception for me. If there are about 10 million records in that table, I don't want to check them all before inserting a new one.
Ok, so you have one query to insert and check is unique? So you have to INSERT on a UNIQUE_INDEX MySQL column, you can catch these sort of exceptions with the following style of answer shameless stolen from this answer to this question:
In the case of this answer we'll assume you're using PDO, because you should. Please read up about it.
// Pre-setup the database connection somewhere, usually an include (or a class)
$link = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbusername,$dbpassword);
// PDO needs to be set in Exception mode:
$link->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Input Processing functions.
// (entirely optional)
$uname = MyCleanerFunction($_POST['uname']);
$email = MyCleanerFunction($_POST['email']);
//please see note below re:MD5
//$upass = md5($_POST['pass']);
$options['cost'] = 12;
$upass = password_hash($_POST['pass'],PASSWORD_BCRYPT,$options);
//now reach the code part:
try {
//PDO query execution goes here:
$statement = $link->prepare("INSERT INTO user(username,password,email) VALUES(:uname, :email, :pass)"));
$statement->bindValue(":uname", $uname);
$statement->bindValue(":email", $email);
$statement->bindValue(":pass", $upass);
$statement->execute();
//reaching here everything is ok!
}
catch (\PDOException $e) {
if ($e->errorInfo[1] == 1062) {
// The INSERT query failed due to a key constraint violation.
// THIS means that it failed because the Primary Key
// (the email) appears already in the database table.
}
if($e->errorInfo[1] == 9999){
// possible other IF clauses for other errors in INSERT.
}
}
You would also do well to read up about catching and outputting PDO errors. As well as all about MySQL Unique Key Constraints.
Also very useful alternative viewpoint that you Should not catch PDO exceptions.
Also please note that MD5 is an extremely weak hash for storing passwords and that PHP password_hash function is the much preferred way of doing it.
PLEASE use Prepared Statements for your MySQL interactions, the layout above is a rough guide to how they look and is very similar for MySQLi and PDO. Prepared Statements go a long way towards securing your data from malicious user input.
$con=mysqli_connect("localhost","root","","my_db");
$check="SELECT COUNT(*) FROM persons WHERE Email = '$_POST[eMailTxt]'";
if (mysqli_query($con,$check)>=1)
{
echo "User Already in Exists<br/>";
}
else
{
$newUser="INSERT INTO persons(Email,FirstName,LastName,PassWord) values('$_POST[eMailTxt]','$_POST[NameTxt]','$_POST[LnameTxt]','$_POST[passWordTxt]')";
if (mysqli_query($con,$newUser))
{
echo "You are now registered<br/>";
}
else
{
echo "Error adding user in database<br/>";
}
}

How TO Avoid '=' 'or' [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
i make PHP site
With USER / Pass Login
But USer can Skip This Page BY Use
'=' 'or'
‘ or 1=1
Like this
Code Here In File Login_Check.php
`
include("includeszzz/host_conf.php");
include("includeszzz/mysql.lib.php");
$obj=new connect;
$obj1=new connect;
$username=$_GET["username"];
$password=$_GET["password"];
//echo $username;
//echo $password;
$sql="select username from admin where username='$username'";
$obj->query($sql);
$U_num=$obj->num_rows();
//echo $U_num;
if($U_num!=0) {
$sql1="select password from admin where username='$username' and password='$password'";
$obj1->query($sql1);
$P_num=$obj1->num_rows();
if($P_num!=0) {
session_start();
$_SESSION["zizo"]="$username";
//header("location: welcome.php");
echo "1";
} else {
echo "Invalid Password Please Try Again";
}
} else {
echo "Invalid Username Please Try Again";
}
`
You want to avoid using user data in queries without any type of sanitation.
http://php.net/manual/en/security.database.sql-injection.php
"Example #5 A more secure way to compose a query..."
<?php
settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
// please note %d in the format string, using %s would be meaningless
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset);
?>
If the database layer doesn't support binding variables then quote
each non numeric user supplied value that is passed to the database
with the database-specific string escape function (e.g.
mysql_real_escape_string(), sqlite_escape_string(), etc.). Generic
functions like addslashes() are useful only in a very specific
environment (e.g. MySQL in a single-byte character set with disabled
NO_BACKSLASH_ESCAPES) so it is better to avoid them.
Do not print out any database specific information, especially about
the schema, by fair means or foul. See also Error Reporting and Error
Handling and Logging Functions.
You may use stored procedures and previously defined cursors to
abstract data access so that users do not directly access tables or
views, but this solution has another impacts.
Additionally, you can make use of Binding Parameters:
http://php.net/manual/en/pdo.prepared-statements.php
<?php
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':value', $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
// insert another row with different values
$name = 'two';
$value = 2;
$stmt->execute();
?>

Issue with mysql data storage into database [duplicate]

This question already has an answer here:
Issue with uploading data into database
(1 answer)
Closed 8 years ago.
After successfully sending data to my database upon reloading the page it resubmit automatically again. Does anyone know why?
After successfully submitting data the first time, it clears the values inside the text field, but if i reload the page it automatically sends the previously filled data again into database.
To avoid it i have tried !empty condition. I have also tried unset $_POST.
My code looks like this:
if (isset($_POST['Posts'])) {
if (isset($_POST['t']) && isset($_POST['i']) && isset($_POST['P'])) {
$title = $_POST['t'];
$idea = $_POST['i'];
if (!empty($title) && !empty($idea)) {
$query = "INSERT INTO `updates` VALUES ('".mysql_real_escape_string($title)."')";
if ($query_run = mysql_query($query)) { }
else {
echo 'Sorry ,we could\'t register you at this time.Try again later';
}
}
}
}
try to add header at the end, example:
if (isset($_POST['Posts'])) {
//do something
//..do all post stuff
header('Location: thisPage.php'); //clears POST
}
After running the insert, redirect to a new page. Or you could even run a select to check if the data was just submitted, though you might want to put a time frame such as has it been inserted in the past 5 minutes or so. If it has not been inserted, then do the insert. If it was already inserted, either display the success message or a "this data has already been submitted" type answer.

Categories