联系表单不能与Bootstrap + PHP

时间:2016-05-18 11:01:06

标签: php html twitter-bootstrap

我正在尝试使用bootstrap + php通过HTML5发送电子邮件。

HTML:

<form name="frmContacto" class="form-horizontal" method="post" action="mail/contact_me.php">
    <fieldset>
        <legend class="text-center header">Formulario de contacto</legend>

        <div class="form-group">
            <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i></span>
            <div class="col-md-8">
                <input id="fname" name="name" type="text" placeholder="Nombre" class="form-control">
            </div>
        </div>
        <div class="form-group">
            <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i></span>
            <div class="col-md-8">
                <input id="lname" name="name" type="text" placeholder="Apellidos" class="form-control">
            </div>
       </div>

       <div class="form-group">
           <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-envelope-o bigicon"></i></span>
           <div class="col-md-8">
                <input id="email" name="email" type="text" placeholder="Correo electrónico" class="form-control">
           </div>
       </div>

       <div class="form-group">
           <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-phone-square bigicon"></i></span>
           <div class="col-md-8">
               <input id="phone" name="phone" type="text" placeholder="Teléfono" class="form-control">
           </div>
       </div>

       <div class="form-group">
           <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-pencil-square-o bigicon"></i></span>
           <div class="col-md-8">
                <textarea class="form-control" id="message" name="message" placeholder="Introduce aquí tu mensaje." rows="7"></textarea>
           </div>
       </div>

       <div class="form-group">
            <div class="col-md-12 text-center">
                <a href="mailto:xxx@example.com?Subject=Hello%20again" target="_top">
                    <button type="submit" class="btn btn-primary btn-lg">Enviar</button>
                </a>
            </div>
        </div>
    </fieldset>
</form>

PHP:

<?php
// Check for empty fields
if (empty($_POST['name']) ||
    empty($_POST['email']) ||
    empty($_POST['phone']) ||
    empty($_POST['message']) ||
    !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
) {
    echo "No arguments Provided!";
    return false;
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'xxx@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Formulario de contacto web:  $name";
$email_body = "Ha recibido un nuevo mensaje desde la web.\n\n" . "Detalles:\n\Nombre: $name\n\nEmail: $email_address\n\Teléfono: $phone\n\Mensaje:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>

我不知道是否必须在HTML中导入内容。看来php mail()函数没有被调用,因为我在函数行中有一个断点,当我点击“Submit”按钮时没有任何反应。此外,电子邮件在$ to php函数和HTML“mailto”中也是相同的。

非常感谢。

3 个答案:

答案 0 :(得分:1)

检查以下事项─ 1.在HTML中,您已经两次声明了表单名称行,这不是必需的。 2.您应该在配置为邮件服务器的服务器/ PHP配置文件中进行设置。如果未连接邮件服务器,则无法发送邮件

答案 1 :(得分:0)

您是否在php.ini(sendmail参数)中验证了您的设置?

如果需要,您可以阅读此内容: https://blog.codinghorror.com/so-youd-like-to-send-some-email-through-code/

答案 2 :(得分:0)

下面的代码评论很好,所以没有必要写很多。只需阅读评论。这是不言自明的:

<强> PHP

    <?php

        // GET ALL POSTED FIELD-VALUES AND ASSIGN THEM DEFAULT VALUES OF NULL (IF THEY ARE NOT YET SET...
        $lastName   = isset($_POST['last_name'])    ? htmlspecialchars(trim($_POST['last_name']))   : null;
        $firstName  = isset($_POST['first_name'])   ? htmlspecialchars(trim($_POST['first_name']))  : null;
        $email      = isset($_POST['email'])        ? htmlspecialchars(trim($_POST['email']))       : null;
        $phone      = isset($_POST['phone'])        ? htmlspecialchars(trim($_POST['phone']))       : null;
        $message    = isset($_POST['message'])      ? htmlspecialchars(trim($_POST['message']))     : null;

        // VALIDATE THE FIELDS: BUT FIRST CREATE AN ARRAY
        // TO HOLD ERROR MESSAGES FOR FIELDS THAT FAILED THE VALIDATION.
        $arrErrorBag        = array();
        $strErrorMessage    = "";

        // VALIDATE E-MAIL:
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $arrErrorBag["E-Mail"]      = "The Email you entered in not valid.";
        }

        // VALIDATE FIRST NAME:
        if(!preg_match('#(^[a-zA-z])?([\w\.\-\ ])*\w*$#i', $firstName)){
            $arrErrorBag["First Name"] = "First Name Should not be Empty and should contain only alpha-numeric Characters.";
        }

        // VALIDATE LAST NAME:
        if(!preg_match('#(^[a-zA-z])?([\w\.\-\ ])*\w*$#i', $lastName)){
            $arrErrorBag["Last Name"] = "Last Name Should not be Empty and should contain only alpha-numeric Characters.";
        }

        // VALIDATE PHONE:
        if(!preg_match('#^(\+\d{1,3})?\s?(\d{2,4})\s?(\d{2,4})\s?(\d{2,4})\s?(\d{2,4})$#', $phone)){
            $arrErrorBag["Phone"]       = "Telephone Number should be Numeric and Should not be Empty.";
        }

        // VALIDATE MESSAGE:
        if(!preg_match('#([\w\.\-\d\ ])*\w*$#si', $name)){
            $arrErrorBag["Message"]     = "Message Should not be Empty and should contain only alpha-numeric Characters only.";
        }

        if(!empty($arrErrorBag)){
            // WE HAVE SOME ERRORS SO WE BUILD A STRING MESSAGE BASED ON THE ERRORS WE HAVE GATHERED ABOVE...
            $strErrorMessage     .= "<h6 class='error-heading'>There are Errors in the Form Please, correct them to continue.</h6>";
            foreach($arrErrorBag as $fieldName=>$errorMessage){
                $strErrorMessage .= "<div class='error-block'><strong>{$fieldName}: </strong>";
                $strErrorMessage .= "<span>{$errorMessage}: </span></div>";
            }
        }else{
            // THE FORM IS CLEAN AND VALID SO WE SEND THE E-MAIL:
            $name           = $firstName . " " . $lastName;
            $to             = 'xxx@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
            $email_subject  = "Formulario de contacto web:  $name";
            $email_body     = "Ha recibido un nuevo mensaje desde la web.\n\n" . "Detalles:\n\Nombre: {$name}\n\nEmail: {$email}\n\Teléfono: {$phone}\n\Mensaje:\n{$message}";
            $headers        = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
            $headers       .= "Reply-To: {$email}";
            mail($to, $email_subject, $email_body, $headers);

            // THE MAIL WAS SENT SO YOU CAN NOW REDIRECT TO ANOTHER PAGE... MAYBE A THANK YOU PAGE...
            $redirectURL        = "thank-you.php";      //<== THIS IS ONLY AN EXAMPLE... THE URL SHOULD RATHER BE ANY PAGE OF YOUR CHOOSING.
            header("location: " . $redirectURL);
        }

    ?>

<强> HTML

    <!-- BEFORE THE FORM, CREATE A DIV TO HOLD ERROR MESSAGE, IN CASE ERRORS OCCUR... -->
    <!-- IN THIS SCENARIO, IT IS IDEAL TO HAVE BOTH THE PHP AND THE HTML INSIDE THE SAME FILE... -->
    <!-- THE PHP CODE SHOLD BE AT THE TOP OF THE FILE & THE HTML MARKUP BELOW... -->
    <!-- NOTICE THAT THE ACTION ATTRIBUTE OF THE FORM IS NOW EMPTY... THIS FORCES THE FORM TO SUBMIT BACK TO ITSELF: THIS PAGE... -->
    <div class="error-msg-wrapper"><?php echo $strErrorMessage; ?></div>
    <form name="frmContacto" class="form-horizontal" method="post" action="">
        <fieldset>
            <legend class="text-center header">Formulario de contacto</legend>

            <div class="form-group">
                <span class="col-md-1 col-md-offset-2 text-center">
                    <i class="fa fa-user bigicon"></i>
                </span>
                <div class="col-md-8">
                    <input id="fname" name="first_name" type="text" placeholder="Nombre" value="<?php echo $firstName; ?>" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <span class="col-md-1 col-md-offset-2 text-center">
                    <i class="fa fa-user bigicon"></i>
                </span>
                <div class="col-md-8">
                    <input id="lname" name="last_name" type="text" placeholder="Apellidos"  value="<?php echo $lastName; ?>" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <span class="col-md-1 col-md-offset-2 text-center">
                    <i class="fa fa-envelope-o bigicon"></i>
                </span>
                <div class="col-md-8">
                    <input id="email" name="email" type="text" placeholder="Correo electrónico" value="<?php echo $email; ?>" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <span class="col-md-1 col-md-offset-2 text-center">
                    <i class="fa fa-phone-square bigicon"></i>
                </span>
                <div class="col-md-8">
                    <input id="phone" name="phone" type="text" placeholder="Teléfono" value="<?php echo $phone; ?>" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <span class="col-md-1 col-md-offset-2 text-center">
                    <i class="fa fa-pencil-square-o bigicon"></i>
                </span>
                <div class="col-md-8">
                    <textarea class="form-control" id="message" name="message" placeholder="Introduce aquí tu mensaje." rows="7"><?php echo $message; ?></textarea>
                </div>
            </div>

            <div class="form-group">
                <div class="col-md-12 text-center">
                    <input type="submit" class="btn btn-primary btn-lg" value="Enviar" />
                </div>
            </div>
        </fieldset>
    </form>