我试图使用 html 和 php 制作一个有效的联系表单,但是当我输入姓名、电子邮件和消息然后单击发送时,它显示此错误 我正在使用带有 php 的普通本地主机(在 cmd 中:$ php -S localhost:4000)
<br />
<b>Warning</b>: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() in <b>C:\Users\BKMH\Downloads\Yahya\i mustn't uplaod to mega but i need my files\Projects\Websites\Html\Interesiting\GoodDesignePortfolio\php\message.php</b> on line <b>12</b><br />
Sorry, failed to send your message!
这是我的 php 代码:(我是 php 新手)
<?php
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
if(!empty($email) && !empty($message)){
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$receiver = "[email protected]"; //enter that email address where you want to receive all messages
$subject = "From: $name <$email>";
$body = "Name: $name\nEmail: $email\n\nMessage:\n$message\n\nRegards,\n$name";
$sender = "From: $email";
if(mail($receiver, $subject, $body, $sender)){
echo "Your message has been sent";
}else{
echo "Sorry, failed to send your message!";
}
}else{
echo "Enter a valid email address!";
}
}else{
echo "Email and message field is required!";
}
?>
我花了两个小时搜索,但找不到任何有效的解决方案,请帮忙,谢谢
您发布的代码对于使用 HTML 和 PHP 创建基本联系表单来说似乎基本正确。您遇到的问题可能与表单的设置方式或提交方式有关。让我们检查一下代码并确保一切就位。
HTML 表单: 首先,确保您的 HTML 表单结构正确并且方法设置为 POST。以下是 HTML 表单的外观示例:
<!DOCTYPE html>
<html>
<head>
<title>Contact Form</title>
</head>
<body>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message" rows="4" required></textarea><br><br>
<input type="submit" value="Send">
</form>
</body>
</html>
PHP 代码: 创建一个单独的 PHP 文件,我们将其命名为“process.php”,您将在其中放置之前发布的 PHP 代码。确保此 PHP 文件与您的 HTML 表单位于同一目录中。
<?php
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
if (!empty($email) && !empty($message)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$receiver = "[email protected]";
$subject = "From: $name <$email>";
$body = "Name: $name\nEmail: $email\n\nMessage:\n$message\n\nRegards,\n$name";
$sender = "From: $email";
if (mail($receiver, $subject, $body, $sender)) {
echo "Your message has been sent";
} else {
echo "Sorry, failed to send your message!";
}
} else {
echo "Enter a valid email address!";
}
} else {
echo "Email and message field is required!";
}
?>
确保您已将 HTML 表单保存为“index.html”,将 PHP 代码保存为“process.php”,并保存在同一目录中。
通过此设置,当您输入姓名、电子邮件和消息并单击“发送”时,表单数据将发送到“process.php”进行处理。如果一切设置正确,您应该会收到相应的成功或错误消息。
请记住将“[email protected]”替换为您想要接收消息的实际电子邮件地址。