Wednesday, February 18

Best way to prevent some sql injection attacks using PHP

Automagically add slashes to $_POST variables. It helps to prevent some sql injection attacks. Also works with $_GET variables.

FILE NAME: input_cl.php

<?php
    //create array to temporarily grab variables
    $input_arr = array();
    //grabs the $_POST variables and adds slashes
    foreach ($_POST as $key => $input_arr) {
        $_POST[$key] = addslashes($input_arr);
    }
?>

Just put this at the top of your script that gets the variables. Here is an example.

Usage Example

<?php
    include("input_cl.php");
    // all $_POST variables have slashes added to them
    $f_name = $_POST["f_name"];
    $l_name = $_POST["l_name"];
    $phone_num = $_POST["phone_num"];
    $address1 = $_POST["address1"];
    $address2 = $_POST["address2"];
    $city = $_POST["city"];
    $State = $_POST["State"];
    $zip = $_POST["zip"];
 
    //sql insert code goes here.
?>

No comments:

Post a Comment