之前公司要向中華電信租用虛擬主機的時候,我想說我公司電腦是用WINDOWS系統,就租用了WINDOWS,後來才知道要用LINUX才能使用PHP,還好做這樣的更改是不用再收取費用的。
要怎樣才能知道主機有沒有支援PHP呢? 可以先寫個簡單的測試頁面放在主機上
若看得到 (Hello World) 內容就表示有支援喔!
正題來了.確認有支援php, 我們就先完成 html表單頁面的部份, 此範例中我們設定 action="form-1.php" 與 method="post"是當按下送出表單的按鈕之後, form 會透過 post 的傳遞方式,將表單資料送到 form-1.php 這支程式,而表單內容我們放了姓名,電子郵件與機構三個欄位。
<body>
<div class="containar">
<div class="row justify-content-center m-3">
<div class="col-md-5 m-4 p-4 rounded-3" style="background-color: rgb(211, 211, 211);">
<h4 class="fw-bold text-primary text-center">Fill Out The Form To Contact Us</h4>
<form method="post" action="./form-1.php" accept-charset="UTF-8">
<div class="mb-3">
<input type="text" class="form-control border-0" name="name" id="name" placeholder="Name" required>
</div>
<div class="mb-3">
<input type="text" class="form-control border-0" name="institution" id="institution" placeholder="Institution" required>
</div>
<div class="mb-3">
<input type="email" class="form-control border-0" name="email" id="email" placeholder="name@example.com" required>
</div>
<p class="lh-sm"><small>
We assure you that your personal information will be kept confidential and will not be disclosed.
</small></p>
<div class="form-check mb-3">
<input class="form-check-input" type="checkbox" value="1" id="newsletterCheckbox" name="newsletter" checked>
<label class="form-check-label" for="newsletterCheckbox">
I agree to receive Newsletter.
</label>
</div>
<button type="submit" class="btn btn-primary text-white w-100">Submit</button>
</form>
</div>
</div>
</div>
</body>
</html>
再來寫php接受表單的部分,發送成功時會定向到新頁面,如果沒有要到新頁面的話,就像我設原本填資料的頁面吧!
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// 函数用于清理输入数据
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// 清理和获取用户输入
$name = clean_input($_POST['name'] ?? '');
$institution = clean_input($_POST['institution'] ?? '');
$email = clean_input($_POST['email'] ?? '');
$newsletter = isset($_POST['newsletter']) ? 'Yes' : 'No';
// 接收邮件地址和邮件内容
$to = "hello@gmail.com";
$subject = "The Form from Website";
$body = "Name: $name\nEmail: $email\nInstitution:\n$institution\nNewsletter Subscription: $newsletter";
// 设置邮件头,指定内容类型和字符集,中文才不會亂碼
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/plain;charset=UTF-8" . "\r\n";
$headers .= "From: <$email>" . "\r\n";
// 发送邮件并处理结果
if (mail($to, $subject, $body, $headers)) {
// 发送成功,重定向到新页面
echo "<script>alert('Thank you for your message, we will get back to you soon.'); window.location.href = './newsletter.html';</script>";
exit;
} else {
// 发送失败
echo "Sorry, there was an error sending your message. Please try again later.";
}
}
?>
這樣就可以收到信嘍!
留言列表