You are here: Re: [PHP] Avoiding SQL injections: htmlentities() ? « PHP « IT news, forums, messages
Re: [PHP] Avoiding SQL injections: htmlentities() ?

Posted by Chris Shiflett on 03/27/05 06:40

Hi Ryan,

> From what i have been reading, wrapping all my GET and POST requests in a
> htmlentities() function should keep me safe....right? or what else should
> i/can i do?

No, let me start by correcting a misunderstanding. Yes, htmlentities()
is an escaping function, but it is for escaping data for use in HTML
(e.g., data being sent to the client), not data for use in SQL (e.g.,
data being sent to a database).

To answer this question in reverse, to have an SQL vulnerability
generally requires that you fail to take the two most important steps:

1. Filter input.
2. Escape output.

Filtering input doesn't modify it at all. This is the step where you
inspect data to prove its validity. For example, this is one way to
filter a username that is required to be alphanumeric:

<?php

$clean = array();

if (ctype_alnum($_POST['username']))
{
$clean['username'] = $_POST['username'];
}


?>

Escaping output is the process by which you prepare data to be sent to
some external system. The client is the most common, since that's where
standard out goes, and databases are probably the second most common.
The process of escaping does modify data, but only in an attempt to
preserve it. The escaping process should preserve data in the sense that
any characters that might be interpreted by the external system are
represented with an escaped syntax. For example, this is one way to
escape a username (that has already been filtered as demonstrated above)
for use with a MySQL query:

<?php

$mysql = array();

$mysql['username'] = mysql_real_escape_string($clean['username']);

$query = "SELECT *
FROM profile
WHERE username = '{$mysql['username']}'";

$result = mysql_query($query);

?>

I left out basic error checking and such, but hopefully this makes the
escaping part clear.

I don't recommend skipping either of these two crucial steps, but
escaping can help protect you against weak or broken filtering. Because
there are built-in escaping functions for most external systems, you
should rely on these where possible.

Hope that helps.

Chris


--
Chris Shiflett
Brain Bulb, The PHP Consultancy
http://brainbulb.com/

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация