Showing the result, and checking the input
A result appears in the page by echo inside a paragraph, such as <p>Decimal: <?php echo $dec; ?></p>. The trouble is that the visitor can type anything and our page does not check. In PHP 8, decbin("abc") raises a TypeError and the page stops; bindec("102") ignores the character 2, reads only 10 and returns 2, and depending on the settings PHP also prints a Deprecated notice; hexdec("xyz") returns 0. So the rule is: never trust typed text, check it first. A pattern says what is allowed. For binary, only 0 and 1 and at most 32 symbols; for decimal, digits only and at most nine; for hexadecimal, 0 to 9 and A to F in either case and at most eight. If the text does not fit, the page says invalid input and does not convert. Second, typed text that is printed back into the page must go through htmlspecialchars, which turns special characters into harmless text. We use only one harmless case: an apostrophe.
| System | Allowed symbols | Longest text |
|---|---|---|
| binary | 0 and 1 | 32 symbols |
| decimal | 0 to 9 | 9 digits |
| hexadecimal | 0 to 9, A to F, a to f | 8 symbols |
1try { 2 echo decbin("abc"); 3} catch (TypeError $error) { 4 echo $error->getMessage(); 5}
decbin(): Argument #1 ($num) must be of type int, string given
| Button | Typed | What the unchecked page does |
|---|---|---|
| decimal | abc | the page stops with a TypeError |
| binary | 102 | reads only 10, so it shows decimal 2; the binary line shows 102 |
| hexadecimal | xyz | shows decimal 0 |
| decimal | -3 | shows 64 binary digits: sixty-one 1s followed by 101 |
1function convert(string $text, string $from): string { 2 $text = trim($text); 3 $patterns = [ 4 'bin' => '/^[01]{1,32}$/', 5 'dec' => '/^[0-9]{1,9}$/', 6 'hex' => '/^[0-9A-Fa-f]{1,8}$/', 7 ]; 8 if (!isset($patterns[$from]) || !preg_match($patterns[$from], $text)) { 9 return "invalid input"; 10 } 11 $dec = match ($from) { 12 'bin' => bindec($text), 13 'dec' => (int)$text, 14 'hex' => hexdec($text), 15 }; 16 return decbin($dec) . " " . $dec . " " . strtoupper(dechex($dec)); 17} 18 19echo convert("1011", "bin"), "\n"; 20echo convert("640", "dec"), "\n"; 21echo convert("7f", "hex"), "\n"; 22echo convert("1021", "bin"), "\n"; 23echo convert("", "dec");
1011 11 B 1010000000 640 280 1111111 127 7F invalid input invalid input
1echo htmlspecialchars("5' x");5' x
Decide what the checked converter does with each entry and say why: (a) 1021 with the binary button, (b) 7f with the hexadecimal button, (c) 12 34 (with a space) with the decimal button, (d) 640 with the decimal button. For the accepted ones, give the three results.