Итак, это моя первая попытка в PHP, поэтому исправить ее очень легко. Я пытаюсь составить форму, которую можно будет отправить и отправить на электронную почту администрации.
Я запускаю сервер с MAMP, выхожу в Интернет, заполняю форму, отправляю ее и получаю сообщение об ошибке:
We are very sorry, but there were error(s) found with the form you submitted. These errors appear below.
We are sorry, but there appears to be a problem with the form you submitted.
Please go back and fix these errors.
Полный код PHP:
<?php
if (isset($_POST['email'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "I HAVE CORRECT EMAIL HERE 4 SURE";
$email_subject = "eShop Contact Form";
function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.<br /><br />";
echo $error."<br /><br />";
echo "Please go back and fix these errors.<br /><br />";
die();
}
// validation expected data exists
if (!isset($_POST['fname']) ||
!isset($_POST['lname']) ||
!isset($_POST['email']) ||
!isset($_POST['subject'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
$first_name = $_POST['fname']; // required
$last_name = $_POST['lname']; // required
$email_from = $_POST['email']; // required
//$country = $_POST['country']; // not required
$comments = $_POST['subject']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.<br />';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.<br />';
}
if (!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.<br />';
}
if (strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.<br />';
}
if (strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
// $email_message .= "Country: ".clean_string($country)."\n";
$email_message .= "Subject: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success html here -->
Thank you for contacting us. We will be in touch with you very soon.
<?php
}
?>
Это та часть, с которой должны возникнуть проблемы:
// validation expected data exists
if (!isset($_POST['fname']) ||
!isset($_POST['lname']) ||
!isset($_POST['email']) ||
!isset($_POST['subject'])) {
died('We are sorry, but there appears to be a problem with the form you submitted.');
}
P.S Я скопировал сюда код из http://www.freecontactform.com/email_form.php и немного отредактировал.
Используйте error_reporting(E_ALL); ini_set('display_errors', '1');, и он вам расскажет.
@AbraCadaver У меня есть собственная форма, поэтому я изменил эти переменные, и имена правильно соответствуют, могу вас заверить, что
А твоя форма method = "post"?
<form name = "contactform" method = "post" action = "send_form_email.php"> @AbraCadaver Ага
@AbraCadaver Эти две строчки кода не показали ничего нового
@GiorgiQutateladze [Я публикую это здесь, потому что изначально я разместил его в ответе, который, вероятно, будет удален:] Если то, что вы только что разместили в комментариях ниже, является результатом var_dump($_POST), тогда ваша проблема очевидна: вы используете поле такие имена, как firstname и lastname, но ваш PHP ожидает fname и lname.
Кроме того, идея действительно плохо заключается в том, чтобы скопировать и повторно использовать код, который вы не понимаете, но найдете в Интернете. Даже если код, который вы копируете, не является вредоносным (но как вы узнали?), Он может иметь уязвимости в системе безопасности или другие серьезные проблемы. И действительно, в приведенном выше коде есть уязвимости.






Что ж, теперь я начну отсюда. Я отредактирую ваш код заново
ОТПРАВИТЬ.PHP
<?php
if (isset($_POST['formid'])) {
// EDIT THE 2 LINES BELOW AS REQUIRED
$email_to = "[email protected]";
$email_subject = "eShop Contact Form";
//
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$mail = $_POST['email'];
$subject = $_POST['subject'];
$comments = $_POST['comm'];
// I was replace this line
// validation expected data exists
if (empty($fname) or empty($lname) or empty($mail) or empty($subject) or empty($comments)){
$err_msg = 'We are sorry, but there appears to be a problem with the form you submitted.';
} else {
// check mail registered
$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if (!preg_match($email_exp,$mail)) {
$err_msg = 'The Email Address you entered does not appear to be valid.<br />';
} else {
// check name
$string_exp = "/^[A-Za-z .'-]+$/";
if (!preg_match($string_exp,$fname)) {
$err_msg = 'The First Name you entered does not appear to be valid.<br />';
} else {
// check Last name
if (!preg_match($string_exp,$lname)) {
$err_msg = 'The Last Name you entered does not appear to be valid.<br />';
} else {
// Check comment
if ($comments<2 or $comments=='') {
$err_msg = 'The Comments you entered do not appear to be valid.<br />';
} else {
// SEND msg from the visitor
$err_msg = 'Your Messages Was Send. ThankYou!';
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($fname)."\n";
$email_message .= "Last Name: ".clean_string($lname)."\n";
$email_message .= "Email: ".clean_string($email)."\n";
// $email_message .= "Country: ".clean_string($country)."\n";
$email_message .= "Subject: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
}}}}} } else { $err_msg = 'Add Your comment here'; }
?>
INDEX.PHP
<?php require('SUBMIT.PHP'); ?>
<form action = "#" method = "post" />
<p><label>First Name</label>
<input type = "text" placeholder = "First name here" name = "fname" />
</p>
<p><label>Last Name</label>
<input type = "text" placeholder = "Last name here" name = "lname" />
</p>
<p><label>Mail</label>
<input type = "text" placeholder = "Add yourmail here" name = "mail" />
</p>
<p><label>Subject</label>
<input type = "text" placeholder = "Subject here" name = "subject" />
</p>
<p><label>Your Comment</label>
<textarea name = "comm"></textarea>
</p>
<p><input type = "submit" name = "formid" value = "Send" /></p>
</form>
<?php echo $err_msg; ?>
А теперь делай и тестируй.
Да, ты немного отредактировал. Вы поменяли
first_nameнаfnameи т.д. в коде, вы меняли его в форме ???