Is my mysql search secure enough to prevent basic injection attacks? [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
I recently have made a search engine using an html form , php and mysqli. What it does is whatever terms i put in the form it searches that in my mysql database and echos it back on my html page. So far its working as I wanted. However I have seen people warn for Mysql injection attacks on the tutorial i made this engine from so can anyone please check my code below and give me an advice.
<?php
$k = mysqli_real_escape_string($_GET['k']);
$terms = mysqli_real_escape_string(explode(" ", $k));
$query = "SELECT * FROM xaplinks WHERE ";
$i = 0;
foreach ($terms as $each) {
$i++;
if ($i == 1) {
$query .= "xap_name LIKE '%$each%'"; }
else {
$query .= "OR xap_name LIKE '%$each%'"; }
}
$con = mysqli_connect('mysql.hostinger.in','steve','password', 'win');
$query = mysqli_real_escape_string(mysqli_query($con, $query));
$numrows = mysqli_num_rows($query);
if ($numrows > 0) {
while ($row = mysqli_fetch_assoc($query)) {
$name = $row['xap_name'];
$link = $row['xap_link'];
echo "<a href='$link'>$name</a></br>";
}
}
else {
echo "No results found. :( ";
}
mysqli_close($con);
?>
I read online that escape string in mysqli can help prevent injection so ive used it but not sure if its properly implemented. Im very new to mysqli.
Any help / tip would be appreciated , Thanks in advance. :)

Use the PDO class instead of the mysqli class. Further, use prepared statements.

You can create a prepared statement using mysqli->prepare
Should solve your problem.
$queryPrepared = mysqli->prepare($query)
See more here.
PHP MySQLI Prevent SQL Injection

Related

Is this search system vulnerable to SQL injection? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
How can I with mysqli make a query with LIKE and get all results?
(2 answers)
Closed 2 years ago.
I have created a PHP and SQLi based search system. It is very basic and works how all of the ones I have found have. I just have one question. Can a very mean and angry person SQL inject my search system. The search is submitted through an HTML form in POST.
Search System Code
...
require 'includes/dbh.inc.php';
$search = $_POST['search'];
$mysqli = $conn;
$query = "SELECT * FROM listings WHERE listing_name LIKE '%".$search."%'";
echo '<b> <center class="listingstitle">Listings</center> </b> <br> <br>';
if ($result = $mysqli->query($query) and mysqli_num_rows($result) > 0) {
while ($row = $result->fetch_assoc()) {
$price = $row["listing_price"];
$name = $row["listing_name"];
$seller = $row["listing_seller"];
$picture = $row["listing_picture"];
...

To prevent SQL injection using PDO in PHP using custom functions [duplicate]

This question already has answers here:
How to bind LIKE values using the PDO extension?
(7 answers)
Closed 7 years ago.
i am going to prevent SQL injection using PDO but i Want to know can my code prevent SQL injection
Here is my code
connection.php
<?php
$hostname='localhost';
$username='root';
$password='root';
try {
$pdo_obj = new PDO("mysql:host=$hostname;dbname=dbname",$username,$password);
$pdo_obj->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo_obj->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
my function.php
<?php
function getdata($pdo_obj, $sql, $params=NULL) // pdo prepaired statements
{
$stmt = $pdo_obj->prepare($sql);
$stmt->execute($params);
return $stmt;
}
?>
and my page.php
<?php
$searchTerm = $_GET['term'];
$result=getdata($pdo_obj,"SELECT b_type FROM b_details WHERE b_type LIKE '%".$searchTerm."%'")->fetchAll();
// my work
?>
every thing working fine but i am not sure is this code prevent SQL Injection
Thanks in Advance
You aren't using your function's ability to protect from injection. To do so you have to send any data via parameters.
<?php
$searchTerm = '%'.$_GET['term'].'%';
$sql = "SELECT b_type FROM b_details WHERE b_type LIKE ?";
$result = getdata($pdo_obj, $sql, [$searchTerm])->fetchAll(PDO::FETCH_COLUMN);
BTW, I added a PDO::FETCH_COLUMN constant that will make the returned array more convenient, given only one column is selected.

mysql error :error in sql syntax [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 7 years ago.
i want to insert some lines of text(paragraph) in database that is coming from wikipedia page..but mysql is showing this error when i try to insert the data in db:
"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 's capital." can anyone help me to fix this problem..
here is what i have done so far...
<?php
$loc=$_POST["new"];
$url1 ="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=".$loc;
$opf = file_get_contents($url1);
$data = json_decode($opf, true);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$des = $page['extract'];
}
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("location", $con);
$url = "http://upload.wikimedia.org/wikipedia";
echo $sql="INSERT INTO `search`(`id`, `name`, `text`) VALUES ('$loc', '$des');";
mysql_query($sql) or die(mysql_error());
echo "1 record added";
mysql_close($con);
?>
Ideally you should escape data before entering it into a database. The problem you have is the apostrophe is ending the SQL query on '$loc' so the query actually reads:
... VALUES ('Giant's Capital',
Syntax highlight should indicate why that's a problem :)
Use something like: mysql_real_escape_string() to escape your $_POST data before inputting.
$loc = mysql_real_escape_string($_POST['new']);
Doesn't explain why it should work
You have 3 fields and 2 values.
doesn't fix their error
Yes, it does.
uses obsolete code, and is wide open to SQL injections
It isn’t my code. I am adapting OPs code, I am not trying to write it from scratch. Also, I guess, you forgot to mention that mysql function is deprecated since 5.5
Further, although the fact that the code is SQL injectable is good to mention it does not in my opinion constitute an actual answer. It's a comment at best. ie. "hey btw did you know you misspelled a word?" or some such. An editorial nitpick. If questions are going to be closed as duplicates of SQL injection questions then 80% of the questions here would have to be closed as dupes.
If the OPs wants to know about SQL injection please refer to this site
Oh, btw,this is the code:
<?php
$loc=$_POST["new"];
$url1 ="https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=".$loc;
$opf = file_get_contents($url1);
$data = json_decode($opf, true);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$des = $page['extract'];
}
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("location", $con);
$url = "http://upload.wikimedia.org/wikipedia";
echo $sql="INSERT INTO `search`(`name`, `text`) VALUES ('$loc', '$des');";
mysql_query($sql) or die(mysql_error());
echo "1 record added";
mysql_close($con);
?>

Is it better to use mysqli_real_escape_string (with mysqli) or placeholders (with PDO)? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 8 years ago.
Given this code:
mysqli_set_charset('utf8');
$id = mysqli_real_escape_string($_GET['id']);
$result = mysqli_query($con,"SELECT * FROM post WHERE id_post = '$id'");
if (mysqli_num_rows($result) == 0) {
header('Location: 404.php');
die();
} else {
// Continue...
}
And this:
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
// New PDO...
$Ps = $Pdo->prepare('SELECT * FROM post WHERE id_post = :id');
$Ps->execute(array(':id', $id));
if ($Ps->rowCount() == 0) {
header('Location: 404.php');
die();
} else {
// Continue...
}
Is there a best option to prevent SQL Injection or the are equivalent?
Second option is the way to go. Using mysql_real_escape_string() leaves open some space for sql injection using some exotic multibyte character. Ref: SQL injection that gets around mysql_real_escape_string()
Alternatively you can use prepared statment with mysqli

How to change normal sql php code to secure pdo? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to prevent SQL Injection in PHP
Is this code secure since i am using mysql_real_escape_string and strip_tags
Is there any need to change to pdo ?
I am not able to convert the following code to pdo because its displaying cannot modify header .
<?php
include('config.php');
$link =mysql_connect($db_host,$username,$password);
mysql_select_db($db_name);
$id= $_POST["uniqi"];
$comments= $_POST["comments"];
$comments= mysql_real_escape_string($comments);
$comments = strip_tags($comments);
$update = "UPDATE mastertable SET comments = '$comments' WHERE id_pk= '$id'";
mysql_query($update, $link);
mysql_close();
header('Location: http://www.xxxx.com/xxxxx/xxxx.php?cntmsg=Comment Updated');
?>
This is not safe code - your $id variable is not processed by your code.
$id= $_POST["uniqi"];
$id= mysql_real_escape_string($id);
$id = strip_tags($id);

Categories