Input cleansing clarification

Hello, I’m wondering, I have never quite known where/why mysql cleansing has to use mysql_real_escape_string

If I am loggin an ip address in the mysql database and I filter it with
$ip = preg_replace(“/[^0-9.]/”, “”, $_SERVER[‘REMOTE_ADDR’]);

Is this not as safe as using the mysql_real_escape_string?

Is the preg_replace returning more than numbers and dots?

I have just never fully understood why/what makes mysql_real_escape better (when content is filtered with a regex expression).

mysql_real_escape_string is an example of “escaping”, ie protecting the next environment which is about to receive some data.

Your ip preg_replace() example could be described as “filtering”, ie only allowing in what you expect and in this case, removing what is not explicitly allowed in digits and a dot.

The rule is called FIEO (Filter Input, Escape Output).

Do your best to filter incoming data, but no matter how confident you are you have filtered it correctly (mistakes can happen) get into the habit of escaping the output for the next environment.

This applies to any user-generated input, and this includes anything coming from GET, POST, COOKIES and so on.

if the next environment is a webpage, as html, then use the [fphp]htmlentities[/fphp] family of escape options.

Bang FIEO into your head till you get it, it is critical when working on the web.

Have a mental picture of stuff coming into PHP from one end of a pipe, and going somewhere else out the other end.

Excellent, This was what I needed to know…