Preventing SQL Injections [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Best way to stop SQL Injection in PHP
In PHP when submitting strings to the database should I take care of illegal characters using htmlspecialchars() or use a regular expression?
Yesterday I asked a question with regards to a script not working, whilst I in the end solved the issue myself. There was talk of SQL Injections risks.
So what I'm asking today is, with the code I have inserted below, how would one prevent SQL Injections?
So any advice of guidence. I know I can read the internet about SQL injections but there is so many conflicting articles on it, I don't know which is correct or not.
Here is the code, this is all put in a page of it's own lets say 'form-process.php' which the form then submits the data to e.g
<?
session_start();
$_SESSION['Title'] = stripslashes($_REQUEST['Title']);
$_SESSION['ShortTitle'] = stripslashes($_REQUEST['Title']);
$_SESSION['Category'] = stripslashes($_REQUEST['Category']);
$_SESSION['Story'] = stripslashes($_REQUEST['Story']);
$_SESSION['FrontPage'] = stripslashes($_REQUEST['FrontPage']);
$_SESSION['imagefilename'] = ($_FILES['image']['name']);
if (empty($_REQUEST['Title'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=0");
exit;
} elseif (empty($_REQUEST['ShortTitle'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=1");
exit;
} elseif (strlen($_REQUEST['Category']) < 1) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=2");
exit;
} elseif (empty($_REQUEST['Story'])) {
header("Location: ". $_SERVER['HTTP_REFERER'] ."?message=3");
exit;
} else {
include("settings.php");
include("dbconnect.php");
if($_POST['btnSubmit'] == 'Publish'){
$target = "../../../images/matchreports/uploaded/";
$target = $target . time() . '-' . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$image=time() . '-' . basename( $_FILES['image']['name']);
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,image,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(y) . "','$image','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Publishing 1");
header("Location: /cms/matchreports/index.php?message=4");
exit;
} else {
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Publishing 2");
header("Location: /cms/matchreports/index.php?message=5");
exit;}}
if($_POST['btnSubmit'] == 'Save draft'){
$target = "../../../images/matchreports/uploaded/";
$target = $target . time() . '-' . basename( $_FILES['image']['name']);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)){
$image=time() . '-' . basename( $_FILES['image']['name']);
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,image,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$image','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Saving Draft 1");
header("Location: /cms/matchreports/index.php?message=6");
exit;
} else {
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "INSERT INTO " . $match_reports_table . " (Title,ShortTitle,Story,FrontPage,active,date,user_ip) VALUES('" . addslashes($_REQUEST['Title']) . "','" . addslashes($_REQUEST['ShortTitle']) . "','" . addslashes($_REQUEST['Story']) . "','" . addslashes($_REQUEST['FrontPage']) . "','" . addslashes(n) . "','$newdate','" . addslashes($_SERVER['REMOTE_ADDR']) . "')";
$result = #mysql_query($SQL) or die("Error Saving Draft 2");
header("Location: /cms/matchreports/index.php?message=7");
exit;}}
if($_POST['btnSubmit'] == 'Publish changes'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . y . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=8");
exit;}
if($_POST['btnSubmit'] == 'Publish draft to website'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . y . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=9");
exit;}
if($_POST['btnSubmit'] == 'Save changes to draft'){
//This gets all the other information from the form
$newdate = $_POST['date_y'].''.$_POST['date_m'].''.$_POST['date_d'];
$SQL = "UPDATE " . $match_reports_table . " SET Title='" . addslashes($_REQUEST ['Title']) . "',ShortTitle='" . addslashes($_REQUEST['ShortTitle']) . "',Story='" . addslashes($_REQUEST['Story']) . "',Category='" . addslashes($_REQUEST['Category']) . "',FrontPage='" . addslashes($_REQUEST['FrontPage']) . "',active = '" . n . "',date='$newdate' WHERE ID=" . $_REQUEST['ID'] . "";
$result = #mysql_query($SQL) or die("Error Updating News");
header("Location: /cms/matchreports/index.php?message=10");
exit;}
}?>

Use PDO and prepared statements.

A simple, universal rule I like to apply is this:
Always store data raw, and escape it for the appropriate application when needed.
This means, get rid of nebulous stripslashes(), and:
for string values in SQL statements, use the database's appropriate escape function, e.g. mysqli_real_escape_string(),
for system()-type command names, use escapeshellcmd(), for arguments use escapeshellarg(),
for manually assembling GET request URLs, use urlencode(), and finally
for printing content in an HTML structure, use htmlentities().
There's no point in blindly using some sort of mangling and hoping it'll filter out bad things. Be conscious of what you're doing, and do the appropriate thing at every step.
Example: To print a link with a user-provided GET parameter, you'd do
print("<a href='" . htmlentities($BASEURL . "?data=" . urlencode($untrusted)) . "'>click</a>");
Important note: For SQL queries, it is generally preferable to use prepared statements rather than building queries by hand. This is a different technology from what you're used to, so it's not the straight "how do I fix this" answer, but it is by far the better solution.

I strongly suggest this article generally on escaping (google-translated from czech language)

Related

SQL Can't Delete from Table

I have a PHP and I want to do 2 inserts and 1 delete, but I can only make an insert. If the array containt the last parameter == "historico" should delete from instant_table all register with same serial_num and inserte the array intro the instant_table and insert in historical_table("SensorData"). Ifnot (the array don't hace the parameter "historico"), should de delete from instant_table all register with same serial_num and only inserte the array intro the instant_table.
My code:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$serial_numb = test_input($_POST["serial_numb"]);
$DHTtempC = test_input($_POST["DHTtempC"]);
$DHThumid = test_input($_POST["DHThumid"]);
$CCS811_CO2 = test_input($_POST["CCS811_CO2"]);
$CCS811_tVOC = test_input($_POST["CCS811_tVOC"]);
$PM25 = test_input($_POST["PM25"]);
$PM10 = test_input($_POST["PM10"]);
$reading_date = date("Y-m-d");
$update_status = test_input($_POST["update_status"]);
$tipo_tabla = test_input($_POST["tipo_tabla"]);
// Create connection
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
if ($tipo_tabla == "historico"){
$sql = "INSERT INTO SensorData (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
}
$sql = "DELETE FROM instant_data WHERE (serial_numb = '" . $serial_numb . "')";
$sql = "INSERT INTO instant_data (serial_numb, DHTtempC, DHThumid, CCS811_CO2, CCS811_tVOC, PM25, PM10, reading_date, update_status)
VALUES ('" . $serial_numb . "', '" . $DHTtempC . "', '" . $DHThumid . "', '" . $CCS811_CO2 . "', '" . $CCS811_tVOC . "', '" . $PM25 . "', '" . $PM10 . "', '" . $reading_date . "', '" . $update_status . "')";
if ($mysqli->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $mysqli->error;
}
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$mysqli->close();
}
else {
echo "No data posted with HTTP POST.";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Tu sum up, If the array contains the parameter, INSERTE(TABLE1) + DELETE with same serial_num(TABLE2) + INSERTE(TABLE2). If not DELETE with same serial_num(TABLE2) + INSERTE(TABLE2).
EDIT: Now this code only make the second INSERT
It seems like you are overwriting the content of $sql without executing the queries in between. You have to either:
execute each query before redefining $sql
use $sql .= (instead of $sql =) to concatenate the next query. If you do this, you have to terminate your sql query with an ; before concatenating the next query.
Are you using this code just for an small personal project or are you going to publish this in any way? In case of the later one:
please read into PHP SQL best practices. With your current approach you are vulnerable to SQL injections and your code is kinda difficult to read.

Database error: Invalid SQL: WHERE id IN (91220,91222,91232,91233,91244,91263,

The SQL below when echoed in the PHP script displays only WHERE id IN (91220,91222,91232,91233,91244,91263,91264,91277)
Please help me find what is wrong with the SQL.
$sql = "UPDATE customers SET customers.name=AES_ENCRYPT('" . self::PII_OBFUSCATE_NAME . "','" . AES_CRYPT_KEY . "')"
. ", address1=AES_ENCRYPT('" . self::PII_OBFUSCATE_ADDRESS1 . "','" . AES_CRYPT_KEY . "')"
. ", day_phone=AES_ENCRYPT('" . self::PII_OBFUSCATE_PHONE . "','" . AES_CRYPT_KEY . "')"
. ", nite_phone=AES_ENCRYPT('" . self::PII_OBFUSCATE_PHONE . "','" . AES_CRYPT_KEY . "')"
. (is_array($customers_to_obfuscate))
? " WHERE id IN (" . implode(",", $customers_to_obfuscate) . ")"
: " WHERE id = '$customers_to_obfuscate'";
You need to check your braces in the ternary operator. It must look like follows:
((is_array($orders_to_obfuscate)) ? " WHERE id IN (" . implode(",", $orders_to_obfuscate) . ")" : " WHERE id = '$orders_to_obfuscate'");

on form submission values not inserting into database in php

i have an html form , when user submits the data, the data goes into database, this was working fine until i added one more thing, i added mail function to send the mail after the data is submitted. my code is like below:
<?php
error_reporting(0);
session_start();
require('db_config.php');
if (isset($_POST['submit'])) {
$name = $_FILES['Photo']['name'];
list($txt, $ext) = explode(".", $name);
$image_name = time() . "." . $ext;
$tmp = $_FILES['Photo']['tmp_name'];
$shame = $_FILES['paymentphoto']['name'];
list($txts, $exts) = explode(".", $shame);
$receipt_name = time() . "." . $ext;
$tmps = $_FILES['paymentphoto']['tmp_name'];
if (move_uploaded_file($tmp, 'uploads/' . $image_name) && move_uploaded_file($tmps, 'receipt/' . $receipt_name)) {
$sql = "INSERT INTO members (firstname, lastname, image, company, designation, addressone, addresstwo, aadhar, city, state, pin, pan, rnameone, rnametwo, mobile, alternate, email, experience, businessdate, companyregistration, gstin, servicesoffered, fee, mode, receipt) VALUES ('" . $_POST['first_name'] . "','" . $_POST['last_name'] . "' , '" . $image_name . "','" . $_POST['company'] . "', '" . $_POST['designation'] . "','" . $_POST['address'] . "', '" . $_POST['address2'] . "', '" . $_POST['aadhaar'] . "', '" . $_POST['city'] . "', '" . $_POST['state'] . "', '" . $_POST['pin'] . "', '" . $_POST['pan'] . "', '" . $_POST['recommended'] . "', '" . $_POST['recommended2'] . "','" . $_POST['mobile'] . "', '" . $_POST['alternate'] . "', '" . $_POST['email'] . "', '" . $_POST['experience'] . "', '" . $_POST['date'] . "', '" . $_POST['registration'] . "', '" . $_POST['gst'] . "', '" . $_POST['services'] . "', '" . $_POST['fee'] . "', '" . $_POST['payment'] . "', '" . $receipt_name . "' )";
$mysqli->query($sql);
$to = "teiamembers#gmail.com"; // this is your Email address
$from = $_POST['email']; // this is the sender's Email address
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$headers = "From:" . $from . "\nMIME-Version: 1.0\nContent-Type: text/html; charset=utf-8\n";
$headers2 = "From:" . $to;
$subject = "TEIA Membership Registration Request";
$subject2 = "TEIA Membership Request";
$message = $first_name . " has requested for TEIA Registration. Full Name:" . " " . $first_name . " " . $last_name . "<br>" . "Email:" . $from . "<br>" . "Mobile:" . " " . $_POST['mobile'] . "<br>" . "Company Name:" . " " . $_POST['company'] . "<br>" . "Designation" . " " . $_POST['designation'] . "<br>" . "Residence Address:" . " " . $_POST['address'] . "<br>" . "Office Address:" . " " . $_POST['address2'] . "<br>" . "Aadhaar:" . " " . $_POST['aadhaar'] . "<br>" . "City:" . " " . $_POST['city'] . "<br>" . "State:" . " " . $_POST['state'] . "<br>" . "Pin:" . " " . $_POST['pin'] . "<br>" . "Pan:" . " " . $_POST['pan'] . "<br>" . "Reference:" . " " . $_POST['recommended'] . "<br>" . "Alternate Number:" . " " . $_POST['alternate'] . "<br>" . "Experience:" . " " . $_POST['experience'] . "<br>" . "Aadhaar:" . " " . $_POST['aadhaar'] . "<br>" . "Date of Business Setup:" . " " . $_POST['date'] . "<br>" . "Company Registration Number:" . " " . $_POST['registration'] . "<br>" . "GSTIN:" . " " . $_POST['gst'] . "<br>" . "Services Offered:" . " " . $_POST['services'] . "<br>" . "Fee Paid:" . " " . $_POST['fee'] . "<br>" . "Payment Mode:" . " " . $_POST['payment'] . "<br>";
$message2 = "Your request for TEIA Membership Received. We will contact you Shortly. ";
mail($to, $subject, $message, $headers);
mail($from, $subject2, $message2, $headers2); // sends a copy of the message to the sender
if ($mysqli) {
$msg = "Your Request For Membership Registration Sent Successfully";
}
}
}
?>
now the problem is when the user submits the form, the mail is working properly, but the values are not going to database, can anyone please tell me what could be wrong here, thanks in advance
TAKE CARE OF SQL INJECTION first.
Some amount of checking is necessary all the time. At the very least...this one.
if($mysqli->query($sql)) { fine } else { error }
And in the "error" part of above, if you would have included error number and actual message, you yourself might have found the answer.
Main doubt I have is...you have some unique column and the insert did not happen as it did appear in database earlier.
Also, better to use an id int unique auto_increment for several purposes.
Secondly, you should have created $mailstatus and have checked the same and not mysqli for this message.
if ($mailstatus) {
$msg = "Your Request For Membership Registration Sent Successfully";
}

PHP MySQL INSERT query not inserting all values

I have this variables :
$cliente = mysqli_real_escape_string($conn, htmlentities($_GET["cliente"]));
$metatickt = mysqli_real_escape_string($conn, htmlentities($_GET["metatickt"]));
$metaext = mysqli_real_escape_string($conn, htmlentities($_GET["metaext"]));
$metaenc = mysqli_real_escape_string($conn, htmlentities($_GET["metaenc"]));
$uf = mysqli_real_escape_string($conn, htmlentities($_GET["estado"]));
And I'm trying to do this query :
$queryInst = "INSERT meta_control (mes,cliente,meta_exit,meta_tickt,meta_enc,uf)"
. " VALUES (MONTH(NOW()),'" . $cliente . "','" . $metaext . "','" . $metatickt . "','" . $metaenc . "','" . $uf . "')";
mysqli_query($conn, $queryInst);
But when I check my db the only column that is not NULL is mes. What could be the cause to this?
You should have to use proper query. INSERT INTO
$queryInst = "INSERT INTO meta_control (mes,cliente,meta_exit,meta_tickt,meta_enc,uf)"
. " VALUES (MONTH(NOW()),'" . $cliente . "','" . $metaext . "','" . $metatickt . "','" . $metaenc . "','" . $uf . "')";
mysqli_query($conn, $queryInst);
You are probably getting an SQL error.
You should check for such errors using mysqli_error($conn) - http://php.net/manual/en/mysqli.error.php. In this case you probably have an error caused by the absence of the INTO keyword in your SQL query, which should be INSERT INTO ....
http://dev.mysql.com/doc/refman/5.7/en/insert.html

I want to show an error if duplicates are there in database using php and mysql

I'm trying to show an error while entering duplicates using php and mysql, but i'm not getting how to complete, please give an solution........
this is my code:
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
}
You have to create unique key in productcost table , using unique fields like (product, productCategory, model). Now execute insert query, if there is a recode in the table return error . now you can handle error and give message.
try{
mysql_query("INSERT INTO productcost (product_key_id,product, productCategory,model,purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES
('" . $_POST["created_product_id"] . "','" . $_POST["product"] . "','".$_POST["productCategory"] . "','" . $_POST["model"] . "','".$_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','".$_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','".$_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
return TRUE;
}
catch(Exception $e){
return FALSE;
}
or you can check is there a recode in table before insert
select count(*) as cc from doc_upload where product_key_id = $_POST["created_product_id"];
To show an error message while entering duplicates:
// First check there are same data available or not using a query by counting the row
$sqlCheck = "SELECT COUNT(`id`) WHERE product = '" . $_POST["product"] . "' AND productCategory = '" . $_POST["productCategory"] . "' AND model = '" . $_POST["model"] . "'"; // You have to add mroe thing in where clause
$CheckQuery = mysql_query($sqlCheck);
// if there is no duplicate data
//
if ($CheckQuery > 0) {
# code...
mysql_query(
"INSERT INTO productcost (product, productCategory, model, purchasePrice, mrp, customerPrice, marginCustomer, dealerPrice, marginDealer)
VALUES ('" . $_POST["product"] . "','" . $_POST["productCategory"] . "','" . $_POST["model"] . "','" . $_POST["purchasePrice"] . "','" . $_POST["mrp"] . "','" . $_POST["customerPrice"] . "','" . $_POST["marginCustomer"] . "','" . $_POST["dealerPrice"] . "', '" . $_POST["marginDealer"] . "')");
$current_id = mysql_insert_id();
if(!empty($current_id)) {
$message = "New Product Added Successfully";
}
} else {
$message = "Data is Duplicated";
}
Note : I'm Giving you an Example . this is how you have to check
duplicate data

Categories