In this article we will pass a parameter to a PHP script via a URL, and we will get a little more sophisticated in our conditionals and regular expressions.
One problem with accepting parameters is that there are often security issues. It is very important to ensure that the parameters passed by the user conform exactly to what you expect. Use regular expressions and other methods to clean up the data before you operate on it. As an example of why this is important, say you had a user input their favorite color. You then echoed back their favorite color. What if, instead of their favorite color, they entered a path name? Depending on how your server and software was configured, you might end up returning the contents of a file, rather than their favorite color. Maybe their favorite color really was your password file? 🙂 Anyway, be very, very paranoid about what you do with the data that users enter in to your system.
One way to pass a parameter to a PHP program is via a URL. Simply tag a ?variable=value on to the end of the URL. The PHP program will interpret the variable as $variable, with the value of value.
The example program below will accept a parameter decin and convert the parameter to binary with pretty LEDs:
<html> <head> <title>Decimal To Binary</title> </head> <body bgcolor=000000> <?php echo "<font color=ffffff>"; $intrim=preg_replace("/\D/","",$decin); if($intrim > 65535) $intrim=65535; else if ($intrim < 0) $intrim=0; $bin=decbin($intrim); echo "Decimal ".$intrim." in binary:<br /><br />"; for($i=0; $i<strlen($bin);$i++){ if (substr($bin,$i,1) == "1") echo "<img src=led2.jpg align=left border=0 >"; else echo "<img src=led2off.jpg align=left border=0 >"; } ?> </body> </html> |
Simply replace the 14 with other values in the URL to convert other numbers. [note: this isn’t very secure and requires register_globals to be on] The preg_replace command replaces all non-digits with nothing and puts the value in the variable $intrim. We then limit the numbers to a 0-16 bit number (0-65535). The second if clause that sets $intrim=0 if $inttrim < 0 is probably redundant, since any negative sign is trimmed. The concern here was that if a very large number was entered, the value might wrap and become negative. It could be. If not with this version of PHP, then maybe others. Remember, be very paranoid. If you can code exactly what your limits are, do it. Maybe you have extra code, but security, here, is more important than brevity. The decbin function converts the number in decimal to a binary string. The strlen function finds the length of the string, and the substr function returns a particular character in the string as we loop from the first character through the last. As we loop through the string, we just echo the HTML for displaying an LED that is glowing if the value is 1, and display an LED that is not glowing if the value is 0. For more info on the functions available in PHP, click here.