☰ خطة العام · تكنولوجيا المعلومات والاتصالات (بالإنجليزية)

The converter as a PHP web page

الأسبوع 7 · الوحدة ١ الموضوع الثالث: محوّل الأعداد كصفحة ويب بلغة PHP: النموذج وأدوات التحكم وكود PHP وعرض النتيجة · 3 دروس
3

Showing the result, and checking the input

ICT Secondary 3 Term 1, Unit 1, Topic 3: pp. 37–50
GoalPrint the results with echo, see what bad input does, and make the page safer by checking the input before converting.
New words
input validation · checking typed text before using itpreg_match · tests whether a text fits a pattern, for example only the symbols 0 and 1htmlspecialchars · turns characters such as < and ' into harmless text before the page prints themTypeError · the error PHP raises when a function gets a value of the wrong type; the page stops
Explanation

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.

SystemAllowed symbolsLongest text
binary0 and 132 symbols
decimal0 to 99 digits
hexadecimal0 to 9, A to F, a to f8 symbols
Worked examples
Php
1try {
2    echo decbin("abc");
3} catch (TypeError $error) {
4    echo $error->getMessage();
5}
Output
decbin(): Argument #1 ($num) must be of type int, string given
What PHP 8 does with a wrong text on the unchecked page. Here is the first case, caught with try and catch so that we can read the message.
ButtonTypedWhat the unchecked page does
decimalabcthe page stops with a TypeError
binary102reads only 10, so it shows decimal 2; the binary line shows 102
hexadecimalxyzshows decimal 0
decimal-3shows 64 binary digits: sixty-one 1s followed by 101
The other bad entries, on the unchecked page. The page also shows whatever was typed as the binary result when the binary button is pressed, so wrong digits appear as “binary”.
Php
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");
Output
1011 11 B
1010000000 640 280
1111111 127 7F
invalid input
invalid input
A safer converter: one function that checks the text with a pattern first and returns invalid input if it does not fit. The output lines come from running it.
Php
1echo htmlspecialchars("5' x");
Output
5&#039; x
htmlspecialchars before printing typed text back. The apostrophe becomes a harmless code.
Class activity

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.

Practice
1
What does decbin("abc") do in PHP 8?
2
Why is 102 a bad entry for the binary button?
3
What does htmlspecialchars do?
4
Which pattern idea fits a hexadecimal entry?