Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 167
  • Last Modified:

mysql sanitisation example from book


Here is the example

function sanitiseString($var) {
$var = stripslashes($var);
$var = striptags($var);
$var = htmlentities($var); }

function sanitiseMySQL($conn, $var) {

$var= $conn->realeascapestring($var)
$var = sanitiseString($var);
return $var;

$var = sanitiseMySQL, $_POST['input'];
This is based on a mysqli connection object. I am asking out of curiosity as i use prepared statements anyway but if my understanding is correct wouldnt stripSlashes in first function the undo the work of realeascapestring in the second function?

Or does stripslashes leave things alone that are escaped? I know it leaves alone escaped backslashes but if you had escaped an apostrophe wouldnt this code just undo that?.

I know this could open a whole sanitisation debate. That is not my point of asking. I dont understand the example so I asssume I am missing or overlooking something about stripslahes

  • 2
  • 2
1 Solution
Ray PaseurCommented:
The example is wrong, full stop.  Don't use it.

Correct examples are given in this article.
andiejeAuthor Commented:
Glad its not just me :)
andiejeAuthor Commented:
Actually i see i posted the question wrong it should be

$var = sanitiseMySQL(conn, $_POST['input']);

I use PDO but I was still curious to understand what the author was doing.
Ray PaseurCommented:
curious to understand what the author was doing
I have no earthly idea!  It does not make sense to me.

You might want to be aware of the background on Magic Quotes, but that alone does not explain what the author was thinking.  The code just looks wrong, as if the instructions were out of order.

The general design that I follow is this:

1. Filter and sanitize the external input data by verifying that it makes sense (expected integers are, in fact, integers, string lengths are appropriate, etc.)

2. Escape the data with a real_escape_string() function

3. Store in the data base

4. Upon retrieval from the data base, use htmlentities() before echo.

This process ensures that you stored a true representation of what your script received and also protects the clients who see the stored data.  HTMLentities() will prevent malicious Javascript from being executed in the client browser, so it's important to use it before echoing any browser output.

In any case, thanks for the points, ~Ray

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now