Checking the form and the picture
Never trust what arrives from a form. First, the empty field. PHP has a function empty(), but it treats the text "0" as empty, so a term “0” would be refused. Safer is to trim the spaces and compare with an empty string: trim($term) !== ''. Second, a missing entry. If no file was chosen, $_FILES['picture']['name'] may not exist; the operator ?? gives a default: $_FILES['picture']['name'] ?? ''. The sign @, which some books use, only hides error messages; it is not a variable and it does not solve anything. Third, the picture name. A visitor’s file may be called ../../x.php; basename keeps only x.php. Then check the extension against a short list. Do not accept any file just because it is a file. A server also limits the size of an upload; if an example size is needed, 1 MB means 1,024 KB.
| Check | Code | Why |
|---|---|---|
| field not empty | trim($term) !== '' | empty("0") would refuse a term 0 |
| entry may be missing | $_FILES['picture']['name'] ?? '' | no warning if no file was chosen |
| safe file name | basename($name) | drops folders such as ../../ |
| expected ending | in_array($ext, [...]) | only picture files |
1<?php 2var_dump(empty("0"), empty(""), empty("a"), isset($nothing)); 3?>
bool(true) bool(true) bool(false) bool(false)
1<?php 2$term = trim(" router "); 3$trans = trim(" "); 4var_dump($term !== '', $trans !== ''); 5?>
bool(true) bool(false)
1<?php 2echo basename("../../x.php"), " ", basename("pic/router.webp"); 3?>
x.php router.webp
1<?php 2$name = "router.webp"; 3$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION)); 4var_dump(in_array($ext, ["webp", "png", "jpg"])); 5?>
bool(true)
1<?php 2$_FILES = []; 3$name = $_FILES['picture']['name'] ?? ''; 4var_dump($name); 5?>
string(0) ""
For each value below say what happens in the three checks (trim, basename, extension list): “ router ”, “ ”, “../pic/cat.webp”, “run.exe”. Then write the PHP condition that must be true before a term with a picture is saved.