2015-08-01 2 views
0

Я понятия не имею, почему мои скрипты не работают так, как должны. Я использую форму начальной загрузки. Когда моя форма заполнена и собирается нажать кнопку, то я не буду Перенаправление на пустой странице, как и ничего Отправить это отправить:Не удается отправить письмо через bootstrap php

http://mywebpageaddress.com/send_form_email.php?comments=Hi%2C%0D%0Afirst+message%0D%0AJohn 

самозагрузки форма index.html код:

<form action="send_form_email.php" method="post" class="form-horizontal"> 
      <div class="form-group"> 
      <label for="first_name" class="col-lg-2 control-label">First name</label> 
      <div class="col-lg-10"> 
      <input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter you first name"> 
      </div> 
      </div><!-- End form group --> 

      <div class="form-group"> 
      <label for="last_name" class="col-lg-2 control-label">Last name</label> 
      <div class="col-lg-10"> 
       <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter you last name"> 
      </div> 
      </div><!-- End form group --> 

      <div class="form-group"> 
      <label for="email" class="col-lg-2 control-label">Email</label> 
      <div class="col-lg-10"> 
       <input type="text" class="form-control" id="email" name="email" placeholder="Enter you Email Address"> 
      </div> 
      </div><!-- End form group --> 

      <div class="form-group"> 
      <label for="telephone" class="col-lg-2 control-label">Telephone</label> 
      <div class="col-lg-10"> 
       <input type="text" class="form-control" id="telephone" name="telephone" placeholder="Enter you phone number"> 
      </div> 
      </div> 

      <div class="form-group"> 
      <label for="comments" class="col-lg-2 control-label">Any Message</label> 
      <div class="col-lg-10"> 
       <textarea name="comments" id="comments" name="comments" class="form-control" 
       cols="20" rows="10" placeholder="Enter your Message"></textarea> 
      </div> 
      </div> 

      <div class="form-group"> 
      <div class="col-lg-10 col-lg-offset-2"> 
       <button type="submit" class="btn btn-primary">Submit</button> 
      </div> 
      </div> 



     </form> 

PHP файл:

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

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

    $email_subject = "website html form submissions"; 


    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['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. 

<?php 
} 
die(); 
?> 

выход:

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

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

    $email_subject = "website html form submissions"; 


    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['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. 

<?php 
} 
die(); 
?> 
+0

Возможно, вы захотите удалить '@' в '@ mail', поскольку он подавляет сообщения об ошибках. Кроме того, решайте, используете ли вы 'POST' или' GET'. Метод формы по умолчанию - 'GET', но ваш PHP ожидает' POST'. – Huey

ответ

2

Вы не устанавливаете метод в своем элементе form. поэтому по умолчанию он устанавливает get. Изменение

<form action="send_form_email.php" method="post" class="form-horizontal"> 

И изменить поля ввода и задать имя как:

<input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter you first name"> 

И так далее.

+0

Я добавил это, но после заполнения формы снова была перенаправлена ​​на пустую страницу: http://mywebpageaddress.com/send_form_email.php – Arie

+0

OMG !, вы не указали имя поля ввода в своей форме. – Chayan

+0

вы можете показать, что вы имеете в виду? – Arie

1

Я серьезно Не рекомендуется использовать функцию PHP почты, потому что иногда в моем случае не работают ... Кроме того, вы не установите метод в вас форме, вы должны установить это нравится:

<form method="post" action="ha.php> 

Также вы отправляете форму с полями, которые php не может получить! например:

<input type="text" class="form-control" id="last_name" placeholder="Enter you last name"> <!-- Where is the name="last_name" ? Otherwise you can't retrieve it with php --> 

Там в PHP библиотека, которая сделает вашу жизнь легко о письмах:

SwiftMailer

Там очень много полезной документации, которую вы могли прочитать в официальных документах о SwiftMailer

Например, чтобы отправить почту, вы можете попробовать с

require_once 'lib/swift_required.php'; 

// Create the Transport 
    $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25) // the smtp of google or live. 
//google for example neeeds : Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl") 
    ->setUsername('your username') 
    ->setPassword('your password') 
    ; 
//live for example 

$transport = \Swift_SmtpTransport::newInstance() 
     ->setUsername('[email protected]')->setPassword('blablablabla!') 
     ->setHost('smtp-mail.outlook.com') 
     ->setPort(587)->setEncryption('tls'); 

    /* 
You could alternatively use a different transport such as Sendmail or Mail: 

// Sendmail 
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs'); 

// Mail 
$transport = Swift_MailTransport::newInstance(); 
*/ 

// Create the Mailer using your created Transport 
$mailer = Swift_Mailer::newInstance($transport); 

// Create a message 
$message = Swift_Message::newInstance('Wonderful Subject') 
    ->setFrom(array('[email protected]' => 'John Doe')) 
    ->setTo(array('[email protected]', '[email protected]' => 'A name')) 
->setBody('Here is the message itself') 
; 

// Send the message 
$result = $mailer->send($message); 
+0

Действие есть – Arie

+0

Я просто не хотел отправлять тег формы только с одним атрибутом ... –

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