Minulý týždeň PHP skladalo stránky z premenných (variables), ktoré si napísal do kódu. Dnes prídu údaje od používateľa: vyplní form, stlačí Registrovať a tvoj PHP ich dostane, skontroluje, vypočíta z nich niečo a bezpečne vypíše. Naučíš sa, čo je $_POST, ako sa údaje overujú (validation), čo je XSS a ako sa pred ním chrániš, a ako sa form spracuje v tom istom súbore tak, aby používateľ nemusel všetko písať znova.
Last week PHP built pages from variables you wrote into the code. Today the data comes from the user: they fill in a form, press Register and your PHP receives the data, checks it, calculates something from it and prints it safely. You will learn what $_POST is, how data is verified (validation), what XSS is and how you protect yourself against it, and how a form is processed in the same file so that the user does not have to type everything again.
TeóriaTheory
Takto vyzerá form, ktorý si urobil v cv03 a ktorý máš v cv04 v web/content/register.php:
Form z cv04 v prehliadači.
A toto je jeho zdrojový kód. Oproti cv04 sú zmenené len dve veci: method="get" na method="post" a action na ../practice/process.php. Všetko ostatné zostáva, aj anglické name a value (since, grade, style, interest[], consent; hodnoty toprope, lead, course, yes), ktoré máš od cv02.
<form method="post" action="../practice/process.php">
<div class="mb-3">
<label for="name" class="form-label">Meno a priezvisko</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">E-mail</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="since" class="form-label">Leziem od roku</label>
<input type="number" class="form-control" id="since" name="since" min="1950" max="2026">
</div>
<div class="mb-3">
<label for="date" class="form-label">Dátum prvej návštevy</label>
<input type="date" class="form-control" id="date" name="date">
</div>
<div class="mb-3">
<label for="grade" class="form-label">Najvyššia vylezená obťažnosť</label>
<select class="form-select" id="grade" name="grade" required>
<option value="">-- vyber --</option>
<option value="5a">5a (V)</option>
<option value="5c">5c (VI)</option>
<option value="6a">6a (VI+)</option>
<option value="6b">6b (VII)</option>
</select>
</div>
<fieldset class="mb-3">
<legend class="fs-6">Štýl lezenia</legend>
<div class="form-check">
<input class="form-check-input" type="radio" name="style" id="style_toprope" value="toprope" checked>
<label class="form-check-label" for="style_toprope">s horným istením</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="style" id="style_lead" value="lead">
<label class="form-check-label" for="style_lead">s dolným istením</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="style" id="style_boulder" value="boulder">
<label class="form-check-label" for="style_boulder">bouldering</label>
</div>
</fieldset>
<fieldset class="mb-3">
<legend class="fs-6">Mám záujem o</legend>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="interest[]" id="interest_course" value="course">
<label class="form-check-label" for="interest_course">kurz pre začiatočníkov</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="interest[]" id="interest_rental" value="rental">
<label class="form-check-label" for="interest_rental">požičanie výstroja</label>
</div>
</fieldset>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" name="consent" id="consent" value="yes" required>
<label class="form-check-label" for="consent">Súhlasím s prevádzkovým poriadkom</label>
</div>
<div class="mb-3">
<label for="message" class="form-label">Správa</label>
<textarea class="form-control" id="message" name="message" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Registrovať</button>
</form>
Čo sa po stlačení Registrovať prenesie, kam a ako to PHP spracuje, je ďalej.
Čo sa stane po odoslaní form
V cv03 si odoslal form a údaje sa objavili v adresnom riadku: form.html?name=Jana&email=…. To bola metóda GET: údaje cestujú v adrese. Dnes form prepneme na metódu POST: údaje cestujú v tele requestu a v adrese ich nevidno.
| GET | POST | |
|---|---|---|
| kde sú údaje | v adrese za ? |
v tele requestu, v adrese nie |
| dá sa adresa poslať kamarátovi | áno, aj s údajmi | nie, údaje v nej nie sú |
| na čo sa hodí | hľadanie, filter, stránkovanie | odoslanie údajov: registrácia, prihlásenie, správa |
| v PHP | $_GET |
$_POST |
Form má dva rozhodujúce atribúty (attributes): method hovorí, ako údaje pošle, action hovorí, ktorému súboru.
<form method="post" action="../practice/process.php">
Cvičný súbor process.php je v priečinku practice/, form je vo web/content/, preto cesta ../practice/process.php: .. je nadradený priečinok, ako v termináli. Prehliadač po stlačení tlačidla (button) pošle request „spusti process.php a tu máš údaje”. sigma spustí PHP v process.php, to údaje spracuje a výsledok ide v response späť do prehliadača. Ak je action="" (prázdny), request ide na tú istú stránku, z ktorej form odišiel; to využijeme na konci.
Odoslanie form metódou POST.
process.php, údaje v tele requestu
process.php; údaje sú v $_POST
Viac: W3Schools: PHP Form Handling
$_POST je asociatívne array
Všetko, čo prišlo z form, má PHP pripravené v array $_POST. Key je name poľa (field) form, value je to, čo používateľ zadal. Je to presne asociatívne array z minulého týždňa, len ho nenaplnil tvoj kód, ale prehliadač. $_POST je k dispozícii v každom súbore bez deklarácie (hovorí sa mu superglobálne array, superglobal). Rovnaké array $_GET vzniká pri metóde GET.
Najprv form. Takto vyzerá vyplnený, tesne pred stlačením Registrovať:
Vyplnený form pred odoslaním.
Zdrojový kód je na začiatku Teórie; všimni si v ňom name každého field a value pri možnostiach: presne tieto názvy a hodnoty odídu na server.
Po stlačení Registrovať prehliadač pošle request POST a na serveri je v $_POST toto. Najrýchlejší pohľad dnu je print_r (z minulého týždňa: vypíše celé array aj s key). Vloží sa do značky (tag) <pre>: to je HTML tag pre predformátovaný text, prehliadač v nej zachová konce riadkov a medzery, inak by výpis zlepil do jedného riadka.
<pre><?php print_r($_POST); ?></pre> <!-- pre: zachová riadky výpisu -->
Takto to vyzerá v prehliadači po odoslaní vyplneného form.
Array ( [name] => Jana Nováková [email] => jana@example.com [since] => 2021 [date] => 2021-09-18 [grade] => 6a [style] => lead [interest] => Array ( [0] => course [1] => rental )
[consent] => yes
[message] =>
)
Tri veci si všimni:
- Všetko je text (
string), aj rok2021. Prehliadač posiela len text.var_dump($_POST['since'])ukážestring(4) "2021". - Skupina checkboxov
interest[]prišla ako vnorené array (ArrayvnútriArray). Preto sa vnamepíšu hranaté zátvorky. - Nezaškrtnutý checkbox nepríde vôbec: key
consentv array nie je. Čo s tým, o chvíľu.
Druhý spôsob, ako vidieť všetko naraz, je cyklus (loop) foreach z minulého týždňa, ktorý prejde $_POST key po key:
<dl> <!-- dl: zoznam dvojíc názov – hodnota -->
<?php foreach ($_POST as $key => $value): ?> <!-- $key = name field, $value = čo prišlo -->
<dt><?= $key ?></dt> <!-- dt: názov -->
<dd><?= is_array($value) ? implode(', ', $value) : $value ?></dd> <!-- dd: hodnota -->
<?php endforeach; ?>
</dl>
Čo je tu nové: <dl> je HTML zoznam dvojíc, <dt> je názov (term) a <dd> jeho hodnota (description); na výpis „názov: hodnota” sa hodí lepšie ako tabuľka (table). is_array($value) je funkcia, ktorá vráti true, keď je hodnota array (naša skupina checkboxov), inak false. Podmienka (Condition) ?: z minulého týždňa potom vyberie: pre array implode(', ', $value) (z minulého týždňa: spojí prvky (elements) do jedného textu s čiarkou), pre obyčajnú hodnotu priamo $value. Bez implode by echo z array vypísal len slovo Array a hlásenie Array to string conversion.
Takto to vyzerá v prehliadači.
- name
- Jana Nováková
- jana@example.com
- since
- 2021
- date
- 2021-09-18
- grade
- 6a
- style
- lead
- interest
- course, rental
- consent
- yes
- message
Viac: PHP: $_POST, W3Schools: HTML dl
Z $_POST do variables
Pravidlo na celý semester: na začiatku súboru prenes každú hodnotu z $_POST do variable s rovnakým názvom a ďalej pracuj už len s variables. Kód je kratší, čitateľnejší a na jednom mieste vidíš, čo z form používaš.
$name = trim($_POST['name'] ?? '');
Tento riadok čítaj sprava doľava:
$_POST['name']: hodnota pod keyname, to, čo bolo v field Meno.?? '': operátor??(null coalescing) znamená „a ak taká hodnota nie je, použi to, čo je za mnou”. Keby keynamev$_POSTchýbal (súbor otvorený bez form, nezaškrtnutý checkbox, preklep vname), bez??by PHP hlásiloWarning: Undefined array key "name". S??dostaneš prázdny text a nič nespadne.trim(...): funkcia odstráni medzery (aj tabulátory a konce riadkov) zo začiatku a konca textu.trim(' Jana ')dá'Jana'. Používateľ, ktorý omylom napíše do mena len medzery, tak pošle prázdny text, a prázdny text vieme skontrolovať.$name =: výsledok sa uloží do variable.
Ostatné fields podľa druhu:
$name = trim($_POST['name'] ?? ''); // text: trim a náhrada ''
$email = trim($_POST['email'] ?? '');
$since = (int) ($_POST['since'] ?? 0); // číslo: z textu '2021' urobí (int) číslo 2021; náhrada 0
$date = $_POST['date'] ?? ''; // dátum príde ako text '2021-09-18', zatiaľ necháme
$grade = $_POST['grade'] ?? ''; // select: value vybranej možnosti, napr. '6a'
$style = $_POST['style'] ?? ''; // radio: value označenej možnosti
$interest = $_POST['interest'] ?? []; // skupina checkboxov: array; náhrada prázdne array []
$consent = $_POST['consent'] ?? ''; // jeden checkbox: 'yes', alebo nič, keď nebol zaškrtnutý
$message = trim($_POST['message'] ?? '');
(int) pred hodnotou je pretypovanie z minulého týždňa: z textu '2021' urobí číslo 2021, z textu 'abc' urobí 0. Bez neho by sa rok porovnával ako text. Pre checkboxy je náhrada [], prázdne array, aby implode a loop fungovali, aj keď nič nebolo zaškrtnuté.
Od tohto miesta píšeme $name, nie $_POST['name']. Výpis po jednom:
<p>Meno: <?= $name ?></p> <!-- obyčajná hodnota -->
<p>Záujem: <?= implode(', ', $interest) ?></p> <!-- array spojené čiarkou; prázdne array dá prázdny text -->
<p>Súhlas: <?= $consent == 'yes' ? 'áno' : 'nie' ?></p> <!-- condition ?: z minulého týždňa -->
Takto to vyzerá v prehliadači.
Meno: Jana Nováková
Záujem: course, rental
Súhlas: áno
Pozor: takto vypísať cudzie hodnoty bez ošetrenia je nebezpečné. Prečo, príde v časti o XSS; v cvičnom súbore je to na pozretie v poriadku, na web to nepatrí.
Viac: PHP: Null coalescing operator, PHP: trim
Conditions naplno: if, elseif, else
Minulý týždeň si mal if s jednou vetvou. Kontrola údajov potrebuje viac vetiev:
if ($name == '') { // 1. prázdne meno?
$errors['name'] = 'Meno je povinné.';
} elseif (mb_strlen($name) < 3) { // 2. ak nie je prázdne: je kratšie ako 3 znaky?
$errors['name'] = 'Meno má mať aspoň 3 znaky.';
} elseif (mb_strlen($name) > 60) { // 3. ak ani to: je dlhšie ako 60?
$errors['name'] = 'Meno je pridlhé.';
} // inak je meno v poriadku, nič sa nestane
PHP ide zhora: prvá splnená condition sa vykoná, ostatné vetvy preskočí. else na konci (bez conditions) zachytí všetko, čo nesplnilo nič predtým. mb_strlen je z minulého týždňa (počíta znaky). Conditions sa spájajú: && (a zároveň), || (alebo), ! pred condition ju obráti (nie). Zátvorky určujú poradie.
| Zápis | Pravda, keď | Príklad |
|---|---|---|
$a == '' |
text je prázdny | po trim prázdne meno |
$a != 'yes' |
hodnota sa nerovná | $consent != 'yes': súhlas nebol zaškrtnutý |
empty($a) |
prázdny text, 0, prázdne array |
empty($interest): žiadny checkbox |
isset($a['x']) |
key x v array existuje |
isset($errors['name']): field meno má chybu |
!$a |
$a neplatí |
!isset($errors['name']): meno je v poriadku |
$a && $b |
obe platia | $since < 1950 && $since != 0 |
$a \|\| $b |
aspoň jedna platí | $since < 1950 \|\| $since > 2026: rok mimo rozsahu |
Viac: PHP: if, elseif, else, W3Schools: PHP if…else
Práca s dátumom a časom
Z field <input type="date"> príde dátum vždy ako text v tvare RRRR-MM-DD, bez ohľadu na to, ako ho prehliadač ukázal: var_dump($date) dá string(10) "2021-09-18". Ak dátum chceš len vypísať alebo si ho poznačiť, text stačí. Ak s ním chceš počítať (koľko dní zostáva, či je v minulosti), musíš ho previesť na číslo.
PHP počíta s časom ako s jedným číslom: počet sekúnd od 1. januára 1970 (timestamp). Prevod oboma smermi robia dve funkcie:
strtotime($text)(string to time) prevedie text s dátumom na timestamp.strtotime('2021-09-18')dá1631923200. Keď text nie je dátum (strtotime('včera v noci'),strtotime('')), funkcia vrátifalse. Tým sa dá dátum skontrolovať: ak je výsledokfalse, používateľ dátum nezadal.date($format, $timestamp)prevedie timestamp späť na text pre človeka podľa formátu. Formát je text z písmen:ddeň,mmesiac,Yrok,lnázov dňa (po anglicky, slovenčinu PHP nemá).date('d. m. Y', 1631923200)dá18. 09. 2021. Keď druhý parameter vynecháš,datepoužije teraz:date('d. m. Y')je dnešný dátum,date('Y')dnešný rok (ako minulý týždeň v pätičke (footer)). Pozor,datevracia text; keď chceš s rokom počítať, napíš(int) date('Y').time()je timestamp práve teraz.
Keď sú oba dátumy čísla, dajú sa odčítať. Rozdiel je v sekundách; deň má 24 × 60 × 60 = 86 400 sekúnd.
$visit = strtotime($date); // text '2021-09-18' na timestamp
$days = (time() - $visit) / 86400; // dni od prvej návštevy do dnes, desatinné (1858.6)
$days = floor($days); // floor zaokrúhli nadol na celé (1858); ceil zaokrúhli nahor
$years = (int) date('Y') - $since; // dnešný rok ako číslo mínus zadaný rok
echo 'Od prvej návštevy prešlo ' . $days . ' dní. Lezieš už ' . $years . ' rokov.';
Takto to vyzerá v prehliadači.
Porovnať dátumy znamená porovnať čísla: strtotime($date) > time() je pravda, keď je dátum v budúcnosti; prvá návšteva v budúcnosti byť nemôže. Porovnanie textov '2021-09-18' < '2026-9-1' by dalo nezmysel.
| Zápis | Čo robí | Výsledok |
|---|---|---|
strtotime('2021-09-18') |
text na timestamp | 1631923200 |
strtotime('nezmysel') |
text nie je dátum | false |
time() |
teraz ako timestamp | 1792454400 |
date('d. m. Y', $visit) |
timestamp na text | 18. 09. 2021 |
date('l', $visit) |
názov dňa | Saturday |
date('d. m. Y') |
bez timestampu: dnes | 20. 10. 2026 |
(int) date('Y') |
dnešný rok ako číslo | 2026 |
floor(1858.6), ceil(1858.6) |
nahor, nadol | 1858, 1859 |
Viac: PHP: strtotime, PHP: date
Dôveruj, ale preveruj: validácia (validation)
V cv03 si form dal required, type="email", min a max. Prehliadač podľa nich nepustí prázdne field ani rok 1800. To je pohodlie pre používateľa, nie ochrana: stlač F12, nájdi <input> a slovo required zmaž; form odíde prázdny. Kto chce, pošle serveru čokoľvek aj bez prehliadača. Preto platí: server kontroluje všetko, vždy, aj keď to kontroloval prehliadač. Kontrole údajov sa hovorí validácia (validation).
required sa dá zmazať jedným dvojklikom. Prehliadač potom pustí prázdne pole.
Chyby budeme zbierať do array. Na začiatku vytvoríme prázdne array $errors = [];. Bude asociatívne: key je názov field, value je text chyby pre človeka, napríklad $errors['email'] = 'Zadaj platný e-mail.';. Keď je field v poriadku, do array sa nič nezapíše. Na konci count($errors) (z minulého týždňa: počet elements) povie, koľko chýb sa našlo; count($errors) == 0 znamená „všetko v poriadku”. A pretože key je názov field, neskôr vieme hlášku ukázať priamo pri tom field.
Ešte dve funkcie, ktoré potrebujeme:
filter_var($hodnota, $filter)skontroluje hodnotu podľa zadaného filtra. FilterFILTER_VALIDATE_EMAILje pripravený v PHP a kontroluje tvar e-mailu (niečo@niečo.niečo). Keď je hodnota v poriadku, funkcia ju vráti; keď nie, vrátifalse.filter_var('jana@example.com', FILTER_VALIDATE_EMAIL)dá'jana@example.com',filter_var('jana@', FILTER_VALIDATE_EMAIL)dáfalse. V condition s!pred funkciou:if (!filter_var($email, FILTER_VALIDATE_EMAIL))čítaj „ak e-mail nie je platný”.in_array($hodnota, $array)vrátitrue, keď sa hodnota v array nachádza. Select a radio majú v HTML pevný zoznam možností, ale server dostane len text a ten mohol ktokoľvek prepísať. Zoznam možností preto drž v PHP ako asociatívne array (key =valuez HTML, value = text pre človeka):
$grades = ['5a' => '5a (V)', '5c' => '5c (VI)', '6a' => '6a (VI+)', '6b' => '6b (VII)'];
Kontrolovať treba key. array_keys($grades) urobí z asociatívneho array obyčajné array samých key: ['5a', '5c', '6a', '6b']. A in_array($grade, array_keys($grades)) je true, keď je $grade jeden z nich; s ! pred tým: „ak obťažnosť nie je zo zoznamu”. in_array('6a', ['5a', '5c', '6a', '6b']) dá true, in_array('9z', …) dá false. To isté array o chvíľu vypíše <option> loop, takže zoznam možností je v kóde len raz.
Čo sa kontroluje a ako (všetko na variables z časti „Z $_POST do variables”):
| Čo | Ako | Zápis | Chyba, keď |
|---|---|---|---|
| povinné field | prázdny text po trim |
$name == '' |
používateľ nezadal nič alebo len medzery |
| dĺžka textu | mb_strlen |
mb_strlen($name) < 3 |
'Jo' |
filter_var |
!filter_var($email, FILTER_VALIDATE_EMAIL) |
'jana@', '' |
|
| číslo v rozsahu | po (int) porovnať |
$since < 1950 \|\| $since > (int) date('Y') |
1800, 0 (prázdne field) |
| dátum | strtotime |
strtotime($date) === false |
'', 'abc' |
| dátum nie je v budúcnosti | porovnať timestampy | strtotime($date) > time() |
'2030-01-01' |
| hodnota zo zoznamu | in_array + array_keys |
!in_array($grade, array_keys($grades)) |
'', '9z' |
| checkbox súhlas | porovnať s value |
$consent != 'yes' |
nebol zaškrtnutý |
Celý blok kontrol je v Ukážke 2.
Viac: PHP: filter_var, PHP: in_array, PHP: array_keys
Ošetrenie výstupu: XSS
Skús do field Meno napísať <b>Jana</b> a odoslať. Vo výpise bude Jana tučným písmom: prehliadač dostal tag <b> a poslúchol ju. Teraz skús <script>alert('ahoj')</script>. Vyskočí okno. Do tvojej stránky práve niekto vložil svoj program.
Tomuto sa hovorí XSS (cross-site scripting): útočník vloží cez form alebo adresu kód, ktorý sa vykoná v prehliadači iných návštevníkov. Ukradne im prihlásenie, prepíše stránku, presmeruje ich inam. Stačí jedno neošetrené field.
Obrana je jedna funkcia: htmlspecialchars($text, ENT_QUOTES, 'UTF-8'). Zamení v texte päť znakov, ktoré majú v HTML význam, za ich zápis ako obyčajný znak: < na <, > na >, & na &, " na ", ' na '. Prehliadač ich potom zobrazí ako písmená a nevykoná. Z <b>Jana</b> sa stane <b>Jana</b> a na obrazovke vidíš doslova <b>Jana</b>.
Tri parametre: prvý je text; druhý ENT_QUOTES je konštanta (z minulého týždňa: pevná hodnota s menom), ktorá hovorí „zameň aj úvodzovky aj apostrofy”, bez nej by apostrof prešiel a v value='…' by rozbil attribute; tretí 'UTF-8' je kódovanie textu, bez neho sa môže pokaziť diakritika. Píš tie tri parametre vždy rovnako.
Pravidlo: každá hodnota, ktorú napísal používateľ, ide do HTML cez htmlspecialchars. Vždy, aj keď „vyzerá neškodne”.
<p>Meno: <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></p>
Čo sa nerobí: PHP má funkciu strip_tags, ktorá z textu zmaže všetky HTML tag. Zdá sa, že by stačilo ňou vstup „vyčistiť” a uložiť. Nerobí sa to: meno „O’Neil” alebo správa „ceny < 10 €” sú platné texty a mazaním by si ich poškodil; útočník navyše pozná zápisy, ktoré cez strip_tags prejdú. Vstup sa uloží taký, aký prišiel, a ošetruje sa každý výstup. Druhá časť bezpečnosti, útok cez databázu (SQL injection), príde s databázou.
Viac: PHP: htmlspecialchars, OWASP: Cross Site Scripting
Form, ktorý sa spracuje sám
process.php je dobrý na učenie, pre používateľa nie: pri chybe vidí hlásenie na inej stránke, musí sa vrátiť a písať všetko znova. Hotové weby to robia inak: form pošle údaje sám sebe (action=""), ten istý súbor ich skontroluje a buď ukáže zhrnutie, alebo form znova aj s chybami a s tým, čo už bolo vyplnené. Hovorí sa tomu samospracujúci form (self-processing form).
Ako súbor zistí, či ho niekto otvoril z menu, alebo mu prišiel odoslaný form? V superglobálnom array $_SERVER má PHP údaje o requeste; $_SERVER['REQUEST_METHOD'] je 'GET' pri otvorení z menu a 'POST' po odoslaní form.
V našom template je to content/register.php. Kostra, každý riadok s komentárom:
<?php
$errors = []; // prázdne array na chyby, key = field
$sent = $_SERVER['REQUEST_METHOD'] == 'POST'; // bool: true po odoslaní, false pri otvorení z menu
$name = trim($_POST['name'] ?? ''); // z $_POST do variables, vždy (pri otvorení sú prázdne)
// ... ostatné fields rovnako
$grades = ['5a' => '5a (V)', /* ... */]; // zoznamy možností ako v process.php
if ($sent) { // kontroly len po odoslaní
if ($name == '') { $errors['name'] = 'Meno je povinné.'; }
// ... ostatné kontroly presne ako v process.php
}
?>
<?php if ($sent && count($errors) == 0): ?> <!-- odoslané a bez chýb -->
<!-- zhrnutie: hodnoty cez htmlspecialchars -->
<?php else: ?> <!-- prvé otvorenie, alebo odoslané s chybami -->
<!-- form; fields dostanú späť hodnoty a hlášky -->
<?php endif; ?>
Pri prvom otvorení ($sent je false) sú variables prázdne a form čistý; po odoslaní s chybou majú variables to, čo používateľ napísal, a form to vráti do fields. Hovorí sa tomu form, ktorý si pamätá hodnoty (sticky form). Pre každý druh field je zápis iný:
input(text, email, number, date): attributevaluepredvyplní field. Dáme doň variable, ošetrenú, lebo je od používateľa:value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>"textarea: nemávalue, text sa píše medzi tag:<textarea …><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></textarea>select: vybraná<option>má attributeselected(slovo bez hodnoty). Condition?:vypíšeme slovoselected, keď savaluemožnosti rovná tomu, čo prišlo, inak nič:<option value="6a" <?= $grade == '6a' ? 'selected' : '' ?>>6a (VI+)</option>radio: označený má attributechecked, rovnako condition:<input type="radio" name="style" value="lead" <?= $style == 'lead' ? 'checked' : '' ?>>checkboxv skupine:$interestje array zaškrtnutých;in_arrayzistí, či je táto možnosť medzi nimi:<input type="checkbox" name="interest[]" value="course" <?= in_array('course', $interest) ? 'checked' : '' ?>>checkboxsúhlas:<?= $consent == 'yes' ? 'checked' : '' ?>
Aby si to nemusel písať pre každú <option> zvlášť, vypíše ich loop z array možností, ktoré už máš pre kontrolu:
<select class="form-select" id="grade" name="grade">
<option value="">-- vyber --</option>
<?php foreach ($grades as $key => $label): ?> <!-- $key = '6a', $label = '6a (VI+)' -->
<option value="<?= $key ?>" <?= $grade == $key ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
Z toho PHP vyrobí pre $grade = '6a' toto HTML:
<option value="">-- vyber --</option>
<option value="5a" >5a (V)</option>
<option value="5c" >5c (VI)</option>
<option value="6a" selected>6a (VI+)</option>
<option value="6b" >6b (VII)</option>
Rovnako radio z $styles a checkboxy z $interests. Zoznam možností je potom na jednom mieste: pridáš položku do array a je aj v kontrole, aj vo form.
Hlášku pri field ukáže Bootstrap. Má na to dve triedy (class) pre HTML: is-invalid na field urobí červený rámik a invalid-feedback je div s textom, ktorý je skrytý a Bootstrap ho zobrazí (červeným) len vtedy, keď field pred ním má is-invalid. PHP teda rozhodne len o tom, či slovo is-invalid do class napíše:
<input type="email" class="form-control <?= isset($errors['email']) ? 'is-invalid' : '' ?>" id="email" name="email"
value="<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>">
<div class="invalid-feedback"><?= $errors['email'] ?? '' ?></div>
isset($errors['email']) je true, keď kontrola zapísala chybu pre e-mail. Výsledné HTML pri chybe a bez chyby:
<!-- s chybou: rámik červený, text viditeľný -->
<input type="email" class="form-control is-invalid" id="email" name="email" value="jana@">
<div class="invalid-feedback">Zadaj platný e-mail.</div>
<!-- bez chyby: obyčajné field, prázdny div zostane skrytý -->
<input type="email" class="form-control " id="email" name="email" value="jana@example.com">
<div class="invalid-feedback"></div>
Takto to vyzerá v prehliadači po odoslaní so zlým e-mailom.
Ešte jedna vec: keď po odoslaní stlačíš F5, prehliadač sa spýta, či má údaje poslať znova. Je to normálne správanie pri POST; riešenie (presmerovanie) príde neskôr.
Viac: PHP: $_SERVER, Bootstrap: Validation, server side
Najčastejšie chyby a čo znamenajú
| Čo vidíš | Príčina | Riešenie |
|---|---|---|
Warning: Undefined array key "email" |
preklep v name form, alebo nezaškrtnutý checkbox |
name a key presne rovnako; z $_POST čítaj s ?? '' |
form „nič nerobí”, $_POST je prázdne |
chýba method="post", alebo field nemá name |
doplň method, každé field má name |
po odoslaní je adresa …?name=… |
method chýba, form išiel cez GET |
method="post" |
Array to string conversion |
checkbox skupina vypísaná ako text | implode(', ', $interest) |
| rok sa porovnáva zle | $_POST je text, porovnanie textov |
(int) pred porovnaním |
diakritika po htmlspecialchars je rozbitá |
chýba 'UTF-8' |
tri parametre vždy: ENT_QUOTES, 'UTF-8' |
| po oprave chyby sú fields prázdne | chýba value="…" s hodnotou |
pozri zoznam pamätania hodnôt |
select neukáže vybranú hodnotu |
selected je napísané napevno |
selected condition v loop |
strtotime vracia false |
dátum nie je v tvare RRRR-MM-DD |
field type="date", kontrola === false |
| F5 sa pýta na opätovné odoslanie | normálne pri POST | zatiaľ nič, stránku otvor z menu |
This is the form you made in cv03 and have in cv04 in web/content/register.php:
The form from cv04 in the browser.
And this is its source code. Compared with cv04 only two things changed: method="get" to method="post" and action to ../practice/process.php. Everything else stays, including the English name and value (since, grade, style, interest[], consent; the values toprope, lead, course, yes) you have had since cv02.
<form method="post" action="../practice/process.php">
<div class="mb-3">
<label for="name" class="form-label">Name and surname</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">E-mail</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="since" class="form-label">Climbing since</label>
<input type="number" class="form-control" id="since" name="since" min="1950" max="2026">
</div>
<div class="mb-3">
<label for="date" class="form-label">Date of the first visit</label>
<input type="date" class="form-control" id="date" name="date">
</div>
<div class="mb-3">
<label for="grade" class="form-label">Hardest grade climbed</label>
<select class="form-select" id="grade" name="grade" required>
<option value="">-- choose --</option>
<option value="5a">5a (V)</option>
<option value="5c">5c (VI)</option>
<option value="6a">6a (VI+)</option>
<option value="6b">6b (VII)</option>
</select>
</div>
<fieldset class="mb-3">
<legend class="fs-6">Climbing style</legend>
<div class="form-check">
<input class="form-check-input" type="radio" name="style" id="style_toprope" value="toprope" checked>
<label class="form-check-label" for="style_toprope">top rope</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="style" id="style_lead" value="lead">
<label class="form-check-label" for="style_lead">lead</label>
</div>
<div class="form-check">
<input class="form-check-input" type="radio" name="style" id="style_boulder" value="boulder">
<label class="form-check-label" for="style_boulder">bouldering</label>
</div>
</fieldset>
<fieldset class="mb-3">
<legend class="fs-6">I am interested in</legend>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="interest[]" id="interest_course" value="course">
<label class="form-check-label" for="interest_course">a beginners' course</label>
</div>
<div class="form-check">
<input class="form-check-input" type="checkbox" name="interest[]" id="interest_rental" value="rental">
<label class="form-check-label" for="interest_rental">gear rental</label>
</div>
</fieldset>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" name="consent" id="consent" value="yes" required>
<label class="form-check-label" for="consent">I agree with the house rules</label>
</div>
<div class="mb-3">
<label for="message" class="form-label">Message</label>
<textarea class="form-control" id="message" name="message" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
What is sent after pressing Register, where it goes and how PHP processes it, follows.
What happens after a form is submitted
In cv03 you submitted a form and the data appeared in the address bar: form.html?name=Jana&email=…. That was the GET method: the data travels in the address. Today we switch the form to the POST method: the data travels in the body of the request and is not visible in the address.
| GET | POST | |
|---|---|---|
| where the data is | in the address after ? |
in the body of the request, not in the address |
| can the address be sent to a friend | yes, with the data | no, the data is not in it |
| what it is for | search, filter, paging | sending data: registration, login, message |
| in PHP | $_GET |
$_POST |
A form has two decisive attributes: method says how it sends the data, action says to which file.
<form method="post" action="../practice/process.php">
The practice file process.php is in the practice/ folder and the form is in web/content/, hence the path ../practice/process.php: .. is the parent folder, as in the terminal. After the button is pressed the browser sends the request “run process.php and here is the data”. sigma runs the PHP in process.php, it processes the data and the result goes back to the browser in the response. If action="" (empty), the request goes to the same page the form was sent from; we will use that at the end.
Submitting a form with the POST method.
process.php, data in the request body
process.php; the data is in $_POST
More: W3Schools: PHP Form Handling
$_POST is an associative array
Everything that came from the form is ready in the array $_POST. The key is the name of the form field, the value is what the user entered. It is exactly the associative array from last week, only your code did not fill it, the browser did. $_POST is available in every file without declaration (it is called a superglobal array). The same array $_GET is created with the GET method.
First the form. This is what it looks like filled in, just before pressing Register:
The filled-in form before submitting.
The source code is at the beginning of the Theory; notice the name of every field and the value of the options in it: exactly these names and values go to the server.
After pressing Register the browser sends a POST request and on the server $_POST holds this. The quickest look inside is print_r (from last week: prints the whole array with its keys). It goes inside the <pre> tag: that is the HTML tag for preformatted text, the browser keeps the line breaks and spaces in it, otherwise it would glue the output into one line.
<pre><?php print_r($_POST); ?></pre> <!-- pre: keeps the lines of the output -->
This is what it looks like in the browser after submitting a filled-in form.
Array ( [name] => Jana Nováková [email] => jana@example.com [since] => 2021 [date] => 2021-09-18 [grade] => 6a [style] => lead [interest] => Array ( [0] => course [1] => rental )
[consent] => yes
[message] =>
)
Notice three things:
- Everything is text (
string), even the year2021. The browser sends only text.var_dump($_POST['since'])showsstring(4) "2021". - The checkbox group
interest[]arrived as a nested array (ArrayinsideArray). That is why the square brackets are written inname. - An unchecked checkbox does not arrive at all: the key
consentis not in the array. What to do about it, in a moment.
The second way to see everything at once is the foreach loop from last week, which goes through $_POST key by key:
<dl> <!-- dl: a list of pairs name – value -->
<?php foreach ($_POST as $key => $value): ?> <!-- $key = name of the field, $value = what arrived -->
<dt><?= $key ?></dt> <!-- dt: name -->
<dd><?= is_array($value) ? implode(', ', $value) : $value ?></dd> <!-- dd: value -->
<?php endforeach; ?>
</dl>
What is new here: <dl> is an HTML list of pairs, <dt> is the name (term) and <dd> its value (description); for printing “name: value” it fits better than a table. is_array($value) is a function that returns true when the value is an array (our checkbox group), otherwise false. The ?: condition from last week then chooses: for an array implode(', ', $value) (from last week: joins the items into one text with a comma), for an ordinary value directly $value. Without implode, echo of an array would print only the word Array and the message Array to string conversion.
This is what it looks like in the browser.
- name
- Jana Nováková
- jana@example.com
- since
- 2021
- date
- 2021-09-18
- grade
- 6a
- style
- lead
- interest
- course, rental
- consent
- yes
- message
More: PHP: $_POST, W3Schools: HTML dl
From $_POST into variables
A rule for the whole semester: at the beginning of the file move every value from $_POST into a variable with the same name and from then on work only with the variables. The code is shorter, more readable, and in one place you see what you use from the form.
$name = trim($_POST['name'] ?? '');
Read this line from right to left:
$_POST['name']: the value under the keyname, what was in the Name field.?? '': the operator??(null coalescing) means “and if there is no such value, use what comes after me”. If the keynamewere missing in$_POST(the file opened without the form, an unchecked checkbox, a typo inname), without??PHP would reportWarning: Undefined array key "name". With??you get an empty text and nothing breaks.trim(...): the function removes spaces (also tabs and line breaks) from the beginning and the end of the text.trim(' Jana ')gives'Jana'. A user who by mistake types only spaces into the name thus sends an empty text, and an empty text we can check.$name =: the result is stored in the variable.
The other fields by kind:
$name = trim($_POST['name'] ?? ''); // text: trim and the substitute ''
$email = trim($_POST['email'] ?? '');
// number: (int) makes the number 2021 from the text '2021'; substitute 0
$since = (int) ($_POST['since'] ?? 0);
$date = $_POST['date'] ?? ''; // the date comes as the text '2021-09-18', we leave it for now
$grade = $_POST['grade'] ?? ''; // select: the value of the chosen option, e.g. '6a'
$style = $_POST['style'] ?? ''; // radio: the value of the checked option
$interest = $_POST['interest'] ?? []; // checkbox group: array; substitute an empty array []
$consent = $_POST['consent'] ?? ''; // single checkbox: 'yes', or nothing when it was not checked
$message = trim($_POST['message'] ?? '');
(int) before the value is the type cast from last week: it makes the number 2021 from the text '2021', and 0 from the text 'abc'. Without it the year would be compared as text. For checkboxes the substitute is [], an empty array, so that implode and the loop work even when nothing was checked.
From this point we write $name, not $_POST['name']. Printing one by one:
<p>Name: <?= $name ?></p> <!-- ordinary value -->
<!-- array joined with a comma; an empty array gives an empty text -->
<p>Interest: <?= implode(', ', $interest) ?></p>
<p>Consent: <?= $consent == 'yes' ? 'yes' : 'no' ?></p> <!-- the ?: condition from last week -->
This is what it looks like in the browser.
Name: Jana Nováková
Interest: course, rental
Consent: yes
Careful: printing someone else’s values like this, without treatment, is dangerous. Why, comes in the XSS part; in a practice file it is fine for a look, on the website it does not belong.
More: PHP: Null coalescing operator, PHP: trim
Conditions in full: if, elseif, else
Last week you had if with one branch. Checking data needs more branches:
if ($name == '') { // 1. empty name?
$errors['name'] = 'The name is required.';
} elseif (mb_strlen($name) < 3) { // 2. if not empty: shorter than 3 characters?
$errors['name'] = 'The name must have at least 3 characters.';
} elseif (mb_strlen($name) > 60) { // 3. if not that either: longer than 60?
$errors['name'] = 'The name is too long.';
} // otherwise the name is fine, nothing happens
PHP goes from the top: the first condition that holds is executed, the other branches are skipped. else at the end (without a condition) catches everything that did not meet anything before. mb_strlen is from last week (counts characters). Conditions are combined: && (and at the same time), || (or), ! before a condition reverses it (not). Brackets set the order.
| Notation | True when | Example |
|---|---|---|
$a == '' |
the text is empty | an empty name after trim |
$a != 'yes' |
the value is not equal | $consent != 'yes': consent was not checked |
empty($a) |
empty text, 0, empty array |
empty($interest): no checkbox |
isset($a['x']) |
the key x exists in the array |
isset($errors['name']): the name field has an error |
!$a |
$a does not hold |
!isset($errors['name']): the name is fine |
$a && $b |
both hold | $since < 1950 && $since != 0 |
$a \|\| $b |
at least one holds | $since < 1950 \|\| $since > 2026: the year is out of range |
More: PHP: if, elseif, else, W3Schools: PHP if…else
Working with date and time
From the <input type="date"> field the date always comes as text in the form YYYY-MM-DD, no matter how the browser showed it: var_dump($date) gives string(10) "2021-09-18". If you only want to print the date or note it down, the text is enough. If you want to calculate with it (how many days remain, whether it is in the past), you must convert it to a number.
PHP counts time as one number: the number of seconds since 1 January 1970 (timestamp). Two functions convert in both directions:
strtotime($text)(string to time) converts a text with a date to a timestamp.strtotime('2021-09-18')gives1631923200. When the text is not a date (strtotime('last night-ish'),strtotime('')), the function returnsfalse. That is how a date can be checked: if the result isfalse, the user did not enter a date.date($format, $timestamp)converts a timestamp back to a text for people according to the format. The format is a text of letters:dday,mmonth,Yyear,lthe name of the day (in English; PHP has no Slovak).date('d. m. Y', 1631923200)gives18. 09. 2021. When you leave out the second parameter,dateuses now:date('d. m. Y')is today’s date,date('Y')this year (as in the footer last week). Careful,datereturns text; when you want to calculate with the year, write(int) date('Y').time()is the timestamp right now.
When both dates are numbers, they can be subtracted. The difference is in seconds; a day has 24 × 60 × 60 = 86,400 seconds.
$visit = strtotime($date); // the text '2021-09-18' to a timestamp
$days = (time() - $visit) / 86400; // days from the first visit until today, decimal (1858.6)
$days = floor($days); // floor rounds down to a whole number (1858); ceil rounds up
$years = (int) date('Y') - $since; // this year as a number minus the entered year
echo $days . ' days have passed since the first visit. You have been climbing for ' . $years . ' years.';
This is what it looks like in the browser.
Comparing dates means comparing numbers: strtotime($date) > time() is true when the date is in the future; a first visit cannot be in the future. Comparing the texts '2021-09-18' < '2026-9-1' would give nonsense.
| Notation | What it does | Result |
|---|---|---|
strtotime('2021-09-18') |
text to a timestamp | 1631923200 |
strtotime('nonsense') |
the text is not a date | false |
time() |
now as a timestamp | 1792454400 |
date('d. m. Y', $visit) |
timestamp to text | 18. 09. 2021 |
date('l', $visit) |
the name of the day | Saturday |
date('d. m. Y') |
without a timestamp: today | 20. 10. 2026 |
(int) date('Y') |
this year as a number | 2026 |
floor(1858.6), ceil(1858.6) |
up, down | 1858, 1859 |
More: PHP: strtotime, PHP: date
Trust, but verify: validation
In cv03 you gave the form required, type="email", min and max. The browser does not let an empty field or the year 1800 through because of them. That is convenience for the user, not protection: press F12, find the <input> and delete the word required; the form goes out empty. Whoever wants to sends the server anything, even without a browser. So the rule is: the server checks everything, always, even when the browser checked it. Checking data is called validation.
required attribute can be deleted with one double-click. The browser then lets an empty field through.
We will collect the errors into an array. At the beginning we create an empty array $errors = [];. It will be associative: the key is the name of the field, the value is the error text for a person, for example $errors['email'] = 'Enter a valid e-mail.';. When a field is fine, nothing is written into the array. At the end count($errors) (from last week: the number of items) says how many errors were found; count($errors) == 0 means “everything is fine”. And because the key is the name of the field, later we can show the message right at that field.
Two more functions we need:
filter_var($value, $filter)checks the value according to the given filter. The filterFILTER_VALIDATE_EMAILis ready in PHP and checks the form of an e-mail (something@something.something). When the value is fine, the function returns it; when not, it returnsfalse.filter_var('jana@example.com', FILTER_VALIDATE_EMAIL)gives'jana@example.com',filter_var('jana@', FILTER_VALIDATE_EMAIL)givesfalse. In a condition with!before the function:if (!filter_var($email, FILTER_VALIDATE_EMAIL))read “if the e-mail is not valid”.in_array($value, $array)returnstruewhen the value is in the array. Select and radio have a fixed list of options in HTML, but the server gets only text, and anyone could have rewritten it. So keep the list of options in PHP as an associative array (key =valuefrom HTML, value = the text for a person):
$grades = ['5a' => '5a (V)', '5c' => '5c (VI)', '6a' => '6a (VI+)', '6b' => '6b (VII)'];
It is the key that must be checked. array_keys($grades) makes a plain array of the keys alone from the associative array: ['5a', '5c', '6a', '6b']. And in_array($grade, array_keys($grades)) is true when $grade is one of them; with ! in front: “if the grade is not from the list”. in_array('6a', ['5a', '5c', '6a', '6b']) gives true, in_array('9z', …) gives false. The same array will print the <option>s with a loop in a moment, so the list of options is in the code only once.
What is checked and how (everything on the variables from the part “From $_POST into variables”):
| What | How | Notation | Error when |
|---|---|---|---|
| required field | empty text after trim |
$name == '' |
the user entered nothing or only spaces |
| text length | mb_strlen |
mb_strlen($name) < 3 |
'Jo' |
filter_var |
!filter_var($email, FILTER_VALIDATE_EMAIL) |
'jana@', '' |
|
| number in a range | compare after (int) |
$since < 1950 \|\| $since > (int) date('Y') |
1800, 0 (empty field) |
| date | strtotime |
strtotime($date) === false |
'', 'abc' |
| date not in the future | compare timestamps | strtotime($date) > time() |
'2030-01-01' |
| value from a list | in_array + array_keys |
!in_array($grade, array_keys($grades)) |
'', '9z' |
| consent checkbox | compare with value |
$consent != 'yes' |
it was not checked |
The whole block of checks is in Example 2.
More: PHP: filter_var, PHP: in_array, PHP: array_keys
Treating the output: XSS
Try typing <b>Jana</b> into the Name field and submit. In the output Jana will be in bold: the browser received the <b> tag and obeyed it. Now try <script>alert('hi')</script>. A window pops up. Someone has just put their own program into your page.
This is called XSS (cross-site scripting): an attacker inserts code through a form or an address, and it runs in the browsers of other visitors. It steals their login, rewrites the page, redirects them elsewhere. One untreated field is enough.
The defence is one function: htmlspecialchars($text, ENT_QUOTES, 'UTF-8'). It replaces the five characters that have a meaning in HTML with their notation as an ordinary character: < with <, > with >, & with &, " with ", ' with '. The browser then shows them as letters and does not execute them. <b>Jana</b> becomes <b>Jana</b> and on the screen you see literally <b>Jana</b>.
Three parameters: the first is the text; the second ENT_QUOTES is a constant (from last week: a fixed value with a name) which says “replace both double quotes and apostrophes”, without it an apostrophe would pass and would break the attribute in value='…'; the third 'UTF-8' is the encoding of the text, without it the diacritics may break. Always write those three parameters the same way.
The rule: every value the user typed goes into HTML through htmlspecialchars. Always, even when it “looks harmless”.
<p>Name: <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></p>
What is not done: PHP has the function strip_tags, which deletes all HTML tags from a text. It seems it would be enough to “clean” the input with it and store it. It is not done: the name “O’Neil” or the message “prices < 10 €” are valid texts and deleting would damage them; moreover, an attacker knows notations that pass through strip_tags. The input is stored as it came, and every output is treated. The second part of security, the attack through the database (SQL injection), comes with the database.
More: PHP: htmlspecialchars, OWASP: Cross Site Scripting
A form that processes itself
process.php is good for learning, not for the user: on an error they see the message on another page, must go back and type everything again. Finished websites do it differently: the form sends the data to itself (action=""), the same file checks it and either shows a summary, or the form again with the errors and with what was already filled in. This is called a self-processing form.
How does the file know whether someone opened it from the menu or a submitted form arrived? In the superglobal array $_SERVER PHP has data about the request; $_SERVER['REQUEST_METHOD'] is 'GET' when opened from the menu and 'POST' after the form is submitted.
In our template this is content/register.php. The skeleton, every line with a comment:
<?php
$errors = []; // empty array for errors, key = field
$sent = $_SERVER['REQUEST_METHOD'] == 'POST'; // bool: true after submitting, false when opened from the menu
$name = trim($_POST['name'] ?? ''); // from $_POST into variables, always (empty when opened)
// ... the other fields the same way
$grades = ['5a' => '5a (V)', /* ... */]; // lists of options as in process.php
if ($sent) { // checks only after submitting
if ($name == '') { $errors['name'] = 'The name is required.'; }
// ... the other checks exactly as in process.php
}
?>
<?php if ($sent && count($errors) == 0): ?> <!-- submitted and without errors -->
<!-- summary: values through htmlspecialchars -->
<?php else: ?> <!-- first opening, or submitted with errors -->
<!-- the form; the fields get their values and messages back -->
<?php endif; ?>
On the first opening ($sent is false) the variables are empty and the form is clean; after submitting with an error the variables hold what the user typed and the form puts it back into the fields. This is called a form that remembers its values (sticky form). For every kind of field the notation is different:
input(text, email, number, date): thevalueattribute pre-fills the field. We put the variable into it, treated, because it is from the user:value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>"textarea: has novalue, the text is written between the tags:<textarea …><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></textarea>select: the chosen<option>has the attributeselected(a word without a value). With the?:condition we print the wordselectedwhen the option’svalueequals what arrived, otherwise nothing:<option value="6a" <?= $grade == '6a' ? 'selected' : '' ?>>6a (VI+)</option>radio: the checked one has the attributechecked, by a condition in the same way:<input type="radio" name="style" value="lead" <?= $style == 'lead' ? 'checked' : '' ?>>checkboxin a group:$interestis the array of the checked ones;in_arrayfinds out whether this option is among them:<input type="checkbox" name="interest[]" value="course" <?= in_array('course', $interest) ? 'checked' : '' ?>>checkboxconsent:<?= $consent == 'yes' ? 'checked' : '' ?>
So that you do not have to write it for every <option> separately, a loop prints them from the array of options you already have for the check:
<select class="form-select" id="grade" name="grade">
<option value="">-- choose --</option>
<?php foreach ($grades as $key => $label): ?> <!-- $key = '6a', $label = '6a (VI+)' -->
<option value="<?= $key ?>" <?= $grade == $key ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
From this PHP makes, for $grade = '6a', this HTML:
<option value="">-- choose --</option>
<option value="5a" >5a (V)</option>
<option value="5c" >5c (VI)</option>
<option value="6a" selected>6a (VI+)</option>
<option value="6b" >6b (VII)</option>
Radio from $styles and checkboxes from $interests in the same way. The list of options is then in one place: you add an item to the array and it is both in the check and in the form.
Bootstrap shows the message at the field. It has two classes for HTML for that: is-invalid on the field makes a red border, and invalid-feedback is a div with a text that is hidden, and Bootstrap shows it (in red) only when the field before it has is-invalid. So PHP decides only whether it writes the word is-invalid into class:
<input type="email" class="form-control <?= isset($errors['email']) ? 'is-invalid' : '' ?>" id="email" name="email"
value="<?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?>">
<div class="invalid-feedback"><?= $errors['email'] ?? '' ?></div>
isset($errors['email']) is true when the check wrote an error for the e-mail. The resulting HTML with an error and without one:
<!-- with an error: red border, text visible -->
<input type="email" class="form-control is-invalid" id="email" name="email" value="jana@">
<div class="invalid-feedback">Enter a valid e-mail.</div>
<!-- without an error: ordinary field, the empty div stays hidden -->
<input type="email" class="form-control " id="email" name="email" value="jana@example.com">
<div class="invalid-feedback"></div>
This is what it looks like in the browser after submitting with a bad e-mail.
One more thing: when you press F5 after submitting, the browser asks whether it should send the data again. That is normal behaviour with POST; the solution (a redirect) comes later.
More: PHP: $_SERVER, Bootstrap: Validation, server side
The most common errors and what they mean
| What you see | Cause | Solution |
|---|---|---|
Warning: Undefined array key "email" |
a typo in the form’s name, or an unchecked checkbox |
name and key exactly the same; read from $_POST with ?? '' |
the form “does nothing”, $_POST is empty |
method="post" is missing, or a field has no name |
add method, every field has a name |
after submitting the address is …?name=… |
method is missing, the form went through GET |
method="post" |
Array to string conversion |
the checkbox group printed as text | implode(', ', $interest) |
| the year compares wrongly | $_POST is text, comparison of texts |
(int) before comparing |
diacritics broken after htmlspecialchars |
'UTF-8' is missing |
always three parameters: ENT_QUOTES, 'UTF-8' |
| after fixing an error the fields are empty | value="…" with the value is missing |
see the list of remembering values |
select does not show the chosen value |
selected is written fixed |
selected by a condition in the loop |
strtotime returns false |
the date is not in the form YYYY-MM-DD |
field type="date", check === false |
| F5 asks about resubmitting | normal with POST | nothing for now, open the page from the menu |
UkážkyExamples
Ukážky píšu len to, čo je k veci: form, PHP blok, výpis. Časť <head> s Bootstrap je ako v Ukážke 2 minulého týždňa; vo vzore sú súbory celé.
Ukážka 1: process.php, prvý pohľad na údaje
Vyplň form na form.php, stlač Registrovať; prehliadač ťa prenesie na process.php. Zatiaľ bez kontrol, len pozeráme, čo prišlo.
<h1>Čo prišlo z form</h1>
<h2>Celé array</h2>
<pre><?php print_r($_POST); ?></pre> <!-- print_r: celé array; pre: zachová riadky -->
<h2>Loop</h2>
<dl>
<?php foreach ($_POST as $key => $value): ?> <!-- prejde všetky fields -->
<dt><?= $key ?></dt> <!-- name field -->
<dd><?= is_array($value) ? implode(', ', $value) : $value ?></dd> <!-- array spojí, inak hodnota -->
<?php endforeach; ?>
</dl>
Otvor process.php aj priamo z adresy, bez form: $_POST je prázdne, print_r vypíše Array ( ), loop nevypíše nič a nič nespadne. Odošli form s nezaškrtnutým súhlasom: key consent vo výpise nie je.
Ukážka 2: variables, zoznamy možností, kontroly
Do process.php nad HTML pribudne PHP blok. Pod ním výpis po jednom a výpis chýb alebo potvrdenie.
<?php
// 1. z $_POST do variables; ?? dá náhradu, keď hodnota neprišla; trim odstráni medzery na okrajoch
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$since = (int) ($_POST['since'] ?? 0); // (int): z textu číslo
$date = $_POST['date'] ?? ''; // text RRRR-MM-DD
$grade = $_POST['grade'] ?? '';
$style = $_POST['style'] ?? '';
$interest = $_POST['interest'] ?? []; // array zaškrtnutých, alebo prázdne array
$consent = $_POST['consent'] ?? '';
$message = trim($_POST['message'] ?? '');
// 2. zoznamy možností: key = value z HTML, value = text pre človeka; slúžia na kontrolu aj na výpis
$grades = ['5a' => '5a (V)', '5c' => '5c (VI)', '6a' => '6a (VI+)', '6b' => '6b (VII)'];
$styles = ['toprope' => 's horným istením', 'lead' => 's dolným istením', 'boulder' => 'bouldering'];
$interests = ['course' => 'kurz pre začiatočníkov', 'rental' => 'požičanie výstroja'];
// 3. prázdne array na chyby; key = názov field, value = text chyby
$errors = [];
// 4. kontroly; keď field neprejde, zapíše sa chyba pod jeho key
if ($name == '') { // prázdne po trim
$errors['name'] = 'Meno je povinné.';
} elseif (mb_strlen($name) < 3) { // priveľmi krátke
$errors['name'] = 'Meno má mať aspoň 3 znaky.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // filter_var vráti false pri zlom tvare; ! obráti
$errors['email'] = 'Zadaj platný e-mail.';
}
if ($since < 1950 || $since > (int) date('Y')) { // mimo rozsahu; 0 z prázdneho field je tiež mimo
$errors['since'] = 'Rok musí byť medzi 1950 a ' . date('Y') . '.';
}
if (strtotime($date) === false) { // text sa nedá previesť na dátum (aj prázdny)
$errors['date'] = 'Zadaj dátum.';
} elseif (strtotime($date) > time()) { // dátum je v budúcnosti
$errors['date'] = 'Dátum prvej návštevy nemôže byť v budúcnosti.';
}
if (!in_array($grade, array_keys($grades))) { // hodnota nie je medzi key zoznamu
$errors['grade'] = 'Vyber obťažnosť zo zoznamu.';
}
if (!in_array($style, array_keys($styles))) {
$errors['style'] = 'Vyber štýl.';
}
if ($consent != 'yes') { // nezaškrtnutý checkbox: '' z ??
$errors['consent'] = 'Bez súhlasu sa nedá registrovať.';
}
?>
<h1>Spracovanie registrácie</h1>
<h2>Po jednom</h2>
<p>Meno: <?= $name ?></p> <!-- zatiaľ bez ošetrenia, oprava v Ukážke 4 -->
<p>E-mail: <?= $email ?></p>
<p>Záujem: <?= implode(', ', $interest) ?></p> <!-- array na text -->
<p>Súhlas: <?= $consent == 'yes' ? 'áno' : 'nie' ?></p>
<h2>Výsledok kontroly</h2>
<?php if (count($errors) > 0): ?> <!-- našla sa aspoň jedna chyba -->
<div class="alert alert-danger"> <!-- Bootstrap alert z týždňa 4 -->
<ul class="mb-0">
<?php foreach ($errors as $field => $text): ?> <!-- $field = názov field, $text = hláška -->
<li><?= $field ?>: <?= $text ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php else: ?> <!-- žiadna chyba -->
<div class="alert alert-success">Registrácia je v poriadku.</div>
<?php endif; ?>
Takto to vyzerá v prehliadači po odoslaní so zlým e-mailom a dátumom v budúcnosti.
- email: Zadaj platný e-mail.
- date: Dátum prvej návštevy nemôže byť v budúcnosti.
Čo robí ktorý blok: 1 prenesie všetko do variables, od tohto miesta sa $_POST už nepoužíva; 2 zoznamy sú v kóde raz; 3 array na chyby je na začiatku prázdne; 4 každá kontrola buď nič neurobí, alebo zapíše chybu pod key svojho field; na konci count($errors) rozhodne, ktorá vetva sa vypíše.
Ukážka 3: výpočty z údajov
Vo vetve else (údaje sú v poriadku) sa dá počítať. Výpočty idú až sem, lebo s neplatným dátumom sa počítať nedá.
<?php else: ?>
<?php
$visit = strtotime($date); // text na timestamp
$days = floor((time() - $visit) / 86400); // sekundy od návštevy / sekundy v dni, nadol
$years = (int) date('Y') - $since; // dnešný rok ako číslo mínus zadaný rok
?>
<div class="alert alert-success">Registrácia je v poriadku.</div>
<p>Prvá návšteva bola <?= date('d. m. Y', $visit) ?>, bola to <?= date('l', $visit) ?>,
odvtedy prešlo <?= $days ?> dní.</p> <!-- date: timestamp na text; l = názov dňa -->
<!-- ?: pridá text len niekedy -->
<p>Lezieš <?= $years ?> rokov<?= $years >= 10 ? ', to je už skúsenosť' : '' ?>.</p>
<p>Správa má <?= mb_strlen($message) ?> znakov.</p> <!-- počet znakov -->
<?php endif; ?>
Takto to vyzerá v prehliadači.
Prvá návšteva bola 18. 09. 2021, bola to Saturday, odvtedy prešlo 1858 dní.
Lezieš 5 rokov.
Správa má 0 znakov.
Ukážka 4: XSS pred a po
Do field Meno napíš <script>alert('ahoj')</script> a odošli.
<!-- NEBEZPEČNÉ: prehliadač dostane tag <script> a vykoná ju -->
<p>Meno: <?= $name ?></p>
<!-- BEZPEČNÉ: < sa stane <, prehliadač ukáže text -->
<p>Meno: <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></p>
Takto to vyzerá v prehliadači. Prvý riadok otvorí okno s textom „ahoj” a vypíše len „Meno:“; druhý riadok vypíše kód ako text.
Meno:
Meno: <script>alert(‘ahoj’)</script>
Po tejto ukážke prepíš v process.php všetky výpisy hodnôt od používateľa na ošetrené: $name, $email, $message, aj $value v loop v Ukážke 1. Texty z $errors a z $grades si napísal ty, tie ošetrovať netreba; $grade samotné (key od používateľa) áno, ak ho vypisuješ.
Ukážka 5: samospracujúci form v content/register.php
Celý súbor s komentárom pri každom riadku, ktorý robí niečo nové. Fields email, since, date sú rovnaké ako name, preto sú skrátené; vo vzore sú celé.
<?php
$errors = []; // prázdne array na chyby, key = field
$sent = $_SERVER['REQUEST_METHOD'] == 'POST'; // true po odoslaní form, false pri otvorení z menu
$name = trim($_POST['name'] ?? ''); // z $_POST do variables; pri otvorení z menu sú prázdne
$email = trim($_POST['email'] ?? '');
$since = (int) ($_POST['since'] ?? 0);
$date = $_POST['date'] ?? '';
$grade = $_POST['grade'] ?? '';
$style = $_POST['style'] ?? 'toprope'; // predvolený radio, aby bol pri prvom otvorení označený
$interest = $_POST['interest'] ?? [];
$consent = $_POST['consent'] ?? '';
$message = trim($_POST['message'] ?? '');
$grades = ['5a' => '5a (V)', '5c' => '5c (VI)', '6a' => '6a (VI+)', '6b' => '6b (VII)']; // zoznamy možností
$styles = ['toprope' => 's horným istením', 'lead' => 's dolným istením', 'boulder' => 'bouldering'];
$interests = ['course' => 'kurz pre začiatočníkov', 'rental' => 'požičanie výstroja'];
if ($sent) { // kontroly len po odoslaní
if ($name == '') { $errors['name'] = 'Meno je povinné.'; }
elseif (mb_strlen($name) < 3) { $errors['name'] = 'Meno má mať aspoň 3 znaky.'; }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = 'Zadaj platný e-mail.'; }
if ($since < 1950 || $since > (int) date('Y')) {
$errors['since'] = 'Rok musí byť medzi 1950 a ' . date('Y') . '.';
}
if (strtotime($date) === false) { $errors['date'] = 'Zadaj dátum.'; }
elseif (strtotime($date) > time()) { $errors['date'] = 'Dátum nemôže byť v budúcnosti.'; }
if (!in_array($grade, array_keys($grades))) { $errors['grade'] = 'Vyber obťažnosť zo zoznamu.'; }
if (!in_array($style, array_keys($styles))) { $errors['style'] = 'Vyber štýl.'; }
if ($consent != 'yes') { $errors['consent'] = 'Bez súhlasu sa nedá registrovať.'; }
}
$chosen = []; // texty zaškrtnutých záujmov pre zhrnutie
foreach ($interest as $key) { // prejde key od používateľa
if (isset($interests[$key])) { // len key, ktoré v zozname sú
$chosen[] = $interests[$key]; // pridá text pre človeka
}
}
?>
<?php if ($sent && count($errors) == 0): ?> <!-- odoslané a bez chýb: zhrnutie -->
<section id="done" class="mb-5">
<h2>Registrácia prijatá</h2>
<dl>
<dt>Meno</dt><dd><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></dd> <!-- od používateľa: ošetriť -->
<dt>E-mail</dt><dd><?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?></dd>
<!-- číslo po (int), bezpečné -->
<dt>Lezie od</dt><dd><?= $since ?> (<?= (int) date('Y') - $since ?> rokov)</dd>
<!-- prešlo kontrolou, dá sa previesť -->
<dt>Prvá návšteva</dt><dd><?= date('d. m. Y', strtotime($date)) ?></dd>
<!-- key prešiel in_array; text je tvoj -->
<dt>Obťažnosť</dt><dd><?= $grades[$grade] ?></dd>
<dt>Štýl</dt><dd><?= $styles[$style] ?></dd>
<dt>Záujem</dt><dd><?= count($chosen) > 0 ? implode(', ', $chosen) : 'žiadny' ?></dd>
<dt>Správa</dt><dd><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></dd>
</dl>
</section>
<?php else: ?> <!-- prvé otvorenie, alebo odoslané s chybami: form -->
<section id="register" class="mb-5">
<h2>Registrácia lezca</h2>
<?php if (count($errors) > 0): ?> <!-- len po odoslaní s chybami -->
<div class="alert alert-danger">Form má chyby, oprav červené fields.</div>
<?php endif; ?>
<form method="post" action=""> <!-- action="": odošle sa sám sebe -->
<div class="mb-3">
<label for="name" class="form-label">Meno a priezvisko</label>
<!-- class is-invalid pri chybe; value vráti hodnotu späť -->
<input type="text" class="form-control <?= isset($errors['name']) ? 'is-invalid' : '' ?>"
id="name" name="name" value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>" required>
<!-- text chyby, alebo nič -->
<div class="invalid-feedback"><?= $errors['name'] ?? '' ?></div>
</div>
<!-- email, since, date: rovnaké tri riadky ako pri name -->
<div class="mb-3">
<label for="grade" class="form-label">Najvyššia vylezená obťažnosť</label>
<select class="form-select <?= isset($errors['grade']) ? 'is-invalid' : '' ?>" id="grade" name="grade" required>
<option value="">-- vyber --</option>
<?php foreach ($grades as $key => $label): ?> <!-- možnosti zo zoznamu -->
<!-- selected pri vybranej -->
<option value="<?= $key ?>" <?= $grade == $key ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
<div class="invalid-feedback"><?= $errors['grade'] ?? '' ?></div>
</div>
<fieldset class="mb-3">
<legend class="fs-6">Štýl lezenia</legend>
<?php foreach ($styles as $key => $label): ?>
<div class="form-check">
<!-- checked pri označenom -->
<input class="form-check-input" type="radio" name="style" id="style_<?= $key ?>" value="<?= $key ?>"
<?= $style == $key ? 'checked' : '' ?>>
<label class="form-check-label" for="style_<?= $key ?>"><?= $label ?></label>
</div>
<?php endforeach; ?>
</fieldset>
<fieldset class="mb-3">
<legend class="fs-6">Mám záujem o</legend>
<?php foreach ($interests as $key => $label): ?>
<div class="form-check">
<!-- checked, ak je key medzi zaškrtnutými -->
<input class="form-check-input" type="checkbox" name="interest[]" id="interest_<?= $key ?>" value="<?= $key ?>"
<?= in_array($key, $interest) ? 'checked' : '' ?>>
<label class="form-check-label" for="interest_<?= $key ?>"><?= $label ?></label>
</div>
<?php endforeach; ?>
</fieldset>
<div class="form-check mb-3">
<input class="form-check-input <?= isset($errors['consent']) ? 'is-invalid' : '' ?>" type="checkbox"
name="consent" id="consent" value="yes" <?= $consent == 'yes' ? 'checked' : '' ?> required>
<label class="form-check-label" for="consent">Súhlasím s prevádzkovým poriadkom</label>
<div class="invalid-feedback"><?= $errors['consent'] ?? '' ?></div>
</div>
<div class="mb-3">
<label for="message" class="form-label">Správa</label>
<!-- textarea: hodnota medzi tag -->
<textarea class="form-control" id="message" name="message" rows="3"><?=
htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Registrovať</button>
</form>
</section>
<?php endif; ?>
Pozor na action="": form ide na form.php, ten vloží template a template vloží content/register.php. Celé spracovanie je v jednom request.
Ukážka 6: prompt na process.php
Mám form v súbore content/register.php (posielam ho nižšie) na tému [DOPLŇ tému].
Vytvor súbor practice/process.php pre PHP 8.1, ktorý ho spracuje. Form mu posiela údaje
metódou POST na adresu ../practice/process.php. Bez databázy, bez JavaScriptu, bez funkcií.
Štruktúra:
1. Hore v bloku <?php ... ?>: každú hodnotu z $_POST načítaj do variable
s anglickým názvom podľa name field, s trim a s ?? '' (pre skupinu checkboxov ?? []);
čísla preveď cez (int). Pri každom riadku komentár, čo robí.
2. Zoznamy možností select, radio a checkbox ako asociatívne array
(key = value z HTML, value = text pre človeka), názvy po anglicky.
3. Kontroly do asociatívneho array $errors (key = názov field) cez if / elseif:
povinné meno s mb_strlen aspoň 3, e-mail cez filter_var FILTER_VALIDATE_EMAIL,
číslo v rozsahu. Ostatné fields nechaj s komentárom // DOPLŇ: kontrola.
4. HTML5 stránka s Bootstrap 5.3 z CDN, body s class container:
heading, <pre> s print_r($_POST), výpis troch hodnôt po jednom,
výpis všetkých hodnôt loop foreach do <dl> s is_array a implode,
potom if: ak sú chyby, alert-danger so zoznamom chýb (key: text),
inak alert-success.
5. Všetky hodnoty od používateľa vo výpise ošetri cez
htmlspecialchars($x, ENT_QUOTES, 'UTF-8').
Ku každému bloku krátky komentár, čo robí.
Tu je form:
[VLOŽ content/register.php]
Prečo je prompt napísaný práve takto:
$errorss key = field: rovnaké array použiješ v samospracovaní a testy ho hľadajú,- tri kontroly hotové, zvyšné
// DOPLŇ: každú kontrolu, ktorú dopíšeš, vieš pri obhajobe vysvetliť, - zoznamy možností ako array: jeden zoznam pre kontrolu aj pre form,
- bez funkcií a bez databázy: tie prídu, keď budú treba.
Ukážka 7: prompt na výpočty
V súbore process.php (posielam) mám po kontrolách vetvu else, kde sú údaje
v poriadku. Doplň do nej výpočty z údajov form, PHP 8.1, bez funkcií:
- z field s dátumom [DOPLŇ name field]: dátum vo formáte d. m. Y, anglický názov dňa
cez date('l'), počet dní od toho dátumu do dnes cez time() a strtotime delené 86400 a floor,
- z field s rokom [DOPLŇ name field]: počet rokov do dnes cez (int) date('Y'),
- dĺžka textu z field [DOPLŇ name field] cez mb_strlen,
- jeden ďalší výpočet nechaj ako komentár // DOPLŇ: vlastný výpočet z mojej témy.
Výsledky vypíš v paragraphs s <?= ?>. Pri každom výpočte komentár, čo počíta a v akých jednotkách.
Tu je súbor:
[VLOŽ process.php]
Prečo takto: výpočty sú po kontrolách, lebo s neplatným dátumom sa počítať nedá; jeden výpočet si vymyslíš sám a ten sa pýta pri obhajobe; jednotky v komentári, lebo 86400 bez vysvetlenia o mesiac nikto nespozná.
Ukážka 8: prompt na samospracujúci form
Posielam content/register.php (form) a process.php (kontroly) z webu na tému
[DOPLŇ tému]. Prepíš content/register.php na samospracujúci form, PHP 8.1,
bez funkcií, bez databázy. Súbor sa vkladá do template cez include, takže v ňom
nie je <html>, <head> ani menu, len obsah pre <main>.
1. Hore PHP blok: $errors = []; $sent = $_SERVER['REQUEST_METHOD'] == 'POST';
načítanie všetkých fields z $_POST s trim a ?? ako v process.php; array možností
skopíruj z process.php; kontroly spusti len if ($sent) a nechaj tam komentár
// DOPLŇ: skopíruj kontroly z process.php.
2. Potom if ($sent && count($errors) == 0): section so zhrnutím v <dl>, hodnoty
od používateľa cez htmlspecialchars($x, ENT_QUOTES, 'UTF-8'), hodnoty zo
select/radio preložené cez array možností na text pre človeka; zaškrtnuté
checkboxy prelož loop foreach do pomocného array a spoj cez implode.
3. else: section s form s method="post" a action="": nad form
alert-danger, ak sú chyby; každé input má value s hodnotou späť cez
htmlspecialchars, class is-invalid condition isset($errors['field'])
a pod sebou div.invalid-feedback s textom chyby cez ?? '';
<option>, radio a checkbox vypíš loop foreach z array možností
so selected / checked condition; textarea s hodnotou medzi tags.
Pri jednom field nechaj value a is-invalid nevyplnené s komentárom
// DOPLŇ: hodnota späť a chyba.
4. Texty, class Bootstrap, label a id nemeň. Pri každom riadku PHP komentár.
Tu sú súbory:
[VLOŽ content/register.php a process.php]
Prečo takto: kontroly si prenesieš sám, lebo ich poznáš z process.php; jedno field doplníš ručne, aby si vedel, ako vzniká value a is-invalid; zoznamy možností sú raz, preto loop.
The examples show only what matters: the form, the PHP block, the output. The page head with <head> and Bootstrap is as in Example 2 of last week; in the sample the files are complete.
Example 1: process.php, the first look at the data
Fill in the form on form.php, press Register; the browser takes you to process.php. No checks yet, we only look at what arrived.
<h1>What came from the form</h1>
<h2>The whole array</h2>
<pre><?php print_r($_POST); ?></pre> <!-- print_r: the whole array; pre: keeps the lines -->
<h2>With a loop</h2>
<dl>
<?php foreach ($_POST as $key => $value): ?> <!-- goes through all fields -->
<dt><?= $key ?></dt> <!-- name of the field -->
<dd><?= is_array($value) ? implode(', ', $value) : $value ?></dd> <!-- joins an array, otherwise the value -->
<?php endforeach; ?>
</dl>
Open process.php also directly from the address, without the form: $_POST is empty, print_r prints Array ( ), the loop prints nothing and nothing breaks. Submit the form with the consent unchecked: the key consent is not in the output.
Example 2: variables, lists of options, checks
A PHP block is added to process.php above the HTML. Below it the output one by one and the output of errors or the confirmation.
<?php
// 1. from $_POST into variables; ?? gives a substitute when the value did not arrive; trim removes spaces at the edges
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$since = (int) ($_POST['since'] ?? 0); // (int): a number from the text
$date = $_POST['date'] ?? ''; // text YYYY-MM-DD
$grade = $_POST['grade'] ?? '';
$style = $_POST['style'] ?? '';
$interest = $_POST['interest'] ?? []; // array of the checked ones, or an empty array
$consent = $_POST['consent'] ?? '';
$message = trim($_POST['message'] ?? '');
// 2. lists of options: key = value from HTML, value = text for a person; used for the check and for the output
$grades = ['5a' => '5a (V)', '5c' => '5c (VI)', '6a' => '6a (VI+)', '6b' => '6b (VII)'];
$styles = ['toprope' => 'top rope', 'lead' => 'lead', 'boulder' => 'bouldering'];
$interests = ['course' => 'a beginners\' course', 'rental' => 'gear rental'];
// 3. empty array for errors; key = name of the field, value = error text
$errors = [];
// 4. checks; when a field fails, an error is written under its key
if ($name == '') { // empty after trim
$errors['name'] = 'The name is required.';
} elseif (mb_strlen($name) < 3) { // too short
$errors['name'] = 'The name must have at least 3 characters.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // filter_var returns false for a bad form; ! reverses
$errors['email'] = 'Enter a valid e-mail.';
}
if ($since < 1950 || $since > (int) date('Y')) { // out of range; 0 from an empty field is also out
$errors['since'] = 'The year must be between 1950 and ' . date('Y') . '.';
}
if (strtotime($date) === false) { // the text cannot be converted to a date (also empty)
$errors['date'] = 'Enter a date.';
} elseif (strtotime($date) > time()) { // the date is in the future
$errors['date'] = 'The date of the first visit cannot be in the future.';
}
if (!in_array($grade, array_keys($grades))) { // the value is not among the keys of the list
$errors['grade'] = 'Choose a grade from the list.';
}
if (!in_array($style, array_keys($styles))) {
$errors['style'] = 'Choose a style.';
}
if ($consent != 'yes') { // unchecked checkbox: '' from ??
$errors['consent'] = 'You cannot register without consent.';
}
?>
<h1>Processing the registration</h1>
<h2>One by one</h2>
<p>Name: <?= $name ?></p> <!-- without treatment for now, fixed in Example 4 -->
<p>E-mail: <?= $email ?></p>
<p>Interest: <?= implode(', ', $interest) ?></p> <!-- array to text -->
<p>Consent: <?= $consent == 'yes' ? 'yes' : 'no' ?></p>
<h2>Result of the check</h2>
<?php if (count($errors) > 0): ?> <!-- at least one error was found -->
<div class="alert alert-danger"> <!-- Bootstrap alert from week 4 -->
<ul class="mb-0">
<?php foreach ($errors as $field => $text): ?> <!-- $field = name of the field, $text = message -->
<li><?= $field ?>: <?= $text ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php else: ?> <!-- no error -->
<div class="alert alert-success">The registration is fine.</div>
<?php endif; ?>
This is what it looks like in the browser after submitting with a bad e-mail and a date in the future.
- email: Enter a valid e-mail.
- date: The date of the first visit cannot be in the future.
What each block does: 1 moves everything into variables, from this point $_POST is not used any more; 2 the lists are in the code once; 3 the array for errors is empty at the start; 4 every check either does nothing, or writes an error under the key of its field; at the end count($errors) decides which branch is printed.
Example 3: calculations from the data
In the else branch (the data is fine) you can calculate. The calculations go here, because you cannot calculate with an invalid date.
<?php else: ?>
<?php
$visit = strtotime($date); // text to a timestamp
$days = floor((time() - $visit) / 86400); // seconds since the visit / seconds in a day, down
$years = (int) date('Y') - $since; // this year as a number minus the entered year
?>
<div class="alert alert-success">The registration is fine.</div>
<p>The first visit was on <?= date('d. m. Y', $visit) ?>, it was a <?= date('l', $visit) ?>,
<?= $days ?> days have passed since.</p> <!-- date: timestamp to text; l = name of the day -->
<!-- ?: adds text only sometimes -->
<p>You have been climbing for <?= $years ?> years<?= $years >= 10 ? ', that is experience' : '' ?>.</p>
<p>The message has <?= mb_strlen($message) ?> characters.</p> <!-- number of characters -->
<?php endif; ?>
This is what it looks like in the browser.
The first visit was on 18. 09. 2021, it was a Saturday, 1858 days have passed since.
You have been climbing for 5 years.
The message has 0 characters.
Example 4: XSS before and after
Type <script>alert('hi')</script> into the Name field and submit.
<!-- DANGEROUS: the browser receives the <script> tag and runs it -->
<p>Name: <?= $name ?></p>
<!-- SAFE: < becomes <, the browser shows text -->
<p>Name: <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></p>
This is what it looks like in the browser. The first line opens a window with the text “hi” and prints only “Name:”; the second line prints the code as text.
Name:
Name: <script>alert(‘hi’)</script>
After this example rewrite all outputs of values from the user in process.php to treated ones: $name, $email, $message, and also $value in the loop in Example 1. The texts from $errors and from $grades were written by you, they need no treatment; $grade itself (a key from the user) does, if you print it.
Example 5: the self-processing form in content/register.php
The whole file with a comment on every line that does something new. The fields email, since, date are the same as name, so they are shortened; in the sample they are complete.
<?php
$errors = []; // empty array for errors, key = field
// true after submitting the form, false when opened from the menu
$sent = $_SERVER['REQUEST_METHOD'] == 'POST';
// from $_POST into variables; empty when opened from the menu
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$since = (int) ($_POST['since'] ?? 0);
$date = $_POST['date'] ?? '';
$grade = $_POST['grade'] ?? '';
$style = $_POST['style'] ?? 'toprope'; // default radio, so that it is checked on the first opening
$interest = $_POST['interest'] ?? [];
$consent = $_POST['consent'] ?? '';
$message = trim($_POST['message'] ?? '');
$grades = ['5a' => '5a (V)', '5c' => '5c (VI)', '6a' => '6a (VI+)', '6b' => '6b (VII)']; // lists of options
$styles = ['toprope' => 'top rope', 'lead' => 'lead', 'boulder' => 'bouldering'];
$interests = ['course' => 'a beginners\' course', 'rental' => 'gear rental'];
if ($sent) { // checks only after submitting
if ($name == '') { $errors['name'] = 'The name is required.'; }
elseif (mb_strlen($name) < 3) { $errors['name'] = 'The name must have at least 3 characters.'; }
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors['email'] = 'Enter a valid e-mail.'; }
if ($since < 1950 || $since > (int) date('Y')) {
$errors['since'] = 'The year must be between 1950 and ' . date('Y') . '.';
}
if (strtotime($date) === false) { $errors['date'] = 'Enter a date.'; }
elseif (strtotime($date) > time()) { $errors['date'] = 'The date cannot be in the future.'; }
if (!in_array($grade, array_keys($grades))) { $errors['grade'] = 'Choose a grade from the list.'; }
if (!in_array($style, array_keys($styles))) { $errors['style'] = 'Choose a style.'; }
if ($consent != 'yes') { $errors['consent'] = 'You cannot register without consent.'; }
}
$chosen = []; // texts of the checked interests for the summary
foreach ($interest as $key) { // goes through the keys from the user
if (isset($interests[$key])) { // only keys that are in the list
$chosen[] = $interests[$key]; // adds the text for a person
}
}
?>
<?php if ($sent && count($errors) == 0): ?> <!-- submitted and without errors: summary -->
<section id="done" class="mb-5">
<h2>Registration received</h2>
<dl>
<dt>Name</dt><dd><?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></dd> <!-- from the user: treat -->
<dt>E-mail</dt><dd><?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?></dd>
<!-- a number after (int), safe -->
<dt>Climbing since</dt><dd><?= $since ?> (<?= (int) date('Y') - $since ?> years)</dd>
<!-- passed the check, can be converted -->
<dt>First visit</dt><dd><?= date('d. m. Y', strtotime($date)) ?></dd>
<!-- the key passed in_array; the text is yours -->
<dt>Grade</dt><dd><?= $grades[$grade] ?></dd>
<dt>Style</dt><dd><?= $styles[$style] ?></dd>
<dt>Interest</dt><dd><?= count($chosen) > 0 ? implode(', ', $chosen) : 'none' ?></dd>
<dt>Message</dt><dd><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></dd>
</dl>
</section>
<?php else: ?> <!-- first opening, or submitted with errors: the form -->
<section id="register" class="mb-5">
<h2>Climber registration</h2>
<?php if (count($errors) > 0): ?> <!-- only after submitting with errors -->
<div class="alert alert-danger">The form has errors, fix the red fields.</div>
<?php endif; ?>
<form method="post" action=""> <!-- action="": submits to itself -->
<div class="mb-3">
<label for="name" class="form-label">Name and surname</label>
<!-- the class is-invalid on error; value puts the value back -->
<input type="text" class="form-control <?= isset($errors['name']) ? 'is-invalid' : '' ?>"
id="name" name="name" value="<?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>" required>
<!-- error text, or nothing -->
<div class="invalid-feedback"><?= $errors['name'] ?? '' ?></div>
</div>
<!-- email, since, date: the same three lines as for name -->
<div class="mb-3">
<label for="grade" class="form-label">Hardest grade climbed</label>
<select class="form-select <?= isset($errors['grade']) ? 'is-invalid' : '' ?>" id="grade" name="grade" required>
<option value="">-- choose --</option>
<!-- options from the list -->
<?php foreach ($grades as $key => $label): ?>
<!-- selected on the chosen one -->
<option value="<?= $key ?>" <?= $grade == $key ? 'selected' : '' ?>><?= $label ?></option>
<?php endforeach; ?>
</select>
<div class="invalid-feedback"><?= $errors['grade'] ?? '' ?></div>
</div>
<fieldset class="mb-3">
<legend class="fs-6">Climbing style</legend>
<?php foreach ($styles as $key => $label): ?>
<div class="form-check">
<!-- checked on the chosen one -->
<input class="form-check-input" type="radio" name="style" id="style_<?= $key ?>" value="<?= $key ?>"
<?= $style == $key ? 'checked' : '' ?>>
<label class="form-check-label" for="style_<?= $key ?>"><?= $label ?></label>
</div>
<?php endforeach; ?>
</fieldset>
<fieldset class="mb-3">
<legend class="fs-6">I am interested in</legend>
<?php foreach ($interests as $key => $label): ?>
<div class="form-check">
<!-- checked if the key is among the checked ones -->
<input class="form-check-input" type="checkbox" name="interest[]" id="interest_<?= $key ?>" value="<?= $key ?>"
<?= in_array($key, $interest) ? 'checked' : '' ?>>
<label class="form-check-label" for="interest_<?= $key ?>"><?= $label ?></label>
</div>
<?php endforeach; ?>
</fieldset>
<div class="form-check mb-3">
<input class="form-check-input <?= isset($errors['consent']) ? 'is-invalid' : '' ?>" type="checkbox"
name="consent" id="consent" value="yes" <?= $consent == 'yes' ? 'checked' : '' ?> required>
<label class="form-check-label" for="consent">I agree with the house rules</label>
<div class="invalid-feedback"><?= $errors['consent'] ?? '' ?></div>
</div>
<div class="mb-3">
<label for="message" class="form-label">Message</label>
<!-- textarea: the value between the tags -->
<textarea class="form-control" id="message" name="message" rows="3"><?=
htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</section>
<?php endif; ?>
Careful with action="": the form goes to form.php, which includes the template, and the template includes content/register.php. The whole processing happens in one request.
Example 6: a prompt for process.php
I have a form in the file content/register.php (I am sending it below) for a website
about [FILL IN the topic]. Create the file practice/process.php for PHP 8.1 that processes it.
The form sends it the data with the POST method to ../practice/process.php. No database, no JavaScript, no functions.
Structure:
1. At the top in a <?php ... ?> block: load every value from $_POST into a variable
with an English name according to the field's name, with trim and with ?? ''
(for the checkbox group ?? []); convert numbers with (int). A comment on every
line saying what it does.
2. The lists of options for select, radio and checkbox as associative arrays
(key = value from HTML, value = text for a person), names in English.
3. Checks into an associative array $errors (key = name of the field) with if / elseif:
required name with mb_strlen at least 3, e-mail with filter_var FILTER_VALIDATE_EMAIL,
a number in a range. Leave the other fields with the comment // DOPLŇ: check.
4. An HTML5 page with Bootstrap 5.3 from the CDN, body with the class container:
a heading, <pre> with print_r($_POST), three values printed one by one,
all values printed with a foreach loop into <dl> with is_array and implode,
then if: if there are errors, alert-danger with the list of errors (key: text),
otherwise alert-success.
5. Treat all values from the user in the output with
htmlspecialchars($x, ENT_QUOTES, 'UTF-8').
A short comment on every block saying what it does.
Here is the form:
[PASTE content/register.php]
Why the prompt is written this way:
$errorswith key = field: you use the same array in the self-processing form and the tests look for it,- three checks done, the rest
// DOPLŇ: every check you add yourself you can explain at the defence, - the lists of options as arrays: one list for the check and for the form,
- no functions and no database: they come when they are needed.
Example 7: a prompt for the calculations
In the file process.php (I am sending it) I have, after the checks, an else branch
where the data is fine. Add calculations from the form data into it, PHP 8.1, no functions:
- from the date field [FILL IN the field's name]: the date in the format d. m. Y, the English
name of the day via date('l'), the number of days from that date until today via time() and strtotime
divided by 86400 and floor,
- from the year field [FILL IN the field's name]: the number of years until today via (int) date('Y'),
- the length of the text from the field [FILL IN the field's name] via mb_strlen,
- leave one more calculation as the comment // DOPLŇ: my own calculation from my topic.
Print the results in paragraphs with <?= ?>. At every calculation a comment saying
what it calculates and in what units.
Here is the file:
[PASTE process.php]
Why this way: the calculations come after the checks, because you cannot calculate with an invalid date; one calculation you invent yourself and that one is asked at the defence; the units in a comment, because nobody recognises 86400 without an explanation a month later.
Example 8: a prompt for the self-processing form
I am sending content/register.php (the form) and process.php (the checks) from a website
about [FILL IN the topic]. Rewrite content/register.php into a self-processing form,
PHP 8.1, no functions, no database. The file is included into a template via include,
so there is no <html>, <head> or menu in it, only the content for <main>.
1. At the top a PHP block: $errors = []; $sent = $_SERVER['REQUEST_METHOD'] == 'POST';
loading of all fields from $_POST with trim and ?? as in process.php; copy the
arrays of options from process.php; run the checks only if ($sent) and leave
the comment // DOPLŇ: copy the checks from process.php there.
2. Then if ($sent && count($errors) == 0): a section with the summary in <dl>, values
from the user through htmlspecialchars($x, ENT_QUOTES, 'UTF-8'), values from
select/radio translated through the arrays of options into text for a person;
translate the checked checkboxes with a foreach loop into a helper array and join
them with implode.
3. else: a section with the form with method="post" and action="": above the form
alert-danger if there are errors; every input has value with the value back
through htmlspecialchars, the class is-invalid by the condition isset($errors['field'])
and below it div.invalid-feedback with the error text via ?? '';
print <option>, radio and checkbox with a foreach loop from the arrays of options
with selected / checked by a condition; textarea with the value between the tags.
At one field leave value and is-invalid unfilled with the comment
// DOPLŇ: value back and the error.
4. Do not change the texts, the Bootstrap classes, label and id. A comment on every PHP line.
Here are the files:
[PASTE content/register.php and process.php]
Why this way: you carry the checks over yourself, because you know them from process.php; one field you complete by hand, so that you know how value and is-invalid arise; the lists of options exist once, hence the loop.
Úlohy na cvičenieLab tasks
Úlohy dostaneš aj ako zadanie cv05 v Classroom 50, sú v súbore README.md v tvojom repository.
Link na zadanie cv05: prijať zadanie
(platí pre skupiny B. Stehlíkovej; ostatné skupiny dostanú link od svojho cvičiaceho)
Úloha 6.1: Príprava Kubeflow. Priprav si Kubeflow podľa návodu 04 Odovzdávanie, časť 1: v Explorer je hore WEB, dole na stavovej lište je Go Live. Ak tam nie je, rozšírenia vráti tento príkaz v termináli:
code-server --install-extension Natizyskunk.sftp --install-extension yandeu.five-server --install-extension bmewburn.vscode-intelephense-client --install-extension mblode.twig-language-2
Potom F1, Developer: Reload Window. Nastavenie pripojenia na sigma zostáva.
Úloha 6.2: Zadanie a kópia minulého týždňa. Prijmi zadanie cv05 v Classroom 50 (link je vyššie) a repository naklonuj do ~/web/ti/cv05 podľa návodu 04, časti 2 a 3. Potom do neho prekopíruj svoj web z minulého týždňa:
cd ~/web/ti
rsync -a --exclude .git --exclude .github --exclude README.md cv04/ cv05/
Pravý klik na cv05, Upload Folder. Over na sigma …/ti/cv05/web/, že web beží.
Úloha 6.3: Form na POST. V web/content/register.php over, že všetky fields majú anglické name a value bez diakritiky (skupina checkboxov má []). Doplň method="post" a action="../practice/process.php". Odošli form: adresa po odoslaní nemá ? a stránka hlási, že process.php nie je. To je v poriadku.
Úloha 6.4: process.php. Prompt z Ukážky 6 so svojím form. Výsledok ulož ako practice/process.php. Vyplň form na sigma, odošli, prezri print_r. Odošli ho aj s nezaškrtnutým checkboxom a pozri, ktorý key chýba.
Úloha 6.5: Kontroly rukou. Doplň // DOPLŇ: kontrola pre všetky zvyšné fields: dátum cez strtotime (a že nie je v budúcnosti, ak to pre tvoju tému dáva zmysel), select a radio cez in_array s array_keys, súhlas, dĺžka správy. Každú kontrolu vyskúšaj: pošli zlú hodnotu a pozri hlášku.
Úloha 6.6: Prehliadač nestačí. F12, v <input> pre meno zmaž required, odošli prázdne. process.php chybu chytí. Ak nie, kontrola chýba.
Úloha 6.7: XSS. Do mena napíš <script>alert('ahoj')</script>, odošli. Ak vyskočí okno, nájdi v process.php výpis bez htmlspecialchars a oprav ho. Prejdi všetky výpisy hodnôt od používateľa, aj $value v loop. Do README.md v repository dopíš dve vety: čo sa stalo pred opravou a po nej.
Úloha 6.8: Výpočty. Prompt z Ukážky 7. Doplň // DOPLŇ: vlastný výpočet niečím zo svojej témy (dni od, roky do, počet znakov, percento…).
Úloha 6.9: Samospracujúci form. Prompt z Ukážky 8. Výsledok ulož ako web/content/register.php. Doplň // DOPLŇ: skopíruj kontroly z process.php a doplň chýbajúce field. Na sigma: otvor Registráciu z menu (prázdny form), odošli s chybou (hodnoty zostali, červené fields), odošli správne (zhrnutie). process.php v repository nechaj, je to cvičný súbor ako variables.php.
Úloha 6.10: Chyba naschvál. V web/content/register.php prepíš v jednom $_POST['email'] key na $_POST['emial'], odošli form, prečítaj, čo sa stalo (hláška, alebo tichá chyba vďaka ??). Oprav. Potom zmaž method="post", odošli, pozri adresu. Oprav.
Úloha 6.11: Commit a push. Podľa návodu 04 Odovzdávanie, časť 5; commit po každej hotovej úlohe. Výsledok testov podľa časti 6.
Úloha 6.12: Upload Folder a kontrola na sigma. Pravý klik na cv05, Upload Folder. Over web/index.php, web/routes.php, web/form.php (prázdny, s chybou, správne), web/contact.php a practice/process.php (otvorený priamo je prázdny).
Hodnotenie: 1 bod. V repository cv05 na GitHub aj na sigma je form spracovaný cez POST, process.php s kontrolami a výpočtami, content/register.php ako samospracujúci form s ošetrenými výpismi. Commit a push najneskôr do nasledujúceho cvičenia.
Uzávierka 2 je koniec tohto týždňa: form spracúva PHP s validáciou vstupov a ošetrením výstupov, beží na sigma. Kolo 1 obhajob (statika a PHP) sa obhajuje z kópie obhajoba1/cv05, príkaz je nižšie.
You get the tasks also as the assignment cv05 in Classroom 50, they are in the file README.md in your repository.
Link to the assignment cv05: accept the assignment
(valid for B. Stehlíková’s groups; the other groups get the link from their lab teacher)
Task 6.1: Preparing Kubeflow. Prepare Kubeflow following guide 04 Submitting, part 1: WEB is at the top of Explorer, Go Live is at the bottom on the status bar. If it is not there, this command in the terminal brings the extensions back:
code-server --install-extension Natizyskunk.sftp --install-extension yandeu.five-server --install-extension bmewburn.vscode-intelephense-client --install-extension mblode.twig-language-2
Then F1, Developer: Reload Window. The connection settings for sigma stay.
Task 6.2: The assignment and a copy of last week. Accept the assignment cv05 in Classroom 50 (the link is above) and clone the repository into ~/web/ti/cv05 following guide 04, parts 2 and 3. Then copy your website from last week into it:
cd ~/web/ti
rsync -a --exclude .git --exclude .github --exclude README.md cv04/ cv05/
Right-click cv05, Upload Folder. Check on sigma …/ti/cv05/web/ that the website runs.
Task 6.3: The form to POST. In web/content/register.php check that all fields have English name and value without diacritics (the checkbox group has []). Add method="post" and action="../practice/process.php". Submit the form: the address after submitting has no ? and the page reports that process.php does not exist. That is fine.
Task 6.4: process.php. The prompt from Example 6 with your form. Save the result as practice/process.php. Fill in the form on sigma, submit, look at print_r. Submit it also with a checkbox unchecked and see which key is missing.
Task 6.5: Checks by hand. Complete // DOPLŇ: check for all remaining fields: the date via strtotime (and that it is not in the future, if that makes sense for your topic), select and radio via in_array with array_keys, consent, the length of the message. Try every check: send a bad value and look at the message.
Task 6.6: The browser is not enough. F12, delete required in the <input> for the name, submit empty. process.php catches the error. If not, a check is missing.
Task 6.7: XSS. Type <script>alert('hi')</script> into the name, submit. If a window pops up, find the output without htmlspecialchars in process.php and fix it. Go through all outputs of values from the user, also $value in the loop. Add two sentences to README.md in the repository: what happened before the fix and after it.
Task 6.8: Calculations. The prompt from Example 7. Complete // DOPLŇ: my own calculation with something from your topic (days since, years until, number of characters, percentage…).
Task 6.9: The self-processing form. The prompt from Example 8. Save the result as web/content/register.php. Complete // DOPLŇ: copy the checks from process.php and complete the missing field. On sigma: open Registration from the menu (an empty form), submit with an error (the values stayed, red fields), submit correctly (the summary). Leave process.php in the repository, it is a practice file like variables.php.
Task 6.10: An error on purpose. In web/content/register.php change one $_POST['email'] key to $_POST['emial'], submit the form, read what happened (a message, or a silent error thanks to ??). Fix it. Then delete method="post", submit, look at the address. Fix it.
Task 6.11: Commit and push. Following guide 04 Submitting, part 5; commit after every finished task. The test result following part 6.
Task 6.12: Upload Folder and the check on sigma. Right-click cv05, Upload Folder. Check web/index.php, web/routes.php, web/form.php (empty, with an error, correct), web/contact.php and practice/process.php (opened directly it is empty).
Grading: 1 point. In the repository cv05 on GitHub and on sigma the form is processed via POST, process.php has checks and calculations, content/register.php is a self-processing form with treated outputs. Commit and push by the next lab at the latest.
Deadline 2 is the end of this week: the form is processed by PHP with input validation and output treatment, it runs on sigma. Round 1 of the defences (static site and PHP) is defended from the copy obhajoba1/cv05, the command is below.
Obhajoba a live codingDefence and live coding
Pri obhajobe budú použité iba otázky a úlohy z týchto zoznamov. Live coding robíš v kópii, odovzdaný stav v cv05 sa nezmení. Kópiu si priprav pred obhajobou:
cd ~/web/ti
mkdir -p obhajoba1
rsync -a --exclude .git cv05/ obhajoba1/cv05/
Potom klikni pravým na priečinok obhajoba1 a v menu úplne dole zvoľ Upload Folder. Kópia je na https://sigma.tuke.sk/student/meno.priezvisko/ti/obhajoba1/cv05/.
Vysvetli (code walkthrough)
- Aký je rozdiel medzi GET a POST a kedy ktorú použiješ.
- Čo robí
methoda čoactionvo form; čo znamenáaction="". - Čo je
$_POST, odkiaľ sa berú jeho key a value. - Prečo je
sincev$_POSTtext a čo s tým. - Prečo nezaškrtnutý checkbox v
$_POSTnie je a ako sa to rieši. - Čo robí
??. - Prečo má
interestvnamehranaté zátvorky a ako sa vypíše. - Čo robí
is_arrayv loop. - Prečo
requiredv HTML nestačí. - Čo robí
trima prečo je prvý. - Čo robí
filter_varsFILTER_VALIDATE_EMAILa čo robí!pred ním. - Prečo sa select a radio kontrolujú cez
in_arraya čo urobíarray_keys($grades). - Čo je v
$errorsa prečo je asociatívne. - Čo vráti
strtotimepre neplatný dátum a ako to zistíš. - Ako vypočítaš dni medzi dvoma dátumami; čo je 86 400.
- Prečo je pri
date('Y')niekedy(int). - Čo je XSS a čo sa ním dá urobiť.
- Čo robí
htmlspecialcharsa čo znamenajú jeho tri parametre. - Prečo sa ošetruje výstup a nie vstup.
- Čo je v
$_SERVER['REQUEST_METHOD']a kedy jePOST. - Ako form vráti vyplnenú hodnotu do
input,select,radio,checkbox. - Prečo sa
<option>vypisujú loop z array. - Čo robí class
is-invalida kde sa berie text pod field. - Prečo sa po F5 prehliadač pýta na opätovné odoslanie.
Uprav (live coding)
- Pridaj kontrolu, že správa má najviac 200 znakov, a hlášku pri field.
- Zmeň minimálnu dĺžku mena na 2 a rozsah roka od 1900.
- Pridaj do array obťažností novú možnosť a over, že je vo form aj v kontrole.
- Pridaj do form nové textové field (napr. mesto) a sprav ho povinné aj so zapamätaním hodnoty.
- Vypíš v zhrnutí počet zaškrtnutých záujmov.
- Zmeň výpočet dní na týždne.
- Vypíš v zhrnutí dátum prvej návštevy aj s názvom dňa.
- Ukáž XSS cez field správa a oprav ho.
- Zmeň vo form
methodna GET a ukáž, kde sa údaje objavia; vráť späť. - Zmeň hlášku v
$errorspre e-mail a ukáž, kde sa prejaví.
Zdôvodni (design decisions)
- Prečo server kontroluje údaje, aj keď ich kontroluje prehliadač.
- Prečo sa ošetruje výstup cez
htmlspecialcharsa vstup sa nemení. - Prečo registrácia ide cez POST a nie GET.
- Prečo je zoznam možností v array a nie napísaný v
<option>. - Prečo sa form spracúva v tom istom súbore a nie v
process.php. - Prečo
$errorsmá key podľa field.
Definition of Done
- Repository cv05 je na GitHub a posledný commit má zelenú ✓; web beží na sigma.
- Form má
method="post", anglickéname;process.phpukazuje$_POSTtromi spôsobmi, kontroluje všetky fields a počíta z nich. content/register.phpsa spracuje sám: pamätá hodnoty, ukazuje chyby pri fields, po úspechu zhrnutie; každý výpis od používateľa je cezhtmlspecialchars.- Vieš ukázať XSS a vysvetliť, prečo sa po oprave nevykoná.
- Každý riadok PHP vo svojich súboroch vieš vysvetliť.
At the defence only questions and tasks from these lists are used. You do the live coding in a copy, the submitted state in cv05 does not change. Prepare the copy before the defence:
cd ~/web/ti
mkdir -p obhajoba1
rsync -a --exclude .git cv05/ obhajoba1/cv05/
Then right-click the folder obhajoba1 and choose Upload Folder at the very bottom of the menu. The copy is at https://sigma.tuke.sk/student/meno.priezvisko/ti/obhajoba1/cv05/.
Explain (code walkthrough)
- What is the difference between GET and POST and when you use which.
- What
methodand whatactiondo in a form; whataction=""means. - What
$_POSTis, where its keys and values come from. - Why
sinceis text in$_POSTand what to do about it. - Why an unchecked checkbox is not in
$_POSTand how that is handled. - What
??does. - Why
interesthas square brackets innameand how it is printed. - What
is_arraydoes in the loop. - Why
requiredin HTML is not enough. - What
trimdoes and why it comes first. - What
filter_varwithFILTER_VALIDATE_EMAILdoes and what!before it does. - Why select and radio are checked via
in_arrayand whatarray_keys($grades)does. - What is in
$errorsand why it is associative. - What
strtotimereturns for an invalid date and how you find that out. - How you calculate the days between two dates; what 86,400 is.
- Why there is sometimes
(int)atdate('Y'). - What XSS is and what can be done with it.
- What
htmlspecialcharsdoes and what its three parameters mean. - Why the output is treated and not the input.
- What is in
$_SERVER['REQUEST_METHOD']and when it isPOST. - How the form returns the filled-in value into
input,select,radio,checkbox. - Why the
<option>s are printed with a loop from an array. - What the class
is-invaliddoes and where the text below the field comes from. - Why the browser asks about resubmitting after F5.
Modify (live coding)
- Add a check that the message has at most 200 characters, and a message at the field.
- Change the minimum length of the name to 2 and the year range from 1900.
- Add a new option to the grades array and check that it is in the form and in the check.
- Add a new text field to the form (e.g. city), make it required and remember its value.
- Print the number of checked interests in the summary.
- Change the calculation of days to weeks.
- Print the date of the first visit with the name of the day in the summary.
- Show XSS through the message field and fix it.
- Change
methodin the form to GET and show where the data appears; put it back. - Change the message in
$errorsfor the e-mail and show where it appears.
Justify (design decisions)
- Why the server checks the data even when the browser checks it.
- Why the output is treated with
htmlspecialcharsand the input is not changed. - Why the registration goes through POST and not GET.
- Why the list of options is in an array and not written in
<option>. - Why the form is processed in the same file and not in
process.php. - Why
$errorshas the key by the field.
Definition of Done
- The repository cv05 is on GitHub and the last commit has a green ✓; the website runs on sigma.
- The form has
method="post", Englishname;process.phpshows$_POSTin three ways, checks all fields and calculates from them. content/register.phpprocesses itself: remembers the values, shows errors at the fields, after success a summary; every output from the user goes throughhtmlspecialchars.- You can show XSS and explain why it does not run after the fix.
- You can explain every line of PHP in your files.