2015-07-29 3 views
0

У меня есть контактная форма в данный момент, действие которой происходит на отдельной php-странице. Однако подтверждение - это просто белая страница с некоторым простым текстом. Как я могу поместить этот php-код на мою страницу контактной формы и выполнить его действие, чтобы я мог сделать подтверждение на той же странице?Как выполнить функцию php в форме html на одной странице?

код PHP выглядит следующим образом:

<?php 
if(isset($_POST['email'])) { 

    // CHANGE THE TWO LINES BELOW 
    $email_to = "[email protected]"; 

    $email_subject = "Movie Night Review Submissions"; 


    function died($error) { 
     // your error code can go here 
     echo "We're sorry, but there's errors found with the form you submitted.<br /><br />"; 
     echo $error."<br /><br />"; 
     echo "Please go back and fix these errors.<br /><br />"; 
     die(); 
    } 

    // validation expected data exists 
    if(!isset($_POST['first_name']) || 
     !isset($_POST['last_name']) || 
     !isset($_POST['email']) || 
     !isset($_POST['telephone']) || 
     !isset($_POST['comments'])) { 
     died('We are sorry, but there appears to be a problem with the form you submitted.');  
    } 

    $first_name = $_POST['first_name']; // required 
    $last_name = $_POST['last_name']; // required 
    $email_from = $_POST['email']; // required 
    $telephone = $_POST['telephone']; // not required 
    $comments = $_POST['comments']; // required 

    $error_message = ""; 
    $email_exp = '/^[A-Za-z0-9._%-][email protected][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 .= "Telephone: ".clean_string($telephone)."\n"; 
    $email_message .= "Comments: ".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); 
?> 

<!-- place your own success html below --> 

Thank you for contacting us. We will be in touch with you very soon. 

You will now be redirected back to the original page within 10 seconds. 

If the page does not load click <a href ="http://movienightreviews.tk/contact_us.html">here</a> to be redirected now. 

<?php 
header('Refresh: 10; URL=http://movienightreviews.tk/contact_us.html'); 
} 
die(); 
?> 

HTML-код страницы в настоящее время является:

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Contact Us</title> 
<link href="Styles/main.css" rel="stylesheet" type="text/css"> 
</head> 
<body> 
<div id="wrapper"> 
    <header id="top"> 
     <h1>Movie Night Reviews</h1> 
     <nav id="mainnav"> 
      <ul> 
       <li><a href="index.html">Home</a></li> 
       <li><a href="trailers.php">Trailers</a></li> 
       <li class = "review"><a href="#">Reviews</a> 
        <ul id = "dropdown1"> 
         <li><a href="civil_war.php">Civil War</a></li> 
         <li><a href="furious_7.html">Furious 7</a></li> 
         <li><a href="fantastic_four.html">Fantastic Four</a></li> 
         <li><a href="jurassic_world.html">Jurassic World</a></li> 
         <li><a href="agents_of_shield.html">Agents of Shield</a></li> 
        </ul> 
       </li> 
       <li><a href="about_us.html">About Us</a></li> 
       <li><a href="contact_us.html"id="thispage">Contact Us</a></li> 
      </ul> 
     </nav> 
    </header> 
    <article id="main"> 
     <h2>Contact Us by E-Mail</h2> 
     <p>To contact us by E-Mail please fill out the following form and click Submit.</p> 
     <form name="htmlform" method="post" action="html_form_send.php"> 
<table width="450px"> 
</tr> 
<tr> 
<td valign="top"> 
    <label for="first_name">First Name *</label> 
</td> 
<td valign="top"> 
    <input type="text" name="first_name" maxlength="50" size="30"> 
</td> 
</tr> 

<tr> 
<td valign="top"> 
    <label for="last_name">Last Name *</label> 
</td> 
<td valign="top"> 
    <input type="text" name="last_name" maxlength="50" size="30"> 
</td> 
</tr> 
<tr> 
<td valign="top"> 
    <label for="email">Email Address *</label> 
</td> 
<td valign="top"> 
    <input type="text" name="email" maxlength="80" size="30"> 
</td> 

</tr> 
<tr> 
<td valign="top"> 
    <label for="telephone">Telephone Number</label> 
</td> 
<td valign="top"> 
    <input type="text" name="telephone" maxlength="30" size="30"> 
</td> 
</tr> 
<tr> 
<td valign="top"> 
    <label for="comments">Comments *</label> 
</td> 
<td valign="top"> 
    <textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea> 
</td> 

</tr> 
<tr> 
<td colspan="2" style="text-align:center"> 
    <input type="submit" value="Submit"> 
    </td> 
</tr> 
</table> 
</form> 
    <h2>Contact Us by Post</h2> 
    <p>To contact us by Post please send a letter to the following address:</p> 
    <p> 
    Joe Bloggs<br> 
    The Shed<br> 
    Moss Side<br> 
    Manchester<br> 
    M15 SHED</p> 
    </article> 
    <aside id="sidebar"> 
     <h2>Disclaimer</h2> 
     <p>For those who haven't realised, this website is just a test website and there is no such company or people tht rementioned inthis website so do not contact us. </p> 
    </aside> 
    <footer> 
     <p>&copy; Copyright 2015 Movie Night Reviews</p> 
    </footer> 
</div> 
</body> 
</html> 

Спасибо за ответы, ребята !! Я сделал, как вы сказали, удалив действие и поместив php на мою страницу. Функция теперь работает, однако половина моего приложения не показывает, почему-то не уверен, почему. Мой новый код теперь:

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title>Contact Us</title> 
<link href="Styles/main.css" rel="stylesheet" type="text/css"> 
</head> 
<body> 
<div id="wrapper"> 
    <header id="top"> 
     <h1>Movie Night Reviews</h1> 
     <nav id="mainnav"> 
      <ul> 
       <li><a href="index.html">Home</a></li> 
       <li><a href="trailers.php">Trailers</a></li> 
       <li class = "review"><a href="#">Reviews</a> 
        <ul id = "dropdown1"> 
         <li><a href="civil_war.php">Civil War</a></li> 
         <li><a href="furious_7.html">Furious 7</a></li> 
         <li><a href="fantastic_four.html">Fantastic Four</a></li> 
         <li><a href="jurassic_world.html">Jurassic World</a></li> 
         <li><a href="agents_of_shield.html">Agents of Shield</a></li> 
        </ul> 
       </li> 
       <li><a href="about_us.html">About Us</a></li> 
       <li><a href="contact_us.html"id="thispage">Contact Us</a></li> 
      </ul> 
     </nav> 
    </header> 
    <article id="main"> 
     <h2>Contact Us by E-Mail</h2> 
     <p>To contact us by E-Mail please fill out the following form and click Submit.</p> 
     <form name="htmlform" method="post" action="#"> 
<table width="450px"> 
</tr> 
<tr> 
<td valign="top"> 
    <label for="first_name">First Name *</label> 
</td> 
<td valign="top"> 
    <input type="text" name="first_name" maxlength="50" size="30"> 
</td> 
</tr> 

<tr> 
<td valign="top"> 
    <label for="last_name">Last Name *</label> 
</td> 
<td valign="top"> 
    <input type="text" name="last_name" maxlength="50" size="30"> 
</td> 
</tr> 
<tr> 
<td valign="top"> 
    <label for="email">Email Address *</label> 
</td> 
<td valign="top"> 
    <input type="text" name="email" maxlength="80" size="30"> 
</td> 

</tr> 
<tr> 
<td valign="top"> 
    <label for="telephone">Telephone Number</label> 
</td> 
<td valign="top"> 
    <input type="text" name="telephone" maxlength="30" size="30"> 
</td> 
</tr> 
<tr> 
<td valign="top"> 
    <label for="comments">Comments *</label> 
</td> 
<td valign="top"> 
    <textarea name="comments" maxlength="1000" cols="25" rows="6"></textarea> 
</td> 

</tr> 
<tr> 
<td colspan="2" style="text-align:center"> 
    <input type="submit" value="Submit"> 
    </td> 
</tr> 
</table> 
</form> 
<h2>Contact Us by Post</h2> 
    <p>To contact us by Post please send a letter to the following address:</p> 
    <p> 
    Joe Bloggs<br> 
    The Shed<br> 
    Moss Side<br> 
    Manchester<br> 
    M15 SHED</p> 
    </article> 
    <aside id="sidebar"> 
     <h2>Disclaimer</h2> 
     <p>For those who haven't realised, this website is just a test website and there is no such company or people tht rementioned inthis website so do not contact us. </p> 
    </aside> 
    <footer> 
     <p>&copy; Copyright 2015 Movie Night Reviews</p> 
    </footer> 
    </div> 
</body> 
<?php 
if(isset($_POST['email'])) { 

    // CHANGE THE TWO LINES BELOW 
    $email_to = "[email protected]"; 

    $email_subject = "Movie Night Review Submissions"; 


    function died($error) { 
     // your error code can go here 
     echo "We're sorry, but there's errors found with the form you submitted.<br /><br />"; 
     echo $error."<br /><br />"; 
     echo "Please go back and fix these errors.<br /><br />"; 
     die(); 
    } 

    // validation expected data exists 
    if(!isset($_POST['first_name']) || 
     !isset($_POST['last_name']) || 
     !isset($_POST['email']) || 
     !isset($_POST['telephone']) || 
     !isset($_POST['comments'])) { 
     died('We are sorry, but there appears to be a problem with the form you submitted.');  
    } 

    $first_name = $_POST['first_name']; // required 
    $last_name = $_POST['last_name']; // required 
    $email_from = $_POST['email']; // required 
    $telephone = $_POST['telephone']; // not required 
    $comments = $_POST['comments']; // required 

    $error_message = ""; 
    $email_exp = '/^[A-Za-z0-9._%-][email protected][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 .= "Telephone: ".clean_string($telephone)."\n"; 
    $email_message .= "Comments: ".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); 
?> 

<!-- place your own success html below --> 

Thank you for contacting us. We will be in touch with you very soon. 
</html> 
+0

удалить действие из здесь '<форма имя =«HTMLForm»метод =«пост»действие =«html_form_send.php»>' так будет например '

' будет держать вас на одной странице после отправки формы – Shehary

+1

Просто скопируйте свой код PHP на свою страницу формы и удалите действие формы. – Kyle

+0

@Kyle Не могли бы вы увидеть обновленный вопрос, так как теперь он вызвал другую проблему. Cheers –

ответ

1

Вы содержание HTML должен быть напечатан условно, так что вы только показать всю страницу, когда доступ пользователя это в первый раз:

<?php 
if(isset($_POST['email'])) { 
    // prepare to send email... 
    @mail($email_to, $email_subject, $email_message, $headers); 
?> 

<!-- success message goes here --> 

<? 
} else { 
?> 

<!-- full html goes here --> 

<?php 
} 
?> 

Кстати, вы можете использовать $_SERVER["SCRIPT_NAME"], так что вы не имеете беспокоиться о изменении кода в случае, если переименовать файл PHP:

<form name="htmlform" method="post" action="<?php echo $_SERVER["SCRIPT_NAME"]; ?>"> 
+0

Спасибо за ответ, он работает, но нижняя половина html отображается только после того, как они отправляют форму, которая является проблемой, любые другие способы сделать это? –

+0

Странно, я не вижу причин для того, чтобы это не сработало, убедитесь, что вы правильно использовали этот код: сначала скопируйте код из моего ответа, замените '// prepare to send email ... ', чтобы ваш код отправил почту вверх пока '@mail (', заменить сообщение «Успешное сообщение» здесь) с «Спасибо» (просто чтобы увидеть его работу), а затем замените «full html here here» на HTML, который вы представили в первую очередь. –

0

код PHP может оставаться почти то же самое, просто вставьте его в HTML-страницы и вставить сообщение об успехе, где вы хотите его в HTML с условным вокруг него (или установить переменная вместо вставки вызова функции в условную):

if (@mail($email_to, $email_subject, $email_message, $headers)) { 
    //success message 
} else { 
    //failure message 
} 

Убедитесь использовать расширение .php на странице HTML, и удалите атрибут действия формы.

+0

Не могли бы вы увидеть обновленный вопрос, так как теперь он вызвал другую проблему. Cheers –

Смежные вопросы