2014-12-21 130 views
-2

我是前端開發人員,我是PHP新手。我正在使用BootStrap3爲我的網站構建一個聯繫表單,而表單實際上提交了該消息,並且我能夠在我的Gmail收件箱中接收到發送的消息,其中一些PHP標記以模式形式顯示爲純文本。如何使錯誤消息以文本形式顯示,而不是使用PHP標記污染窗體?PHP代碼在HTML代碼中顯示爲純文本

的Boottrap3形式:

<form class="form-horizontal" role="form" method="post" action="index.php"> 
    <div class="form-group"> 
     <label for="name" class="col-sm-2 control-label">Name</label> 
      <div class="col-sm-10"> 
       <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($_POST['name']); ?>"> 
       <?php echo "<p class='text-danger'>$errName</p>";?><!-- shows all the time as code--> 
       </div> 
      </div> 
     <div class="form-group"> 
    <label for="email" class="col-sm-2 control-label">Email</label> 
     <div class="col-sm-10"> 
      <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($_POST['email']); ?>"> 
      <?php echo "<p class='text-danger'>$errEmail</p>";?><!-- shows all the time as code--> 
     </div> 
    </div> 
</form> 

PHP代碼(的index.php)

<?php 
if ($_POST["submit"]) { 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $message = $_POST['message']; 
    $human = intval($_POST['human']); 
    $from = 'Demo Contact Form'; 
    $to = '[email protected]'; 
    $subject = 'Message from Contact Demo '; 

    $body = "From: $name\n E-Mail: $email\n Message:\n $message"; 

    // Check if name has been entered 
    if (!$_POST['name']) { 
     $errName = 'Please enter your name'; 
    } 

    // Check if email has been entered and is valid 
    if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { 
     $errEmail = 'Please enter a valid email address'; 
    } 

// If there are no errors, send the email 
    if (!$errName || !$errEmail || !$errMessage || !$errHuman) { 
     if (mail ($to, $subject, $body, $from)) { 
      $result='<div class="alert alert-success">Thank You! I will be in touch</div>'; 
     } else { 
      $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>'; 
     } 
    } 
} 
?> 

回答

1

添加至少if條件你顯示段包含錯誤消息之前,例如:

<?php if ($errName) : ?> 
<p class="text-danger"><?php echo $errName ?></p> 
<?php endif; ?> 

它應該在你的例子中訣竅。

而btw:您的聯繫表格應作爲PHP文件提供。如果它是一個HTML文件,它不會工作,因爲它不會被PHP解釋。

+0

謝謝您的回答。聯繫表格不能是PHP文件,因爲它是引導程序模式窗口的一部分,它爲聯繫表單提供了一個「平臺」。實際上,我可以從我的服務器發送郵件,但由於某種原因,字段的驗證功能尚未正常工作。 – undroid

0

嘗試這樣

<?php echo "<p class='text-danger'>".$errName."</p>";?> 
+0

謝謝,但它不工作。看起來像?>標記不被識別爲php標記,而是作爲文本。 – undroid

+0

喲應該使用Javascript或基於AJAX的模態窗口驗證。試試這個插件[鏈接](https://github.com/nghuuphuoc/bootstrapvalidator) –