CSI: PHP

"Looking at your tweets I cannot even fathom what your job is. CSI:PHP?" — @grmpyprogrammer

I Do Not Think This Function Does What You Think It Does

| Comments

How ‘bout a little data filtering before you go inserting user-generated data into that nice database of yours? Here’s a handy function that does just that. No need to test this one; I know it outputs exactly what I expect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php

Function prepString($string) { // Specifically for MSSQL '' instead of \'
    $badChars = array("'", "&", ",");
    $goodChars = array("", "&", "");

    if (is_string($string)) {
        $string = str_replace($badChars, $goodChars, $string);
        $string = stripslashes($string);
        $string = "$string";
    }

    return($string);
}

Here’s an example of the function in use.

1
2
3
4
5
6
7
8
9
<?php

foreach ($_POST as $x => $y) {
    $_POST[$x] = prepString($y);
}

$query = "insert into table (column1, column2, column3, column4)
    values('" . $_POST['input1'] . "','" . $_POST['input2']
    . "', '" . $_POST['input3'] . "', '" . $_POST['input4'] . "')";

Comments