Sanitize POST array

I have a form to allow users to update a mysql database using

      $location = $_POST['Location'];
      $elevation = $_POST['Elevation']; 
      $circuit_breaker = $_POST['CB'];
      $power_panel = $_POST['PP']; 
      $title = $_POST['Title'];
      $number_of_slots = $_POST['NOS']; 
      $display  = $_POST['display'];

I want t sanitize the variables in case some idiot enters bad data.
Does this help?

      $location = filter_var($_POST['Location'], FILTER_SANITIZE_STRING);
      $elevation = filter_var($_POST['Elevation'] , FILTER_SANITIZE_STRING); 
      $circuit_breaker = filter_var($_POST['CB'], FILTER_SANITIZE_STRING);
      $power_panel = filter_var($_POST['PP'], FILTER_SANITIZE_STRING); 
      $title = filter_var($_POST['Title'], FILTER_SANITIZE_STRING);
      $number_of_slots = filter_var($_POST['NOS'], FILTER_SANITIZE_INT); 
      $display  = filter_var($_POST['display'], FILTER_SANITIZE_INT); 

To make sure all my variables are of type string, except the last 2 are integers

Maybe try this?

Also this may be of interest:

// Replace type “range” with “number”

1 Like

if I do it like that, do I have to worry about people entering double/single quotes?
Would I have to do

$patterns = array();
$patterns[0] = '/"/';
$patterns[1] = "/'/";
$replacements = " ";
$title = preg_replace($patterns, $replacements, $_POST['title']);

Do your tests cater for every eventuality?

What I usually do is to setup a local test environment and to test all possible options before uploading to the server.

What characters are you trying to replace?

I usually use this function:

$test = $_POST['title'];
$test = "all \n\t  ' ' possibilities \n";
$bad  = [
  "'",  // single quote
  '"',  // double quote
  "  ", // double space
$good = " "; // single space
$good = "XXX"; // debug

echo '<br>before ==> ', $test;
$test = str_replace($bad, $good, $test);
echo '<br>after ==> ', $test;

Tested and replaced single forward slash with a double slash

1 Like

No, no, no. Stop.

If you want to prevent SQL injections, use prepared statements. That’s the only valid answer.


My first question would be: sanatize for what? Or what against. “Bad data” what should that mean? Bad for whom? Sanatizing is a matter of context. But if the answer is SQL, then yes, Prepared Statements are to use.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.