Prevent MySQL Injection on search and dropdowns - mysql

I know this might have been asked before but I am trying to protect my search field and drop downs from MySQL injection and am having trouble integrating mysql_real_escape_string into my PHP. I am currently filtering my search results by keywords in 2 drop downs or by a freeform input where the user types in a reference. I've commented below where I am trying to add the escape string but it is breaking my search function. Can anyone advise me on what to do? Thanks for any help
<?php
// SEARCH FROM TEXT INPUT
mysql_select_db($database_connectInfo, $connectInfo);
if (isset($_POST['searchByRef']))
{
$searchword = $_POST['searchByRef'];
//ESCAPE STRING HERE
$searchword = mysql_real_escape_string($connectInfo, $searchword);
$query_dbname = "SELECT * FROM dbname WHERE `ref` LIKE '%".$searchword."%'";
}
else
// SEARCH FROM DROPDOWN MENUS
if (isset($_REQUEST['submit']))
{
$drop1 = $_POST['search1'];
$drop2 = $_POST['search2'];
//ESCAPE STRING HERE
$drop1 = mysql_real_escape_string($connectInfo, $drop1);
$drop2 = mysql_real_escape_string($connectInfo, $drop2);
$query_dbname = 'SELECT * FROM dbname WHERE 1=1' . ($drop1 ? ' AND `colour` LIKE "%' . $drop1 . '%"' : '') . ($drop2 ? ' AND `style` LIKE "%' . $drop2 . '%"' : ' ORDER BY id DESC');
}
else
{
$query_dbname = "SELECT * FROM dbname ORDER BY ref DESC";
}
$dbname = mysql_query($query_dbname, $connectInfo) or die(mysql_error());
$row_dbname = mysql_fetch_assoc($dbname);
$totalRows_all = mysql_num_rows($dbname);
?>

Don't use mysql_escape_string.. instead use mysqli or PDO with prepared statements.
http://www.php.net/manual/en/book.pdo.php
For more info on WHY see this:
Why mysql_real_escape_string() did not prevent hack?

Related

Unique Profile Slug with PHP and PDO

I am using a class to generate a string name profile to slug and next use an SQL command to tell me whats the unique value to use in insert command, the problem is the command isn't working properly, sometimes it is possible to return a value which already exist...
Thats the class I am using to generate the slug: (composer require channaveer/slug)
And this the example code:
use Channaveer\Slug\Slug;
$string = "john doe";
$slug = Slug::create($string);
$profile_count_stmt = $pdo->prepare("
SELECT
COUNT(`id`) slug_count
FROM
`advogados_e_escritorios`
WHERE
`slug_perfil` LIKE :slug
");
$profile_count_stmt->execute([
":slug" => "%".$slug."%"
]);
$profile_count = $profile_count_stmt->fetchObject();
if ($profile_count && $profile_count->slug_count > 0) {
$profile_increment = $profile_count->slug_count + 1;
$slug = $slug . '-' . $profile_increment;
}
echo 'Your unique slug: '. $slug;
// Your unique slug: john-doe-5
This is the content of the table when the script run:
Do you know how can I improve the select command to prevent it to return existing slugs from DB?
Ok finally found a solution... Heres the code for who wants to generate unique profile slugs using PHP - PDO and MySQL
$string = "John Doe";
$string = mb_strtolower(preg_replace('/\s+/', '-', $string));
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
$pdo = Conectar();
$sql = "
SELECT slug_perfil
FROM advogados_e_escritorios
WHERE slug_perfil
LIKE '$slug%'
";
$statement = $pdo->prepare($sql);
if($statement->execute())
{
$total_row = $statement->rowCount();
if($total_row > 0)
{
$result = $statement->fetchAll();
foreach($result as $row)
{
$data[] = $row['slug_perfil'];
}
if(in_array($slug, $data))
{
$count = 0;
while( in_array( ($slug . '-' . ++$count ), $data) );
$slug = $slug . '-' . $count;
}
}
}
echo $slug;
//john-doe-1
You should check if the slug exists or not from your database. If it already exists then you can append some random string like the following
$slug = Slug::create($string);
$slugExists = "DB query to check if the slug exists in your database then you may return the count of rows";
//If the count of rows is more than 0, then add some random string
if($slugExists) {
/** NOTE: you can use primary key - id to append after the slug, but that has to be done after you create the user record. This will help you to achieve the concurrency problem as #YourCommenSense was stating. */
$slug = $slug.time(); //time() function will return time in number of seconds
}
//DB query to insert into database
I have followed the same for my blog articles (StackCoder) too. Even LinkedIn follows the same fashion.
Following is screenshot from LinkedIn URL

replace mysql_real_escape_string for security purposes

I was using a WordPress Plugin That broke on update to 4.3. The error was
mysql_real_escape_string(): Access denied for user
I found out that the error was because the mysql_real_escape_string is called from within MySQL and needs to be logged in before execution. Solutions were to include a mysql_connect before the mysql_real_escape_string, which solved the problem. But it seems from many of the comments, the mysql_real_escape_string an this solution should not be used for various security reasons. But I am not sure how to change the code to PDO::quote etc as I am not really sure whats going on. The query I am trying to change is
function custom_permalinks_request($query) {
global $wpdb;
global $_CPRegisteredURL;
// First, search for a matching custom permalink, and if found, generate the corresponding
// original URL
$originalUrl = NULL;
// Get request URI, strip parameters and s
$url = parse_url(get_bloginfo('url'));
$url = isset($url['path']) ? $url['path'] : '';
$request = ltrim(substr($_SERVER['REQUEST_URI'], strlen($url)),'/');
$request = (($pos=strpos($request, '?')) ? substr($request, 0, $pos) : $request);
$request_noslash = preg_replace('#/+#','/', trim($request, '/'));
if ( !$request ) return $query;
$sql = "SELECT $wpdb->posts.ID, $wpdb->postmeta.meta_value, $wpdb->posts.post_type FROM $wpdb->posts ".
"LEFT JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) WHERE ".
" meta_key = 'custom_permalink' AND ".
" meta_value != '' AND ".
" ( LOWER(meta_value) = LEFT(LOWER('".mysql_real_escape_string($request_noslash)."'), LENGTH(meta_value)) OR ".
" LOWER(meta_value) = LEFT(LOWER('".mysql_real_escape_string($request_noslash."/")."'), LENGTH(meta_value)) ) ".
"ORDER BY LENGTH(meta_value) DESC LIMIT 1";
$posts = $wpdb->get_results($sql);
return $query;
}
Is there an easy way to replace the mysql_real_escape_string or better way to do this? I am not sure this question is similar, but I dont see how to implement the answers.

How to search ignoring spaces between words?

I want search names using my search module with ignoring white spaces .
Ex: if i want to search a name like "A B Zilva"
i want to disply the results on dropdown even if i type the name like "AB Zilva".
currently search without space is not working
$db = JFactory::getDbo();
$searchp=$_GET["term"];
$searchp = str_replace(' ','%%', trim($searchp));
//$searchp= preg_split('/ /', $searchp);
$query = $db -> getQuery(true);
$query="SELECT * FROM content where title like '%".$searchp."%'AND categories_id=82 order by title ASC ";
$db -> setQuery($query);
// Load the results as a list of associated arrays.
$results = $db -> loadAssocList();
$json=array();
foreach ($results as $json_result) {
$json[] = array('value' => $json_result["title"], 'label' => $json_result["title"]);
}
Please advice .
update :
jQuery.extend( jQuery.ui.autocomplete.prototype, {
_renderItem: function( ul, item ) {
var term = this.element.val(),
regex = new RegExp( '(' + term + ')', 'gi' );
html = item.label.replace( regex , "<b>$&</b>" );
return jQuery( "<li></li>" )
.data( "item.autocomplete", item )
.append( jQuery("<a></a>").html(html) )
.appendTo( ul );
}
});
The problem with your code is that when you replace space with %%, you get a search like:
WHERE title like '%AB%%Zilva%'
but this won't match when the title is A B Zilva. You need to remove spaces from both the search string and the column in the database. Do it like this:
$searchp = str_replace(' ', '', $searchp);
and then change the SQL to:
WHERE REPLACE(title, ' ', '') LIKE '%$searchp%'
For the Javascript highlighting, I think you need to do this:
var term = this.element.val().replace(/ /g, '').replace(/.(?=.)/g, '$& *'),
This will create a regular expression that allows for spaces between any of the characters in the search string.

Will my code prevent SQL injection

i have searched and added some prevention code but i need expert advice am i correct ?
I have made seperate file for SQL connect but i have confusion whether i should use include, require, include_onces or any other ?
mysql_connect("localhost", "userr", "pass") or die(mysql_error()) ;
mysql_select_db("databse") or die(mysql_error()) ;
Here i have added two things UTF8 and mysql_real_escape_string.
$bad='anyone123';
$var = mysql_real_escape_string($bad);
$q = mysql_query('SET user_id UTF8');
$q = mysql_query("SELECT * FROM fbusers WHERE user_id = '$var'");
$r = mysql_fetch_array($q);
Please give me advice if how can i prevent injec. to 100%
i don't want my website to be hacked :(
Thank you
You need to use prepared statements for any queries that require user input. This sends the query and the parameters seperately and acts as a layer of security to catch any malicious input.
In PDO:
$stmt = $pdo->prepare("SELECT * FROM fbusers WHERE user_id = :var");
$stmt->execute(array(':var'=>$var));
In mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM fbusers WHERE user_id = ?');
$stmt->bind_param('s', $var);
$stmt->execute();
Maybe this post would help.

Mysql dynamic sql statement with PDO and parameters

I want to create a dynamic sql statement and run it using PDO. My problem is that i have some parameters and i cannot think of a way to pass the parameters.
Ex :
$query = "Select * from tbl_task where 1=1";
if (!empty($name)) $query .= " AND name = ?";
if (!empty($status)) $query .= " AND status = ?"
$db_stmt = new PDOStatement();
$db_stmt = $this->db->prepare($query);
$db_stmt->bindParam (1,$name);
$db_stmt->bindParam (2,$status);
My parameters does not get binded and i don't know how many parameters i have to bind, unless i write the same if statements but with bindParam instructions.
I tryed with mysql_real_escape_string instead bindParam to PDO but for some reason my parameters are added empty.
Any idea on how can i build a dynamic query and bind parameters to PDO ?
Edit 1 :
$arr = array();
if (!empty($name)){
$query .= " AND `name` like :NAME";
$arr['NAME'] = $name;
}
$db_stmt = new PDOStatement();
$db_stmt = $this->db->prepare($query);
$db_stmt->execute($arr);
How can i write a "like" statement ? I tried
$query .= " AND `name` like :NAME" . "%";
and is not working.
What I usually do is the following:
$query = "Select * from `tbl_task` where 1=1";
$arr = array();
if (!empty($name))
{
$query .= " AND `name` = :NAME";
$arr['NAME'] = $name;
}
if (!empty($status))
{
$query .= " AND `status` = :STATUS";
$arr['STATUS'] = $status;
}
$this->db->beginTransaction();
try
{
$tmp = $this->db->prepare($query);
$tmp->execute($arr);
$this->db->commit();
}
catch(PDOException $ex)
{
$this->db->rollBack();
$this->log->error($ex->getMessage());
}
You can't add SQL code as a parameter; only data will do. You'll have to force these bits into $query. They won't be escaped then so they shouldn't contain user-submitted data.
What I usually do is the following:
$query = "Select * from tbl_task where 1=1";
if (!empty($name)) $query .= $db->parse(" AND name = ?s", $name);
if (!empty($status)) $query .= $db->parse(" AND status = ?s",$status);
$data = $this->db->getAll($query);
the idea is in having a function to parse placeholders in arbitrary query part instead of whole query.
I don't bother with native prepared statements though. They pollute PHP scripts with heaps of useless code with not a single benefit.
To answer updated question
as you've been told, you can't bind arbitrary query part. But a literal only.
So, make your literal looks like foo% and then bind it usual way.