Database input sanitisation with PHP forms - php

I sanitise the data I receive from the form in the following way:
$gender = filter_var($_POST['gender'], FILTER_SANITIZE_STRING);
$firstName = filter_var($_POST['firstName'], FILTER_SANITIZE_STRING);
$lastName = filter_var($_POST['lastName'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
$address = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
$numBrochures = (int) filter_var($_POST['quantity'], FILTER_SANITIZE_NUMBER_INT);
The relevant SQL queries that insert the data are as follows:
if (mysqli_query($conn, "INSERT INTO users(firstName, lastName, email, gender) VALUES('$firstName', '$lastName', '$email', '$gender')") == TRUE) {
logSuccess($file, "Adding user");
}
else {
logError($file, "Adding user", mysqli_error($conn));
}
$userId = $conn->query("SELECT `userId` FROM users WHERE `firstName` = '$firstName' AND `lastName` = '$lastName' AND `email` = '$email'")->fetch_object()->userId;
if ($userId == false) {
logError($file, "Fetching user id", mysqli_error($conn));
}
if (mysqli_query($conn, "INSERT INTO brochureOrders(userId, address, numBrochures, message) VALUES('$userId', '$address', '$numBrochures', '$message')") == TRUE) {
logSuccess($file, "Brochure Order");
$sendConfirmationEmail = true;
}
else {
logError($file, "Brochure Order", mysqli_error($conn));
}
However, in my database, I see entries like the following:
address = "vz8y8E gghwptvvzuak, [url=http://ytvsmximkjnp.com/]ytvsmximkjnp[/url], [link=http://hiabgyvsjifp.com/]hiabgyvsjifp[/link], http://tyvylndqitoy.com/"
Shouldn't the following have taken care of this?
$address = filter_var($_POST['address'], FILTER_SANITIZE_STRING);
Could someone tell me what I am doing incorrectly here?

Because the OP stated in the comments he wants to switch to prepared statement, I thought I'd show him an example.
Instead of something like this:
if (mysqli_query($conn, "INSERT INTO users(firstName, lastName, email, gender) VALUES('$firstName', '$lastName', '$email', '$gender')") == TRUE) {
logSuccess($file, "Adding user");
}
else {
logError($file, "Adding user", mysqli_error($conn));
}
Do something like this:
$query = "INSERT INTO users (firstName, lastName, email, gender) VALUES(?, ?, ?, ?)";
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('ssss', $firstName, $lastName, $email, $gender);
$stmt->exeucte();
$stmt->close();
}else die("Failed to prepare!");
and this
$query = "SELECT `userId` FROM users WHERE `firstName` = ? AND `lastName` = ? AND `email` = ?";
if($stmt = $mysqli->prepare($query)){
$stmt->bind_param('sss', $firstName, $lastName, $email);
$stmt->execute();
$stmt->bind_result($userId);
$stmt->fetch();
$stmt->close()
}else die("Failed to prepare!");

Related

Data not save to the database

I want to save form data to database. I get a success message in the url. But the data get not saved to the database. mysqli_stmt_execute($stmt); seems to get not executed. Can anyone explain me the below code error?
if (isset($_POST['register-submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$type = $_POST['utype'];
$sql = "INSERT INTO `users`(`idroles`, `user_email`, `first_name`, `last_name`, `password`) VALUES((SELECT `idroles` FROM `roles` WHERE `name`= $type), ?, ?, ?, ?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location../View/login_register.php");
exit();
} else if (mysqli_stmt_prepare($stmt, $sql)) {
$hashpwd = password_hash($password, PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt, "ssss", $firstname, $lastname, $email, $hashpwd);
mysqli_stmt_execute($stmt);
header("Location:../View/login_register.php?success");
exit();
}
}
You can check if mysqli_stmt_execute succeded by doing so:
if(mysqli_stmt_execute($stmt)) {
header("Location:../View/login_register.php?success");
exit();
} else {
echo mysqli_error($conn);
exit();
}

Multi - Query in Android

I want to populate the records everytime the customer click the submit button on signup page, and I dont know how to. Here are the codes;
<?php
$con = //credentials
$mobilenumber = $_POST['mobilenumber'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$pincode = $_POST['pincode'];
$emailaddress = $_POST['emailaddress'];
$birthday = $_POST['birthday'];
$sql = mysqli_prepare($con, "INSERT INTO customer (firstname, lastname, mobilenumber, pincode, emailaddress, birthday) VALUES (?, ?, ?, ?, ?, ?) ");
mysqli_stmt_bind_param($sql, "ssiiss", $firstname, $lastname, $mobilenumber, $pincode, $emailaddress, $birthday);
mysqli_stmt_execute($sql);
$response = array();
$response["Success"] = true;
json_encode($response);
$sql2 = mysqli_prepare($dbconn, "SELECT custnum, mobilenumber, emailaddress FROM customer");
while($data = mysqli_stmt_fecth($sql2)){
$mobilenum = $data['mobilenumber'];
$email = $data['emailaddress'];
$custnum = $data['custnum'];
$exp = date('Y-m-d', strtotime('+1 year'));
}
$sql3 = mysqli_prepare($con, "INSERT INTO accounts(userID, type, useraccounts, emailaddress, datecreated, accountexpiry, lastlogin) VALUES (?, ?, ?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($sql3, "ssssddd", $custnum,'Customer',$mobilenum, $email, curdate(), $exp, curdate() );
mysqli_stmt_execute($sql3);
?>

ERROR WHILE INSERTING USING MYSQLI

i'm new to this PHP please help me here i'm unable to insert values into table.
But if i gave values directly to insert command in place of variables it works.
<?php
include ("db.php");
$msg = "";
if(isset($_POST["submit"]))
{
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$name = mysqli_real_escape_string($db, $name);
$email = mysqli_real_escape_string($db, $email);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);
$sql="SELECT email FROM users2 WHERE email='$email'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if(mysqli_num_rows($result) == 1)
{
$msg = "Sorry...This email already exist...";
}
else
{
$query = mysqli_query($db, "INSERT INTO users2 (name, email, password)VALUES ('$name', '$email', '$password')");
if($query)
{
$msg = "Thank You! you are now registered.";
}
}
}
?>
$sql = "INSERT INTO users2 (name, email, password) VALUES (?,?,?)";
if (!$stmt = $db->prepare($sql)) {
die($db->error);
}
$stmt->bind_param("sss", $name, $email, $password);
if (!$stmt->execute()) {
die($stmt->error);
}
I don't know what is the problem in my above question but
i used the above query instead of the one i used the in question and Boom it is a success.
if any one of you know whats the problem in the question please let me know.
You have to concat the variable in string of insert not just put as variable
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('".$name."', '".$email."', '".$password."')")
or
$query = mysqli_query($db,"INSERT INTO users2 (name, email, password)VALUES ('{$name}', '{$email}', '{$password}')")
You should use prepare statement for this mysql_real_escape_string-versus-Prepared-Statements
Never use md5() is-md5-considered-insecure
Prefer password_hash() or password_verify() Manuel
``

Quick PHP Variable guidance

I'm a newbie with PHP. I am trying to create a log in /register system for a project, so I am using a login system source code I found which has many functions and features like salted passwords. The system itself works fine, but I am trying to add more fields to my MySQL Table. The system had an array for extra columns, but I think it was resulting in bad mysql syntax so I decided to write out the query myself using the variables, but I am not sure how I can give access to the variables to the function. The variables are in the register.php document, here is the code (all of register.php):
if( isset($_POST['submit']) ){
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$user = $_POST['username'];
$sex = $_POST['sex'];
$country = $_POST['strCountryChoice'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$birthdate = $_POST['birthdate'];
$created = date("Y-m-d H:i:s");
//need to add a lot more validation functions.. AKA Check if email exists and username. Password > 5 chars
if( $user=="" || $email=="" || $pass=='' || $pass2=='' || $firstname=='' || $lastname='' || $sex='' || $country='' || $birthdate='' ){
echo "Fields Left Blank","Some Fields were left blank. Please fill up all fields.";
exit;
}
if( !$LS->validEmail($email) ){
echo "E-Mail Is Not Valid", "The E-Mail you gave is not valid";
exit;
}
if( !ctype_alnum($user) ){
echo "Invalid Username", "The Username is not valid. Only ALPHANUMERIC characters are allowed and shouldn't exceed 10 characters.";
exit;
}
if($pass != $pass2){
echo "Passwords Don't Match","The Passwords you entered didn't match";
exit;
}
$createAccount = $LS->register($user, $pass,
array(
"email" => $email,
"name" => $firstname,
"lastname" => $lastname,
"gender" => $sex,
"country" => $country,
"DOB" => $birthdate,
"created" => date("Y-m-d H:i:s") // Just for testing
)
);
if($createAccount === "exists"){
echo "User Exists.";
}elseif($createAccount === true){
echo "Success. Created account.";
}
}
The whole system takes place in another file which has the class. Here is the register function:
public function register( $id, $password, $other = array() ){
if( $this->userExists($id) && (isset($other['email']) && $this->userExists($other['email'])) ){
return "exists";
}else{
$randomSalt = $this->rand_string(20);
$saltedPass = hash('sha256', "{$password}{$this->passwordSalt}{$randomSalt}");
if( count($other) == 0 ){
/* If there is no other fields mentioned, make the default query */
//old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
//new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)");
$sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`) VALUES(:username, :password, :passwordSalt)");
}else{
/* if there are other fields to add value to, make the query and bind values according to it */
//old query: ("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
//new query: ("INSERT INTO `{$this->dbtable}` (`username`, 'email' , `password`, `password_salt` , 'name' , 'lastname' , 'gender' , 'country' , 'DOB') VALUES(:username, :email, :pass, :passwordSalt, :firstname, :lastname, :gender, :country, :DOB)");
$keys = array_keys($other);
$columns = implode(",", $keys);
$colVals = implode(",:", $keys);
//l= $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (`username`, `password`, `password_salt`, $columns) VALUES(:username, :password, :passwordSalt, :$colVals)");
//INSERT INTO MyGuests (firstname, lastname, email)cLUES ('John', 'Doe', 'john#example.com')
$sql = $this->dbh->prepare("INSERT INTO `{$this->dbtable}` (username,email,password,password_salt,name,lastname,created,gender,country,DOB) VALUES ('$username','$email','$pass','$saltedPass','$firstname','$lastname','$created','$gender','$country','$birthdate')");
print($sql);
foreach($other as $key => $value){
$value = htmlspecialchars($value);
$sql->bindValue(":$key", $value);
}
}
/* Bind the default values */
$sql->bindValue(":username", $id);
$sql->bindValue(":password", $saltedPass);
$sql->bindValue(":passwordSalt", $randomSalt);
$sql->execute();
return true;
}
}
So I need to use the variables from register.php in the class file. Can I just include it at the top or do I need to do something specific to the function?
Thanks. I'm focusing on the $sql line after else.
Yes you can include/require register.php file in the class file to use all the variables.
On another note i would like to mention that you should always filter out the POST data before adding it to the query for security concerns.

Fatal error: Call to a member function execute() on a non-objec [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am new to PDO and keep getting a Fatal error. I am trying to first check for empty fields, then check for duplicate emails and then if that passes insert the user data into the database. After searching and searching I am absolutely lost as to where I am going wrong. Here is my code:
<?php
session_start();
require_once('includes/db_connect.php');
include('functions/email-inject-function.php');
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$email = trim($_POST['email']);
$company = trim($_POST['company']);
$phone = trim($_POST['phone']);
$password = trim($_POST['password']);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if(empty($_POST["first_name"])) {
$first_name_err = "<p>What is your first name?</p>";
$errorflag = 1;
}
if(empty($_POST["last_name"])) {
$last_name_err = "<p>What is your last name?</p>";
$errorflag = 1;
}
//checks email
if(empty($_POST["email"])) {
$email_err = "<p>What is your email address?</p>";
$errorflag = 1;
}
if(empty($_POST["company"])) {
$company_err = "<p>What is your company name?</p>";
$errorflag = 1;
}
if(empty($_POST["phone"])) {
$phone_err = "<p>What is your phone number?</p>";
$errorflag = 1;
}
if(empty($_POST["password"])) {
$pass_err = "<p>Please enter a password</p>";
$errorflag = 1;
}
else {
$injected = IsInjected($email);
if ($injected == true) {
$email_valid_err = "<p>Please enter a valid email.</p>";
$errorflag = 1;
}
}
try {
// Check if email is taken
$stmt = $dbh->prepare("SELECT * FROM `admins` WHERE `email` = :email");
$stmt->execute(array('email' => $email));
if ($stmt->fetchColumn() > 0) {
throw new Exception("That email is already taken.");
}
$sql="INSERT INTO admins (first_name, last_name, email, company, phone, password, reg_date) VALUES (:first_name, :last_name, :email, :company, :phone, SHA1('$password'), NOW())";
$query = $dbh->prepare($sql);
$result->execute(array(':first_name'=>$first_name, ':last_name'=>$last_name, ':email'=>$email, ':company'=>$company, ':phone'=>$phone, ':password'=>$password ));
echo $result;
//catch any errors from try()
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
?>
Its a simple mistake:
replace $result with $query....
So:
$result->execute(array(':first_name'=>$first_name, ':last_name'=>$last_name, ':email'=>$email, ':company'=>$company, ':phone'=>$phone, ':password'=>$password ));
echo $result;
should be:
$query->execute(array(':first_name'=>$first_name, ':last_name'=>$last_name, ':email'=>$email, ':company'=>$company, ':phone'=>$phone, ':password'=>$password ));
echo $query;
the Query is also wrong:
$sql="INSERT INTO admins (first_name, last_name, email, company, phone, password, reg_date) VALUES (:first_name, :last_name, :email, :company, :phone, SHA1('$password'), NOW())";
should be
$sql="INSERT INTO admins (first_name, last_name, email, company, phone, password, reg_date) VALUES (:first_name, :last_name, :email, :company, :phone, SHA1(:password), NOW())";
Note the $password to :password

Categories