.Maui Blog

Prevent sql injection with php

Here is a simple function to prevent Sql Injection with PHP.
Just recall it and check both GET and POST parameters

<?php
function checkInjection() {

    $badchars = array("DROP", "SELECT", "UPDATE", "DELETE", "INSERT", "TRUNCATE", "UNION ALL", "IFNULL", "AS CHAR", "CONCAT(");

    foreach($_REQUEST as $value) {

        if (is_array($value)) {

            foreach($value as $str) {

                $str = strtoupper($str);

                for ($i = 0; $i < count($badchars); $i++) {

                    if (strpos($str, $badchars[$i]) !== false) {
                        die("SQL Injection Detected\n<br />\nIP: ".$_SERVER['REMOTE_ADDR']);
                    }

                }

            }

        } else {

            $value = strtoupper($value);

            for ($i = 0; $i < count($badchars); $i++) {

                if (strpos($value, $badchars[$i]) !== false) {
                    die("SQL Injection Detected\n<br />\nIP: ".$_SERVER['REMOTE_ADDR']);
                }

            }

        }

    }

}
Exit mobile version