当我测试我的 PHP 联系表单时,我不断收到“警告:在第 102 行为 foreach() 提供的参数无效”消息。我最近重建了我的网站,但我使用的 PHP 联系表单代码与我在旧网站上使用的完全相同,并且旧网站的表单仍然可以正常工作。我已经逐字复制并粘贴了它,所以我不确定为什么会出现此错误。任何帮助将不胜感激。
这是我得到假定错误的行(第 102 行):
foreach($errors as $value) {
这是整个表单脚本(错误行在底部):
<?php
//
if(isset($_POST["submit"]))
{
//This is checking if the string length in the firstname field was greater than 1 character
if(strlen($_POST["firstname"]) > 1)
{
$firstname = $_POST["firstname"];
//echo $firstname;
}
else
{
//echo "You did not type in first name";
$errors["firstname"] = "<span class=\"error\">You did not type in a first name.</span>";
}
if(strlen($_POST["lastname"]) > 1)
{
$lastname = $_POST["lastname"];
}
else
{
$errors["lastname"] = "<span class=\"error\">You did not type in a last name.</span>";
}
if(strlen($_POST["email"]) > 1)
{
$email = $_POST["email"];
if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email = $email;
}
else {
$errors["email"] = "<span class=\"error\">Email is invalid.</span>";
}
}
else
{
$errors["email"] = "<span class=\"error\">You did not type in an email address.</span>";
}
//This is checking if the string length in the message field was greater than 1 character
if(strlen($_POST["message"]) > 1)
{
$message = $_POST["message"];
//echo $firstname;
}
else
{
$errors["message"] = "<span class=\"error\">You did not type in a message.</span>";
}
// Code to tell form NOT to send form if there are any errors.
if($errors < 1)
{
$to = "example@email.com";
$from = $email;
// headers makes sure you have a reply-to address
$headers = "From: {$from}" . "\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1';
$subject =
"From: ($from)" . "<br />" .
"First name: ($firstname)" . "<br />" .
"Last name: ($lastname)" . "<br />" .
"Email: ($email)" . "<br />" .
"Message: ($message)";
if(mail($to, $from, $subject, $headers))
{
$finalMsg = "<p class=\"success\">Thank you! Your email was sent.</p>";
}
else {
$finalMsg = "<p class=\"error\">Your email was NOT sent. Please try again.</p>";
}
}
?>
<?php
//each error is displayed
foreach($errors as $value) {
echo "<span>$value</span><br />";
}
}
?>