Casting to string before db query - secure?

As the title suggests, I’m wondering if casting a slug to a string before attempting a mysql db lookup is a secure enough approach? Speaking to another developer about it and he thinks my ctype_alnum check isn’t necessary, as a string cast would be sufficient! What do you guys suggest?

Are you using the mysql_ functions? Then you should pass the string through mysql_real_escape_string() before using it in a query.

Have you considered passing on to PDO ?

what’s in the slug and where has it come from - user input?

Each page on the site (CMS driven) will have a unique slug. I have a controller which will pass the slug in the request to a model, which will try to load a page from the db with the corresponding slug. I’m using an ORM which automatically escapes all values - on top of this I just wanted to check what else I should validate about the slug before trying the db query.

If your ORM is escaping the values correctly then you should have nothing to worry about.

If you have indexed the slug column correctly and you still feel the db is being put under undue duress because of repeated bad slug attempts then you could run the incoming slug against a regex.

Something like:

$str = "128abc-"; // letters numbers and a dash only > 4 chars and < 20 chars
if( preg_match("#^[a-z0-9-]{4,20}$#i", $str) ) {
// go ahead and do a lookup

// show some kind of default value


You might well feel though that running a regex against every incoming slug would be slower than having to do the occasional wasteful db lookup - and you might well be right. Only you can tell whether this is worth bothering with.


I should point out of course, that this check could be part of your .htaccess mod_rewrite rule …