如何使用PHP显示/隐藏元素以及如何将用户发送到其他页面 [英] How to show/hide elements using PHP and how to send user to another page

查看:91
本文介绍了如何使用PHP显示/隐藏元素以及如何将用户发送到其他页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在整理我的联系表单的PHP。我想要做的是如果表格未填写,则会显示错误消息。我有我的HTML与我想要显示的错误的div。

我知道我可以使用'echo'来显示一条消息,但是我希望它正好位于我想要的位置。我已经看到了这样做的一种方式,但它涉及到所有的PHP代码在HTML文件中......然后重命名文件.php。我想保留大部分的PHP代码与HTML分开。



这是我的代码:



HTML:

 < div class =error> 
< p>
请填写所有字段。
< / p>
< / div>
< form id =contactFormaction =contact.phpmethod =post>
< div>
< input type =textname =nameid =nameplaceholder =Your Namemaxlength =65tabindex =1> < label for =name>名称< / label>
< / div>
< div>
< input type =emailname =_ replytoid =emailplaceholder =Your Emailmaxlength =30tabindex =2> < label for =email>电子邮件< / label>
< / div>
< div>
< textarea name =messageid =messagerows =10placeholder =Your Message ...maxlength =1000tabindex =3>< / textarea> < label for =message>您的讯息< / label>
< / div>
< div>
< input type =submitname =submitvalue =Sendtabindex =4>
< / div>
< / form>

PHP:

  //检查表单提交:
if($ _SERVER ['REQUEST_METHOD'] =='POST'){

/ *该函数有一个参数:一个字符串。
*该函数返回一个干净的字符串版本。
*干净的版本可能是空字符串或
*只是删除所有换行符。
* /
函数spam_scrubber($ value){

//很糟糕的值列表:
$ very_bad = array('to:','cc: ','bcc:','content-type:','mime-version:','multipart-mixed:','content-transfer-encoding:');

//如果任何非常糟糕的字符串在
//提交的值中,则返回一个空字符串:
foreach($ very_bad as $ v){
如果(stripos($ value,$ v)!== false)返回'';
}

//用空格替换任何换行符:
$ value = str_replace(array(\r,\\\
,%0a, %0d),'',$ value);

//返回值:
返回trim($ value);

} //结束spam_scrubber()函数。

//清理表单数据:
$ scrubbed = array_map('spam_scrubber',$ _POST);

//最小表单验证:
if(!empty($ scrubbed ['name'])&&!empty($ scrubbed ['email'])&& ($ scrubbed ['comment'])){

//创建主体:
$ body =名称:{$ scrubbed ['name']} \ n \\ \\ n评论:{$ scrubbed ['comments']};

//发送邮件:
mail('example@email.com','联系表格提交',$ body,发件人:{$ scrubbed ['email']} );

//打印一条消息:
echo'< p>< em>谢谢。< / em>< / p>';

//清除$ scrubbed(以便表单不粘):
$ scrubbed = array();

} else {
echo'< p style =font-weight:bold; color:#C00>请完整填写表单。< / p>';

$ b $ //主结束isset()IF

我的php文件名为contact.php,我的html文件名为contact.html。



我想用class error显示div,if该表格是不完整的。



我尝试了另一种方式,将此代码添加到html中,替换当前的错误div:

 < span class =error> *<?php include'contact.php'; echo $ Err;?>< / span> 

以及这个php文件:

  $ Err =请填写所有字段; 

它仍然不起作用。就好像它不能从html文件中读取php文件中的代码,即使我包含了它?

另一件事是,我将如何去发送一旦表单被提交,用户到另一个html页面?是否通过替换

  //打印一条消息:
echo'< p>< em>你< / EM>< / p为H.';

with

  header('Location:nextpage.html'); 

感谢您提前给予任何帮助。

解决方案

首先,您需要了解服务器如何处理PHP和HTML文件。服务器配置告诉它如何解释文件;一些文件按原样提供,一些文件被传递给一个处理程序,将它们作为脚本执行,等等。在服务器配置中,可能会有一行指示服务器将扩展名为 .php 作为使用PHP执行的脚本。 HTML文件不需要执行;它们被发送到客户端,并且客户端的浏览器解释html,css和js信息以呈现网页。因为HTML文件不是作为脚本执行的,所以如果你把文件中的代码(perl,php,java,c ++,smalltalk ......任何你想要的!)都放在 em>由服务器执行,除非浏览器具有该语言的解释器,否则浏览器不会执行,就像HTML,CSS和javascript一样。这就是为什么您的HTML文件中的PHP没有被执行:除非您指示您的Web服务器将该文件解释为PHP脚本,否则它会将其视为标准HTML文件。



在您的情况下,如果表单验证失败,您希望向用户显示错误消息。你也想保持你的代码和你的HTML文件分开(这是一个很好的习惯,恕我直言!)。这带来了问题,因为您确实需要更改HTML页面的内容以包含错误消息,但HTML页面基本上是静态的。您可以将用户重定向到具有相同内容的另一个页面,但在页面顶部会显示一条错误消息,但这是一个相当难看的解决方案。如果表单提交无效,您也可以使用javascript进行表单验证并向用户显示错误消息,但任何关闭JS的人都可以绕过该检查。



针对您的问题的最灵活的解决方案是使用模板系统,该系统允许您自定义页面内容,但让您的PHP代码免受HTML限制。那里有许多PHP模板系统;谷歌会为你提供很多。这些模板包含可以在PHP脚本中设置并在模板中使用的变量;模板引擎然后分析模板,插入变量并输出结果。



在您的情况下,您可以设置您的表单以在顶部显示错误消息的形式,并可能突出显示填写不正确的字段。



下面是一个使用

  include('Smarty.class。')是一个流行的,灵活的模板系统。 PHP'); 

//创建对象
$ smarty = new Smarty;

if(!empty($ _ POST)){
//验证表单输入
...
//最小表单验证:
if ($ scrubbed ['name'])&&!empty($ scrubbed ['email'])&&!empty($ scrubbed ['comments'])){
//发送您的电子邮件
//将用户重定向到一个感谢页面
header(Location:thankyou.html);
}
else {
//在模板中设置一个变量$ error
$ smarty-> assign('error','请完整填写表单');



//显示
$ smarty-> display('form.tpl');

模板文件 form.tpl ,应该包含您的标准表格以及任何需要添加的部分以防出现错误。下面是一个从 form.tpl 文件中的片段:

 < h2>联系我!< / h2> 
{if isset($ error)}
< div class =error>
< p>
{$ error}
< / p>
< / div>
{/ if}

(etc.)

如果contact.php检测到错误,则输出:

 < h2>联系我!< / h2> 
< div class =error>
< p>
请填写完整的表格
< / p>
< / p>
< form id =contactFormaction =contact.phpmethod =post>
(etc.)

如果没有错误(即表单没有填写):

 < h2>联系我!< / h2> 
< form id =contactFormaction =contact.phpmethod =post>
(等)

这是模板可以做的一个非常基本的例子。我希望已经澄清了一些事情,并让您一窥HTML模板的美妙世界。


I'm in the middle of sorting out the PHP for my contact form. What I'm trying to do is have an error message appear if the form isn't filled out. I have a div in my html with the error I want to show.

I know I can use 'echo' to display a message but I want it positioned exactly where I want it. I have seen a way of doing this, but it involves putting all the php code within the html file...and then renaming the file .php. I want to keep the bulk of the php code separate to the html.

Here is my code:

HTML:

<div class="error">
    <p>
        Please fill out all fields.
    </p>
</div>
<form id="contactForm" action="contact.php" method="post">
    <div>
        <input type="text" name="name" id="name" placeholder="Your Name" maxlength="65" tabindex="1"> <label for="name">Name</label> 
    </div>
    <div>
        <input type="email" name="_replyto" id="email" placeholder="Your Email" maxlength="30" tabindex="2"> <label for="email">Email</label> 
    </div>
    <div>
    <textarea name="message" id="message" rows="10" placeholder="Your Message..." maxlength="1000" tabindex="3"></textarea> <label for="message">Your Message</label> 
    </div>
    <div>
        <input type="submit" name="submit" value="Send" tabindex="4"> 
    </div>
</form>

PHP:

// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    /* The function takes one argument: a string.
    * The function returns a clean version of the string.
    * The clean version may be either an empty string or
    * just the removal of all newline characters.
    */
    function spam_scrubber($value) {

        // List of very bad values:
        $very_bad = array('to:', 'cc:', 'bcc:', 'content-type:', 'mime-version:', 'multipart-mixed:', 'content-transfer-encoding:');

        // If any of the very bad strings are in 
        // the submitted value, return an empty string:
        foreach ($very_bad as $v) {
            if (stripos($value, $v) !== false) return '';
        }

        // Replace any newline characters with spaces:
        $value = str_replace(array( "\r", "\n", "%0a", "%0d"), ' ', $value);

        // Return the value:
        return trim($value);

    } // End of spam_scrubber() function.

    // Clean the form data:
    $scrubbed = array_map('spam_scrubber', $_POST);

    // Minimal form validation:
    if (!empty($scrubbed['name']) && !empty($scrubbed['email']) && !empty($scrubbed['comments']) ) {

        // Create the body:
        $body = "Name: {$scrubbed['name']}\n\nComments: {$scrubbed['comments']}";

        // Send the email:
        mail('example@email.com', 'Contact Form Submission', $body, "From: {$scrubbed['email']}");

        // Print a message:
        echo '<p><em>Thank you.</em></p>';

        // Clear $scrubbed (so that the form's not sticky):
        $scrubbed = array();

    } else {
        echo '<p style="font-weight: bold; color: #C00">Please fill out the form completely.</p>';
    }

} // End of main isset() IF

My php is in a file called contact.php and my html is in a file called contact.html.

I want to show the div with class error, if the form isn't complete.

I tried another way by adding this code to the html, replacing the current error div:

<span class="error">* <?php include 'contact.php'; echo $Err;?></span>

and this to the php file:

$Err = "Please fill out all fields";

It still didn't work. It's as if it can't read the code in the php file from the html file, even though I included it?

Another thing is, how would I go about sending the user to another html page once the form has been submitted? Is it done by replacing

// Print a message:
echo '<p><em>Thank you.</em></p>';

with

header('Location: nextpage.html');

Thanks for any help in advance.

解决方案

First, you need to understand how the server processes PHP and HTML files. The server configuration tells it how to interpret files; some files are served as-is, some files are passed to a handler that executes them as a script, etc. In your server config, there will probably be a line that instructs the server to treat files with the extension .php as scripts to be executed using PHP. HTML files do not need to be executed; they are sent to the client, and the client's browser interprets the html, css, and js information to render a web page. Because HTML files are not executed as scripts, if you put code (perl, php, java, c++, smalltalk... whatever you want!) in the file, it will not be executed by the server, and it will not be executed by the browser unless the browser has an interpreter for that language, as is the case with HTML, CSS, and javascript. That is why the PHP in your HTML file is not being executed: unless you instruct your web server to interpret that file as a PHP script, it will treat it like a standard html file.

In your case, you want to present an error message to the user if the form validation fails. You also want to keep your code and your HTML file separate (which is a good habit to get into, IMHO!). This presents a problem because you really need to alter the content of the HTML page to include an error message, but the HTML page is essentially static. You could redirect users to another page with the same content, but an error message at the top of the page, but that's a rather ugly solution. You could also use javascript to do the form validation and present the user with an error message if their form submission is invalid, but anyone who has JS turned off will be able to bypass that check.

The most flexible solution for your problem is to use a template system that allows you to customise your page content but keep your PHP code free from HTML. There are a number of PHP template systems out there; google will turn up plenty for you. The templates contain variables that you can set in your PHP script and use in the template; the template engine then parses the templates, interpolates the variables, and outputs the result.

In your case, you could set up your form to display an error message at the top of the form and perhaps to highlight the fields that have been incorrectly filled.

Here is an example using Smarty, a popular, flexible template system:

include('Smarty.class.php');

// create object
$smarty = new Smarty;

if (! empty($_POST)) {
    // validate your form input
    ...
    // Minimal form validation:
    if (!empty($scrubbed['name']) && !empty($scrubbed['email']) && !empty($scrubbed['comments']) ) {
        // send your email
        // redirect user to a thank you page
        header("Location: thankyou.html");
    }
    else {
        // sets a variable $error in the template
        $smarty->assign('error', 'Please fill out the form completely');
    }
}

// display it
$smarty->display('form.tpl');

The template file, form.tpl, should contain your standard form plus any sections that you want added in case of error. Here's a snippet from an example form.tpl file:

<h2>Contact me!</h2>
{if isset($error)}
<div class="error">
    <p>
        {$error}
    </p>
</div>
{/if}

<form id="contactForm" action="contact.php" method="post">
(etc.)

output if contact.php detects an error:

<h2>Contact me!</h2>
<div class="error">
    <p>
        Please fill out the form completely
    </p>
</p>
<form id="contactForm" action="contact.php" method="post">
(etc.)

output if there is no error (i.e. the form has not been filled in):

<h2>Contact me!</h2>
<form id="contactForm" action="contact.php" method="post">
(etc.)

This is a very basic example of what templates can do. I hope that has clarified things a little and given you a glimpse into the wonderful world of HTML templates.

这篇关于如何使用PHP显示/隐藏元素以及如何将用户发送到其他页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆