我和php类似,不明白问题出在哪里。
有时 php 函数会向我发送空消息,例如
父母姓名
太晚了:
林恩:
电话号码:
电子邮件:
出生日期:
消息正文:
但它应该填充这样的值
父母姓名测试
失误太多:测试
林恩:测试
电话号码:测试
邮箱:test@test
出生日期:21313
消息文本:测试
这是我的 php 代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Обратная Связь</title>
</head>
<body>
<?php
if (isset($_POST['parent'])) {$parent = $_POST['parent'];}
if (isset($_POST['child'])) {$child = $_POST['child'];}
if (isset($_POST['contacts'])) {$contacts = $_POST['contacts'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
if (isset($_POST['bbd'])) {$bbd = $_POST['bbd'];}
if (isset($_POST['city'])) {$city = $_POST['city'];}
if (isset($_POST['mess'])) {$mess = $_POST['mess'];}
$to = "info@test.ee"; /*Укажите ваш адрес электоронной почты*/
$headers = "Content-type: text/plain; text/html; charset=utf-8";
$subject = "Kontakti Info";
$message = "Vanema nimi $parent \n Lapse nimi: $child \nLinn:
$city \nTelefoninumber: $contacts \nEmail: $email \nSünnikuupäev: $bbd \nSõnumi tekst: $mess";
$send = mail ($to, $subject, $message, $headers);
if ($send == 'true')
{
echo "<b>Спасибо за отправку вашего сообщения!<p>";
echo "<a href=index.php>Нажмите,</a> чтобы вернуться на главную страницу";
}
else
{
echo "<p><b>Ошибка. Сообщение не отправлено!";
}
?>
</body>
</html>
<?php
header('Location: https://test.ee/aitah.html ');
?>
请给我建议,哪里出了问题。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您的脚本只是一个表单处理器,您可以例如add
if(empty($_POST)) { die('没有表单数据!'); }到顶部以防止其运行,除非响应表单提交。如果您需要填写所有字段,则必须在处理电子邮件之前检查每个字段。您可以将所有这些
isset塞进一个巨大的if(isset(...)语句中。但是,有一种更简单、更易读的方法来做到这一点。首先,让我们设置几个变量:然后,我们循环遍历字段,如果值存在,则添加到
$data,否则我们添加错误注释。// Loop to check your required fields: foreach($fields as $field) { // If value exists, add to $data: if(!empty($_POST[$field])) { $data[$field] = $_POST[$field]; } // Else add error: else { $errors[] = 'Missing field: ' . $field; } } if(empty($errors)) { // No errors, send your email // You can use "Vanema nimi {$data['parent']}...", // ... otherwise: extract($data) to use $parent etc. } else { // You could report those errors, or redirect back to the form, or whatever. }如果出现错误(= 缺少字段),则不会发送电子邮件。作为奖励,您现在拥有一段可重用的代码,只需修改
$fields数组即可将其用于具有类似功能的其他表单。 (如果您确实需要重用它,则将其包装到函数中是一个好主意;不要复制粘贴代码。function x($post, $fields) { ... }用于基本操作辅助函数。)请注意,这里我们使用
empty代替isset。如果提交空白表单,则会设置字段(为空字符串"")。另请注意,empty返回true对于任何等于false的内容(即""、0、false、null,[])。 (如果“0”是预期且可接受的值,请注意它的“空性”!)另一方面,isset对于任何非null的内容返回 true。附注如果上面的代码是完整的代码,并且您的脚本只是处理表单数据并重定向,那么您根本不需要 HTML 包装器。它永远不会显示。