ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Contact form က feature တစ်ခုလို ထင်ရပေမယ့် တကယ်တော့ pipeline သေးသေးလေးတစ်ခုပါ။ ဧည့်သည်က ရိုက်တယ်၊ PHP က data ကို စစ်တယ်၊ database က သိမ်းတယ်၊ စာမျက်နှာက ရလဒ်ကို ပြတယ်။ အဆင့်တစ်ခုစီကို function သေးသေးလေးတစ်ခုစီအဖြစ် ရေးထားရင် browser မဖွင့်ဘဲ တစ်ခုလုံးကို စမ်းလို့ရပါတယ်။ $_POST နဲ့ ပုံစံတူတဲ့ array တစ်ခုကို function ထဲ ပေးလိုက်ပြီး ပြန်လာတာကို ဖတ်ရုံပါပဲ။
ဒီ project မှာ အဲဒီ function က handle() ပါ။ တကယ့် စာမျက်နှာက နောက်ပိုင်း handle($_POST, ...) ကို ခေါ်မှာဖြစ်ပြီး ဒီမှာတော့ ကြိုရေးထားတဲ့ array တွေနဲ့ ခေါ်ပါမယ်။
Problem → Why → Solution
ပြဿနာ: အားလုံး တစ်နေရာတည်းမှာ ရောနေတဲ့ script
Contact form အများစုရဲ့ ပထမ version က script တစ်ခုတည်းပါ။ $_POST ကို ဖတ်၊ တန်ဖိုးတွေကို INSERT ထဲ တိုက်ရိုက်ကပ်၊ "Thanks" ကို print ထုတ်ပါတယ်။ မြန်ပေမယ့် ပြဿနာ အနည်းဆုံး ငါးခု ရှိပါတယ်။ Field မပါရင် "Undefined array key" warning တက်ပါတယ်။ ဧည့်သည်ရိုက်သမျှ SQL ထဲ တိုက်ရိုက်ဝင်တာမို့ injection ဖြစ်နိုင်ပါတယ်။ ရိုက်သမျှကို HTML အဖြစ် ပြန်ပြတာမို့ XSS ဖြစ်နိုင်ပါတယ်။ ဗလာနဲ့ အဓိပ္ပာယ်မရှိတဲ့ message တွေ သိမ်းမိပါတယ်။ Refresh နှိပ်ရင် form ကို ပြန်ပို့ပြီး နှစ်ခါ သိမ်းပါတယ်။
အဆိုးဆုံးက ဒါကို browser ထဲမှာ form ကို လက်နဲ့ထပ်ခါထပ်ခါ ဖြည့်ပြီးမှ စမ်းလို့ရတာပါ။
<?php
// Everything in one place: reading, saving and printing are tangled together.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$conn->query("INSERT INTO contacts (name, email, message) VALUES (
'{$_POST['name']}', '{$_POST['email']}', '{$_POST['message']}')");
echo "Thanks, {$_POST['name']}!";
}ဘာကြောင့် စမ်းဖို့ ခက်တာလဲ
အဆင့်တိုင်းက web request နဲ့ ကပ်နေပါတယ်။ $_POST ကို တိုက်ရိုက်ဖတ်ပြီး တိုက်ရိုက် print ထုတ်ပါတယ်။ တစ်ခုချင်းစီကို သီးသန့်ခေါ်လို့ မရတာမို့ မြန်မြန်စမ်းလို့လည်း မရပါဘူး။ အဆင့်တွေကို ခွဲလိုက်ရင် တစ်ခုစီမှာ ရှင်းလင်းတဲ့ input နဲ့ output ရှိလာပါတယ်။
Core concept: checkpoint တန်းစီပုံစံ
Submission တစ်ခုက checkpoint တွေကို အစီအစဉ်အတိုင်း ဖြတ်ရပါတယ်။ ဘယ် checkpoint မှာမဆို ပယ်ချခံရရင် အဲဒီအဆင့်မှာပဲ ရပြီး နောက်အဆင့်တွေ မလုပ်တော့ပါဘူး။ Handler က ဘာမှ print မထုတ်ဘဲ status တစ်ခု ပြန်ပေးပါတယ်၊ ဒါကြောင့် စာမျက်နှာကော test ကော နှစ်ခုလုံးက အဲဒီ status ကို သုံးနိုင်ပါတယ်။
၁။ Request adapter
handle(array $post, string $sessionToken, ContactStore $store) က superglobal ကို မထိပါဘူး၊ array ကိုပဲ လက်ခံပါတယ်။ $_POST ကို ထိတဲ့နေရာက web page ဖိုင်တစ်ခုတည်း ဖြစ်ပါတယ်။ ဒါကြောင့် test ထဲမှာ $_POST အစား ရိုးရိုး array ပို့လို့ ရပါတယ်။
၂။ CSRF token နဲ့ honeypot
CSRF token က form ကို သင့် site က ဒီဧည့်သည့် session အတွက် ထုတ်ပေးခဲ့တာ ဟုတ်မဟုတ် သက်သေပြပါတယ်။ hash_equals() နဲ့ နှိုင်းယှဉ်ပါ၊ ဒါက စာကြောင်းနှစ်ခု ဘယ်နေရာမှာ ကွဲကွဲ အချိန်တူတူ ယူပါတယ်။ Honeypot က CSS နဲ့ ဖျောက်ထားတဲ့ input ပါ၊ လူက မဖြည့်ပေမယ့် bot က အကုန်ဖြည့်ပါတယ်။ Bot ကို ဘာကျလဲ မပြောဘဲ တိတ်တိတ်ပဲ လျစ်လျူရှုပါ။
၃။ Validation
validate() က [clean values, errors] ပြန်ပါတယ်။ trim လုပ်၊ is_string နဲ့ type စစ် (name[]=x ကပို့ရင် array ရောက်လာနိုင်ပါတယ်)၊ ဖြည့်ရမယ့် field စစ်၊ mb_strlen နဲ့ အရှည်စစ်၊ filter_var နဲ့ email စစ်ပါတယ်။ Error အားလုံးကို စုပေးလို့ ဧည့်သည်က တစ်ခါတည်း ပြင်နိုင်ပါတယ်။
၄။ Storage
ContactStore က PDO ကို ထုပ်ထားပါတယ်။ UNIQUE (email, message) က ထပ်နေတာကို ကိုင်တွယ်တဲ့ စည်းမျဉ်းပါ။ Request နှစ်ခု တစ်ပြိုင်နက် ဝင်လာလည်း database က တစ်ခုကိုပဲ လက်ခံပါတယ်။ SQLSTATE 23000 ကို ဖမ်းပြီး false ပြန်ပါတယ်။
၅။ Output
Escape လုပ်တာကို သိမ်းတဲ့အချိန်မှာ မဟုတ်ဘဲ HTML ထဲ ထုတ်တဲ့အချိန်မှာ လုပ်ပါ။ Data ကို မူလအတိုင်း သိမ်းထားမှ CSV export၊ email၊ JSON တွေမှာ မှန်ကန်ပါတယ်။ htmlspecialchars() ကို HTML နယ်နိမိတ်မှာပဲ ခေါ်ပါ။
| Status | ဖြစ်စေတဲ့အကြောင်း | ဧည့်သည်မြင်ရတာ |
|---|---|---|
| saved | စစ်ဆေးမှုအားလုံးအောင် | ကျေးဇူးတင်စာမျက်နှာ |
| invalid | Validation error | Error စာနဲ့ အဟောင်းတန်ဖိုးပါတဲ့ form |
| duplicate | email + message တူတာ သိမ်းပြီးသား | "လက်ခံပြီးပါပြီ" ဆိုတဲ့ စာ |
| forbidden | CSRF token မှား/မပါ | "Form သက်တမ်းကုန်" စာ |
| ignored | Honeypot ဖြည့်ထား | ပုံမှန်ထင်ရတဲ့ ကျေးဇူးတင်စာ |
- Request က array အဖြစ် ရောက်လာ
- Token နဲ့ honeypot ကို စစ်
- validate() က clean + errors ပြန်
- သိမ်းပြီး status ပြန်
Handler က ဘာမှ print မထုတ်ဘူး။ Status ပဲ ပြန်တာမို့ စာမျက်နှာနဲ့ test နှစ်ခုလုံး သုံးနိုင်ပါတယ်။
အခြေခံ ပုံစံ
<?php
function handleSubmission(array $input, Service $service): array
{
// 1. confirm the request is allowed (token, honeypot)
// 2. validate and clean the input
// 3. if anything is wrong, return the errors
// 4. store the clean data
// 5. return a status the page can display
}Handler function တစ်ခုက input array နဲ့ dependency တစ်ခုကို လက်ခံပြီး အဆင့်ငါးဆင့်ကို အစီအစဉ်အတိုင်း လုပ်ကာ status array တစ်ခု ပြန်ပါတယ်။
စမ်းလို့ရတဲ့ contact handler
ဒီ file မှာ ContactStore (PDO + UNIQUE)၊ validate() နဲ့ handle() ပါပါတယ်။ အောက်ပိုင်းမှာ $good ဆိုတဲ့ မှန်ကန်တဲ့ submission တစ်ခုကို array_replace() နဲ့ တစ်နေရာချင်းစီ ပျက်အောင်လုပ်ပြီး အမျိုးမျိုးသော request ကို ပုံစံတူ ဖန်တီးထားပါတယ်။ Browser၊ web server၊ stdin ဘာမှ မလိုဘဲ run ပါတယ်။ Course ရဲ့ MySQL lesson တွေမှာ MySQL ကို သုံးပေမယ့် ဒီမှာ PDO + SQLite ကို သုံးထားလို့ MySQL server မလိုပါဘူး။
<?php
declare(strict_types=1);
final class ContactStore
{
public function __construct(private PDO $pdo)
{
$this->pdo->exec('CREATE TABLE IF NOT EXISTS contacts (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL,
message TEXT NOT NULL,
UNIQUE (email, message)
)');
}
/** Returns false when the same email + message is already stored. */
public function save(array $clean): bool
{
$stmt = $this->pdo->prepare(
'INSERT INTO contacts (name, email, message) VALUES (:name, :email, :message)'
);
try {
$stmt->execute($clean);
return true;
} catch (PDOException $e) {
if ($e->getCode() === '23000') { // integrity constraint violation
return false;
}
throw $e;
}
}
public function all(): array
{
$rows = $this->pdo->query('SELECT name, email FROM contacts ORDER BY id');
return $rows->fetchAll(PDO::FETCH_ASSOC);
}
}
/** @return array{0: array<string, string>, 1: array<string, string>} [clean, errors] */
function validate(array $post): array
{
$clean = [];
foreach (['name', 'email', 'message'] as $field) {
$value = $post[$field] ?? '';
$clean[$field] = is_string($value) ? trim($value) : '';
}
$errors = [];
if ($clean['name'] === '') {
$errors['name'] = 'Name is required.';
} elseif (mb_strlen($clean['name']) > 60) {
$errors['name'] = 'Name must be 60 characters or fewer.';
}
if (filter_var($clean['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Enter a valid email address.';
}
if (mb_strlen($clean['message']) < 10) {
$errors['message'] = 'Message must be at least 10 characters.';
}
return [$clean, $errors];
}
function handle(array $post, string $sessionToken, ContactStore $store): array
{
$token = $post['csrf'] ?? '';
if (!is_string($token) || !hash_equals($sessionToken, $token)) {
return ['status' => 'forbidden', 'errors' => ['csrf' => 'Form expired, reload.']];
}
if (($post['website'] ?? '') !== '') { // honeypot field: only bots fill it in
return ['status' => 'ignored', 'errors' => []];
}
[$clean, $errors] = validate($post);
if ($errors !== []) {
return ['status' => 'invalid', 'errors' => $errors];
}
if (!$store->save($clean)) {
return ['status' => 'duplicate', 'errors' => ['message' => 'Already received.']];
}
return ['status' => 'saved', 'errors' => []];
}
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$store = new ContactStore($pdo);
$token = 'token-from-session';
$good = [
'csrf' => $token,
'name' => 'Aung Aung',
'email' => 'aung@example.com',
'message' => 'I would like a quote for a small website.',
];
$submissions = [
'valid' => array_replace($good, ['name' => ' Aung Aung ']),
'duplicate' => $good,
'empty form' => ['csrf' => $token],
'bad email' => array_replace($good, ['email' => 'aung@example']),
'short text' => array_replace($good, ['message' => 'Hi']),
'bot' => $good + ['website' => 'http://spam.example'],
'wrong token' => array_replace($good, ['csrf' => 'guess']),
'array field' => array_replace($good, ['name' => ['x']]),
'html in name' => array_replace($good, [
'name' => 'Su <b>Su</b>',
'email' => 'su@example.com',
]),
'Myanmar name' => array_replace($good, [
'name' => 'မောင်မောင်',
'email' => 'maung@example.com',
]),
];
foreach ($submissions as $label => $post) {
$result = handle($post, $token, $store);
echo str_pad($label, 13) . $result['status'];
if ($result['errors'] !== []) {
echo ' -> ' . implode(' | ', $result['errors']);
}
echo "\n";
}
echo "\nStored contacts (escaped for HTML output):\n";
foreach ($store->all() as $row) {
echo ' ' . htmlspecialchars($row['name']) . ' <' . $row['email'] . ">\n";
}Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Duplicates are a database rule
UNIQUE (email, message)SELECT နဲ့ အရင်စစ်ပြီးမှ INSERT လုပ်ရင် တစ်ပြိုင်နက် request နှစ်ခုက နှစ်ခုလုံး "မရှိသေးဘူး" လို့ မြင်ပြီး နှစ်ခုလုံး ထည့်မိနိုင်ပါတယ်။ UNIQUE ကတော့ database ကိုယ်တိုင် ကာကွယ်ပါတယ်။
- Portable duplicate detection
if ($e->getCode() === '23000') { // integrity constraint violationSQLSTATE 23000 က constraint ချိုးတာအားလုံးအတွက် standard code ဖြစ်လို့ MySQL မှာလည်း အလုပ်လုပ်ပါတယ်။ တခြား error တွေကိုတော့ throw $e နဲ့ ပြန်ပစ်ပြီး ဖုံးမထားပါဘူး။
- Never trust the type
$clean[$field] = is_string($value) ? trim($value) : '';Request ထဲမှာ name[]=x လို့ ထည့်ပို့ရင် $post['name'] က array ဖြစ်ပါတယ်။ is_string စစ်ထားလို့ "array field" လိုင်းမှာ warning မတက်ဘဲ "Name is required." ကိုပဲ ရပါတယ်။
- Characters, not bytes
mb_strlen($clean['name']) > 60strlen() က byte ကို ရေတွက်ပြီး mb_strlen() က စာလုံးကို ရေတွက်ပါတယ်။ မြန်မာနာမည် "မောင်မောင်" က bytes ၃၀ ရှိပေမယ့် စာလုံး ၁၀ လုံးပဲ ရှိလို့ အရှည်ကန့်သတ်ချက်ကို တရားမျှတစွာ သုံးနိုင်ပါတယ်။
- Compare tokens safely
!hash_equals($sessionToken, $token)hash_equals() က ပထမနေရာမှာ သိထားတဲ့ token ကိုထားပြီး timing အပေါ်မူတည်တဲ့ တိုက်ခိုက်မှုကို ကာကွယ်ပါတယ်။ ရိုးရိုး === လည်း အလုပ်လုပ်ပေမယ့် secret နှိုင်းယှဉ်ရာမှာ hash_equals က အကြံပြုထားတာပါ။
- Return a status, never print
return ['status' => 'invalid', 'errors' => $errors];Handler က status နဲ့ error စာတွေကို data အနေနဲ့ပဲ ပြန်ပေးပါတယ်။ ဒီအတွက် main script ရဲ့ foreach loop က output အားလုံးကို ကိုယ်တိုင် ပုံစံချပြီး print နိုင်ပါတယ်။
- Escape only when printing
htmlspecialchars($row['name'])Database ထဲမှာ Su <b>Su</b> ဆိုတဲ့ မူရင်းစာသားကို သိမ်းထားပြီး HTML အတွက် print ထုတ်တဲ့အခါမှ < နဲ့ > ကို escape လုပ်ထားတဲ့ပုံစံ ပြောင်းပါတယ်။ နောက်ဆုံး output စာကြောင်းတွေမှာ အဲဒီရလဒ်ကို မြင်ရပါမယ်။
valid saved
duplicate duplicate -> Already received.
empty form invalid -> Name is required. | Enter a valid email address. | Message must be at least 10 characters.
bad email invalid -> Enter a valid email address.
short text invalid -> Message must be at least 10 characters.
bot ignored
wrong token forbidden -> Form expired, reload.
array field invalid -> Name is required.
html in name saved
Myanmar name saved
Stored contacts (escaped for HTML output):
Aung Aung <aung@example.com>
Su <b>Su</b> <su@example.com>
မောင်မောင် <maung@example.com>Output ကို တစ်လိုင်းချင်း ဖတ်ကြည့်ရအောင်
- valid: နာမည်ရှေ့နောက်က space တွေကို trim လုပ်ပြီး ပထမဆုံး row ကို သိမ်းပါတယ်။
- duplicate: email နဲ့ message တူလို့ UNIQUE ချိုးပြီး save() က false ပြန်ပါတယ်။
- empty form: field သုံးခုစလုံးရဲ့ error ကို စုပေးပါတယ်၊ ပထမ error တစ်ခုတည်းမဟုတ်ပါဘူး။
- bot: honeypot ဖြည့်ထားလို့ ဘာ error စာမှမပြဘဲ ignored ပါ။
- wrong token: validation မလုပ်ခင်မှာတင် forbidden ပါ။ Token မမှန်တဲ့ request အတွက် ကျန်တဲ့အလုပ်တွေ မလုပ်ရပါဘူး။
- html in name နဲ့ Myanmar name: နှစ်ခုလုံး ကောင်းစွာသိမ်းပါတယ်။ Tag တွေကို ပယ်ချတာမဟုတ်ဘဲ output မှာ escape လုပ်တာပါ။
Form ကို ပြန်ပြတဲ့အခါ
Validation မအောင်ရင် ဧည့်သည်ရိုက်ထားတာတွေကို form ထဲ ပြန်ထည့်ပေးရပါတယ်၊ မဟုတ်ရင် message အရှည်ကြီးကို ပြန်ရိုက်ရပါမယ်။ ဒီအခါ ဧည့်သည်ရဲ့ စာသားက HTML ထဲ ရောက်တာမို့ e() ကို သုံးရပါတယ်။ ဒီမှာ textarea ရဲ့ တန်ဖိုးက value attribute ထဲ မဟုတ်ဘဲ tag နှစ်ခုကြားမှာ ရှိတာကို သတိပြုပါ။ PHP 8.1 ကစပြီး htmlspecialchars ရဲ့ default flag တွေမှာ ENT_QUOTES ပါပြီးသားပေမယ့် flag ကို ကိုယ်တိုင်ရေးထားတာက ရှင်းပါတယ်။
<?php
function e(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function renderForm(array $old, array $errors): string
{
$html = "<form method=\"post\">\n";
foreach (['name', 'email'] as $field) {
$value = e($old[$field] ?? '');
$html .= " <input name=\"$field\" value=\"$value\">\n";
if (isset($errors[$field])) {
$html .= ' <p class="error">' . e($errors[$field]) . "</p>\n";
}
}
$html .= ' <textarea name="message">' . e($old['message'] ?? '') . "</textarea>\n";
return $html . '</form>';
}
$old = [
'name' => 'Su "the <b>boss</b>"',
'email' => 'su@example',
'message' => 'Is 5 < 7 & 7 > 5?',
];
$errors = ['email' => 'Enter a valid email address.'];
echo renderForm($old, $errors) . "\n";<form method="post">
<input name="name" value="Su "the <b>boss</b>"">
<input name="email" value="su@example">
<p class="error">Enter a valid email address.</p>
<textarea name="message">Is 5 < 7 & 7 > 5?</textarea>
</form>Quote၊ < ၊ & စတာတွေ ပါတဲ့ ရိုက်ထားတဲ့စာသားက attribute ကို မဖျက်နိုင်ဘဲ စာသားအဖြစ်ပဲ ပြပါတယ်။ ဒါကြောင့် XSS ကို ကာကွယ်ပါတယ်။
handle() ကို တကယ့် စာမျက်နှာနဲ့ ချိတ်ခြင်း
တကယ့် စာမျက်နှာက web server ပေါ်မှာ run တာမို့ ဒီ lesson မှာ run မပြပါဘူး။ session ထဲက token နဲ့ $_POST ကို handle() ထဲ ပို့ရုံပါပဲ။ အောင်မြင်ရင် ကျေးဇူးတင်စာမျက်နှာကို redirect လုပ်ပါ (Post/Redirect/Get)။ ဒါဆို refresh နှိပ်လည်း form ကို ပြန်ပို့မှာ မဟုတ်လို့ နှစ်ခါ သိမ်းတာ ကာကွယ်ပါတယ်။
<?php
// contact.php: runs on a web server, so it is not executed in this lesson.
declare(strict_types=1);
session_start();
if (empty($_SESSION['csrf'])) {
$_SESSION['csrf'] = bin2hex(random_bytes(32)); // new token for this visitor
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$result = handle($_POST, $_SESSION['csrf'], $store);
if ($result['status'] === 'saved') {
header('Location: /thanks.php'); // Post/Redirect/Get: a refresh cannot re-submit
exit;
}
// otherwise render the form again with $result['errors'] and the old values
}လက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
Contact form၊ newsletter signup၊ support ticket form တွေအားလုံး ဒီပုံစံပါပဲ: token စစ်၊ validate၊ သိမ်း၊ status ပြန်ပါတယ်။ Production မှာတော့ IP တစ်ခုကို မိနစ်အတွင်း submission အရေအတွက် ကန့်သတ်တဲ့ rate limiting၊ CAPTCHA၊ ဝန်ထမ်းကို email ပို့တဲ့ notification တွေ ထပ်ထည့်ကြပါတယ်။ Email ပို့တာကို commit ပြီးမှ လုပ်ပါ၊ ဒါမှ message မသိမ်းရဘဲ email ထွက်သွားတာမျိုး မဖြစ်ပါဘူး။ ဒီလို ထပ်တိုးတာတွေကြောင့် handle() ကို သီးခြားထားတာ တန်ပါတယ်၊ စာမျက်နှာ file ပြောင်းသွားပေမယ့် စမ်းပြီးသား core က မပြောင်းပါဘူး။
PDOException ရဲ့ message ကို ဧည့်သည်ကို ဘယ်တော့မှ မပြပါနဲ့၊ table နာမည်တွေ ပေါက်ကြားနိုင်ပါတယ်။ Log ထဲပဲ ရေးပြီး ဧည့်သည်ကို "နောက်မှ ပြန်ကြိုးစားပါ" လို့ ပြပါ။ Message တွေမှာ ကိုယ်ရေးကိုယ်တာ အချက်အလက် ပါလို့ ဘယ်လောက်ကြာကြာ သိမ်းမလဲ၊ ဖျက်ပေးဖို့ တောင်းရင် ဘယ်လိုလုပ်မလဲ ကြိုဆုံးဖြတ်ထားဖို့လည်း လိုပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
Escape ကို သိမ်းတဲ့အချိန်မှာ လုပ်တာ
htmlspecialchars() လုပ်ပြီးမှ သိမ်းရင် database ထဲမှာ escape လုပ်ပြီးသား စာသားတွေ ရှိနေပြီး CSV ထုတ်တဲ့အခါ၊ email ပို့တဲ့အခါ အဲဒီ entity code တွေပါ ပေါ်ပါလိမ့်မယ်။ ထပ်ပြီး escape လုပ်မိရင် escape လုပ်ပြီးသား စာသားကို ထပ်ပြောင်းလို့ double-escape ဖြစ်ပါတယ်။ မူရင်းကို သိမ်းပြီး HTML ထုတ်တဲ့အခါမှ escape လုပ်ပါ။
$_POST ရဲ့ ပုံစံကို ယုံတာ
$_POST['name'] က အမြဲ string လို့ မယူပါနဲ့။ name[]=x နဲ့ array ရောက်လာနိုင်ပြီး field လုံးဝမပါလည်း ဖြစ်နိုင်ပါတယ်။ ?? '' နဲ့ is_string() ကို သုံးပါ၊ ဒါမှ "Undefined array key" နဲ့ "Array to string conversion" warning တွေ မတက်ပါဘူး။
SELECT ပြီးမှ INSERT နဲ့ ထပ်နေတာကို စစ်တာ
Request နှစ်ခု တစ်ပြိုင်နက်ဝင်ရင် နှစ်ခုလုံး SELECT မှာ "မရှိသေးဘူး" လို့ မြင်ပြီး နှစ်ခုလုံး INSERT လုပ်မိပါတယ်။ UNIQUE constraint ကို ထားပြီး constraint error ကို ဖမ်းပါ။ SELECT စစ်တာကို ချစ်စရာ error message အတွက်ပဲ ထပ်ထည့်လို့ရပါတယ်။
Textarea တန်ဖိုးကို value attribute ထဲ ထည့်တာ
<input> မှာ တန်ဖိုးက value="..." ထဲ ဝင်ပေမယ့် <textarea> ရဲ့ တန်ဖိုးက tag ဖွင့်ပိတ်ကြားမှာ ရှိရပါတယ်။ value attribute ထဲ ထည့်ရင် browser က လျစ်လျူရှုပြီး ဧည့်သည်ရဲ့ message ပျောက်ပါတယ်။
Mini challenge
Newsletter signup handler ရေးကြည့်ပါ
subscribe(array $post, PDO $pdo): string ကို ရေးပါ။ ဧည့်သည်ရဲ့ email နဲ့ နာမည်ကို လက်ခံပြီး မှန်ကန်ရင် subscribers table ထဲ သိမ်းပါ။ သဘောတူညီချက် (consent) checkbox က "1" ဖြစ်ရပါမယ်။ Email တူတာကို စာလုံးအကြီးအသေးမခွဲဘဲ ထပ်နေတယ်လို့ သတ်မှတ်ပါ။ Browser မလိုပါဘူး၊ ရေးပေးထားတဲ့ array တွေနဲ့ စမ်းပါ။
- email ဒါမှမဟုတ် name က string မဟုတ်ရင် "invalid: fields must be text" ပြန်ပါ
- trim လုပ်ပြီး email ကို lowercase ပြောင်းပါ၊ name ဗလာဆိုရင် "friend" ထားပါ
- filter_var နဲ့ email စစ်ပြီး အမှားရင် "invalid: email"၊ consent မှားရင် "invalid: consent is required" ပြန်ပါ
- Prepared INSERT ကို သုံးပါ။ SQLSTATE 23000 ဆိုရင် "duplicate: already subscribed"၊ အောင်ရင် "subscribed" ပြန်ပါ
<?php
declare(strict_types=1);
// $pdo already has: subscribers(id, email TEXT UNIQUE, name TEXT)
function subscribe(array $post, PDO $pdo): string
{
// TODO: email and name must both be strings
// TODO: trim them, lowercase the email, default the name to "friend"
// TODO: validate the email, then the consent value
// TODO: INSERT with a prepared statement and translate SQLSTATE 23000
// TODO: return "subscribed" on success
}ရလဒ်: "Su@Example.com " က subscribed၊ စာလုံးအကြီးအသေးကွာတဲ့ ထပ်နေတာက duplicate၊ name မပါတာက subscribed (friend)၊ consent မပါတာ၊ email မှားတာ၊ array email၊ ဗလာ array တို့က invalid ပါ။ Stored row နှစ်ခု ရှိပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
စစ်ဆေးမှုတွေရဲ့ အစီအစဉ်က အရေးကြီးပါတယ်။ ဗလာ array [] ကို ပေးရင် email စစ်တဲ့အဆင့်မှာ "invalid: email" ရပါမယ်။ strtolower(trim($email)) ကို filter_var မခေါ်ခင် လုပ်ပါ။
အဖြေ ကြည့်ရန်
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite::memory:');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('CREATE TABLE subscribers (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
name TEXT NOT NULL
)');
function subscribe(array $post, PDO $pdo): string
{
$email = $post['email'] ?? '';
$name = $post['name'] ?? '';
if (!is_string($email) || !is_string($name)) {
return 'invalid: fields must be text';
}
$email = strtolower(trim($email));
$name = trim($name);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
return 'invalid: email';
}
if (($post['consent'] ?? '') !== '1') {
return 'invalid: consent is required';
}
try {
$stmt = $pdo->prepare(
'INSERT INTO subscribers (email, name) VALUES (:email, :name)'
);
$stmt->execute(['email' => $email, 'name' => $name === '' ? 'friend' : $name]);
} catch (PDOException $e) {
if ($e->getCode() === '23000') {
return 'duplicate: already subscribed';
}
throw $e;
}
return 'subscribed';
}
$tests = [
'new subscriber' => [
'email' => 'Su@Example.com ', 'name' => 'Su', 'consent' => '1',
],
'same, other case' => ['email' => 'su@example.com', 'name' => 'Su', 'consent' => '1'],
'no name' => ['email' => 'mya@example.com', 'consent' => '1'],
'no consent' => ['email' => 'kyaw@example.com', 'name' => 'Kyaw'],
'bad email' => ['email' => 'kyaw@', 'name' => 'Kyaw', 'consent' => '1'],
'array email' => ['email' => ['a@b.com'], 'consent' => '1'],
'empty' => [],
];
foreach ($tests as $label => $post) {
echo str_pad($label, 17) . subscribe($post, $pdo) . "\n";
}
$rows = $pdo->query('SELECT email, name FROM subscribers ORDER BY id');
foreach ($rows as $row) {
echo "stored: {$row['email']} ({$row['name']})\n";
}Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Form handler ကို input array လက်ခံပြီး status ပြန်တဲ့ function အဖြစ် ခွဲရေးရင် browser မလိုဘဲ စမ်းလို့ရပါတယ်
- CSRF token ကို hash_equals နဲ့ စစ်ပါ၊ honeypot ကို တိတ်တိတ်ပဲ လျစ်လျူရှုပါ၊ type ကို is_string နဲ့ စစ်ပါ
- ထပ်နေတာကို UNIQUE constraint နဲ့ ကာကွယ်ပါ၊ SQLSTATE 23000 ကို ဖမ်းပါ
- မူရင်း data ကို သိမ်းပြီး HTML ထဲ ထုတ်တဲ့အချိန်မှာမှ escape လုပ်ပါ
PHP Language Reference — PHP Documentation Group