Tracing four cases, and making the page safer
Now trace the page with the four choices and also with no Apply at all. The lamp is lit only for on and on. The page works, but it trusts what it receives. A browser can send any text, not only the options we offered: a visitor, or another program, could send maybe or ON. The page copies the text without checking, so the result depends on text we never planned for. A safer version keeps a list of the allowed values, on and off. If the received value is in the list it is used, otherwise it is replaced by off. The check uses === so that only exactly on and off are accepted, and ?? gives an empty text when a value is missing. The function lamp does all this and returns the two accepted choices and the lamp. One more slip of the book’s page is worth knowing: if the lamp itself is a clickable picture, clicking it sends the form without the Apply button’s name, so the page forgets the choices and shows the start state.
| Value received | The safer page uses |
|---|---|
| on | on |
| off | off |
| maybe | off |
| ON | off |
| (missing) | off |
| list1 | list2 | The page says |
|---|---|---|
| off | off | The lamp is unlit. |
| on | off | The lamp is unlit. |
| off | on | The lamp is unlit. |
| on | on | The lamp is lit. |
| (no Apply) | (no Apply) | The lamp is unlit. |
1function lamp(array $post): string { 2 $allowed = ["on", "off"]; 3 $first = "off"; 4 $second = "off"; 5 $state = "unlit"; 6 if (isset($post['apply'])) { 7 $first = in_array($post['list1'] ?? "", $allowed, true) ? $post['list1'] : "off"; 8 $second = in_array($post['list2'] ?? "", $allowed, true) ? $post['list2'] : "off"; 9 $state = ($first === "on" && $second === "on") ? "lit" : "unlit"; 10 } 11 return "$first $second $state"; 12} 13 14echo lamp([]), "\n"; 15echo lamp(['apply' => 'Apply', 'list1' => 'on', 'list2' => 'on']), "\n"; 16echo lamp(['apply' => 'Apply', 'list1' => 'on', 'list2' => 'off']), "\n"; 17echo lamp(['apply' => 'Apply', 'list1' => 'maybe', 'list2' => 'on']);
off off unlit on on lit on off unlit off on unlit
Trace the safer function on paper for these calls: Apply with list1 = off and list2 = on; Apply with ON and ON; Apply with only list2 = on; and a call with no Apply. Write the returned text for each.