Search code examples
phpjquerymysqlajaxsql-injection

How to make my search engine safe?


I have been making a search engine for my website and just got it completed i am using an ajax request to search the database and wanted to know how i can make it safe from any injections?

Search.ajax.php

    <?php 
$db = new mysqli('localhost', 'root', 'root', 'social');
$search = $_POST['search'];

$query = mysqli_query($db, 'SELECT * FROM users WHERE username LIKE "'.$search.'"');

if (mysqli_num_rows($query) < 1) {
    echo "<b>No results found for <i>".$search."</i></b>";
}else{
    while ($r = mysqli_fetch_assoc($query)) {
        $user = $r['username'];
        echo '<div>Go to <a href="profile.php?user='.$user.'">'.$user.'</p></div>';
    }
}


 ?>

I am searching the database for users that have the username of what they put in the search box. i need help making it so no one can search alert(test); if they search this it will show up an alert box here is an example of it.here is a photo of when someone puts in script tags


Solution

  • Firstly, you will need https to make sure you protect users from hackers by using firewalls and other required security tools.

    Secondly, you need to use htaccess to change extensions, say show user .html instead of .php

    Thirdly, encrypted values instead of plain text.

    There are a lot more issues to take care of but its too complex and broad.