網站若能直接在頁面填寫並寄出信件,無需啟動郵件軟體,使用者體驗將大幅提升。本篇介紹 `mail()` 函式語法,並實作一個「寄信給站長」的完整範例。
mail(收信人, 主題, 內容, 郵件標頭);
<form action="mail.php" method="post">
發件人:<input type="text" name="from" size="25" required><br>
主題:<input type="text" name="subject" size="20" required><br>
內容:<br>
<textarea name="content" cols="80" rows="15" required>你好,站長:</textarea><br>
<input type="submit" value="寄出"> <input type="reset" value="重寫">
</form>
<?php
$from = trim($_POST['from'] ?? '');
$subject = trim($_POST['subject'] ?? '');
$content = trim($_POST['content'] ?? '');
if ($from === '' || $subject === '' || $content === '') {
exit('資料未填完整,請 返回');
}
$body = "[主題] $subject\n";
$body .= "[發件人] $from\n";
$body .= $content;
$headers = "From: $from\r\nReply-To: $from\r\nContent-Type: text/plain; charset=utf-8";
$to = 'webmaster@example.com';
$ok = mail($to, $subject, $body, $headers);
echo $ok ? '寄件成功!' : '寄件失敗!!!';
?>
到此《談談 PHP 語法》系列告一段落。我們從變數、陣列、運算子、表單傳值、Cookie/Session、郵件函式,建立了 PHP 入門基礎。要真正精通,還需深入資料庫操作、框架(Laravel/Symfony)、Composer 套件管理、測試與部署流程。祝各位在 PHP 之路上越走越遠!