Re: escape your variables

From: Date: Tue, 21 Apr 2009 00:05:59 +0000
Subject: Re: escape your variables
References: 1 2 3 4 5 6 7  Groups: php.general 
Request: Send a blank email to php-general+get-291711@lists.php.net to get a copy of this message
How does one deal with that? Do you use mysql_real_escape_string? e.g. <?php $db_host = 'localhost'; $db_user = 'auser'; $db_pwd = 'apassword'; $database = 'adatabase'; $table = 'authorBook'; if (!mysql_connect($db_host, $db_user, $db_pwd)) die("Can't connect to database"); if (!mysql_select_db($database)) die("Can't select database"); // sending query $result = mysql_query("SELECT * FROM {$table}");
    
Inputs are user supplied.
Are you saying that I don't need to sanitize the variables above - $db_host, $db_user, $db_pwd, $database, $table ?
No - they are essentially hardcoded. A user (through a form or any other method) cannot change which db you are talking to. They cannot change the hostname either. If a variable comes from: - a post variable - a get variable - a session variable - a cookie - an environment variable then it will need to be escaped & sanitized. If you are putting the variable at the top of the script and there's no way for a user to change it, then no need to sanitize.
I would love to see an example somewhere that shows an unsanitized variable and the same variable sanitized.
"Sanitizing" depends on what you need. An age field doesn't need anything except a number. A name field should accept everything except html tags. They are going to be sanitized differently. $name = $_POST['name']; <-- unsanitized $name = strip_tags($name); <-- sanitized.
========= Better: myql_query("INSERT INTO foo (name) VALUES ('". mysql_real_escape_string($name, $link) ."')"); This is better because we escape it in the sql statement itself. $name remains unchanged in case we want to use it later. Best: Use prepared statements! ========= What is meant by prepared stetements? Does that mean not using variables?
It's a different way of putting the query together. Data can only mean one thing - data. There's no escaping, the db will always know what it's going to do. http://www.php.net/manual/en/pdo.prepare.php -- Postgresql & php tutorials http://www.designmagick.com/

« previous php.general (#291711) next »