I don’t know how many times I’ve stumbled across PHP code for generating random strings and numbers that aren’t random at all.
Take this example that I just found for instance:
<?php
...
$RandomStr = md5(microtime());
...
?>
Statement from the author: “…[md5 (microtime ())] use to generate the random string…”. [source]
So very wrong… I can predict the time and hence I can predict the outcome of that piece of code. That’s not random.
If you have a look at the website where I found this you can of course argue that the above snippet would be sufficient and maybe it is enough to fool most bots but it’s still not random and that’s my point.
If you wonder about the definition of Random I think wikipedia is doing quite a good job at it.
2008/12/09 17:02 | PHP | Trackback | 2 Comments »
sprintf is very often used in conjunction with mysql_real_escape_string to create secure MySQL queries with user embedded user input. I myself use this technique all the time and have found a very good and comfortable solution to work with.
The other day I stumbled across an interesting problem. Every now and then you tend to write MySQL queries with the ‘LIKE’ command:
mysql_query("SELECT field FROM table WHERE field LIKE '%keyword%'");
With the sprintf this would translate into:
$sKeyWord = 'keyword';
mysql_query(sprintf("SELECT field FROM table WHERE field LIKE '%%s%'", array($sKeyWord));
The code written above wouldn’t work. The ‘%’ is sprintf’s indicator that ‘here comes something that I should replace with something else’. It makes sense that my piece of code above would fail since I have 3x% and only one literal to describe the type of input.
I’d never run into this before so I opened the PHP manual to look for the proper syntax to tell sprintf that I actually want the ‘%’ to be interpreted as a ‘%’ and nothing else. Would you believe I didn’t find an answer? Well, I didn’t.
When PHP.net failed me I went to Google and came up empty once again. I figured it was a bit weird but I began wokring on the last resort for developers: trial & error.
After a lot of frustration and soul searching I found the answer to my question and, of course, it was so simple that it took me some time to think of it:
$sKeyWord = 'keyword';
mysql_query(sprintf("SELECT field FROM table WHERE field LIKE '%%%s%%'", array($sKeyWord));
The solution is to type the ‘%’ twice such as ‘%%’ so the snippet above did the trick. Hopefully this post might save someone else some time, or maybe I’m just that stupid, I don’t know.
PS. The answer to the problem can be found on PHP.net but only if you look hard enough and know what you’re looking for, I didn’t so I missed it.
2008/07/21 22:23 | PHP - Programming | Trackback | 1 Comment »