Recommended Posts

BACKGROUND: It appears that there are few problems in web development that do not have multiple solutions. My problem is to decide which solution best suits my needs. I have a confirmation email that sends a name, hash, and email address via an HTTP REQUEST using the $_GET superglobal to a PHP file that matches the hash with an entry in a newsletter roster table. If the match succeeds the value of the status variable is changed from 0 to 1. Before the hash is sent to the roster table it is sanitized using the MySQLi real_escape_string( ) function.

Elsewhere on my website I use the PHP filter_var( ) function with parameter values that vary with the nature of the data being sent.

QUESTION ONE: In the above instance which PHP function would be more secure. And, why?

To ensure that values are safe for the database, you must use prepared statements.

This I do.

I am referring to the first receipt of the $_GET superglobal -- at the point where I am likely to take information from the variables contained within and seek to process it before uploading it to the database.

Sanitization depends entirely on how the data is being used. If it's being used inan SQL query it has to be made safe for SQL syntax, if it's being printed on an HTML page it has to be made safe for HTML syntax, if it's being put into a Javascript string you need to escape the string delimiters. The data itself, during processing, is not inherently dangerous in any way; it only becomes dangerous when it can be interpreted as code to be executed.

You can't sanitize it when it comes in because you don't know where it's going to be used so you don't know how it needs to be sanitized, there's no single sanitization solution that works for all cases.

You can't sanitize it when it comes in because you don't know where it's going to be used so you don't know how it needs to be sanitized, there's no single sanitization solution that works for all cases.

Could I reword the above statement to read, "When coding (positive) it is not what is coming in that must be sanitized; rather, what is being sent out. When hacking (negative) it is what is going in that counts."

Please allow me now to restate my two questions.

QUESTION ONE: When would you use the real_escape_string( ) function?
QUESTION TWO: When would you use the PHP filter_var( ) WITH sanitization?

The lesson you should be taking is that whenever data is being used in an environment, it should be sanitized according to the syntax of that environment. I don't know anything about hacking.

I would never use the real_escape_string() function. It was used to escape string values for SQL queries before prepared statements existed. Now that prepared statements exist there is no reason to use it.

I've never used filter_var() before. Some people like to use it for validating form data but there is never a situation where it is completely necessary.