Inheriting a web application: an example of fixing someone else’s mistake

Steve Sohcot
2 min readNov 17, 2023

--

What the original developer thought — from Image from MakeAMeme.org

I recently inherited a PHP application. Some users were having trouble inserting strings into the database, and the function to sanitize the input was the culprit.

Don’t Trust User Input

Hopefully you already know you need to “sanitize” user input. The previous developer had a function to check every (string) input from a form using this function:

// original function - don't use this
function c($string){
return strip_tags($string);
}

Perhaps “c” meant “clean”? ❓ 😕

While it was a good intention, if a user happen to put in a string with an apostrophe (ex. “Zoidberg’s wedding album”) then the database threw an error.

As a quick fix, I changed the function to this:

function c($string){
global $con;
$string = strip_tags($string)
return mysqli_real_escape_string($con,$string);
}

And it worked.

Going forward

If I were making a new application, I suggest:

  • Use mysqli_real_escape_string
  • Pass in the database connection into the function, rather than using a global variable
  • Name the function something better

I previously wrote about a PHP function to sanitize user input, copied below:

<?php
function quote_smart($db_connection, $value) {
if( get_magic_quotes_gpc() )
$value = stripslashes( $value );

$value = mysqli_real_escape_string($db_connection, $value );
$value = strip_tags($value);
$value = htmlspecialchars($value);
$value = trim($value);
return $value;
}
?>

--

--

No responses yet