我的表格有问题吗?

发布于 2024-10-07 17:32:22 字数 3986 浏览 0 评论 0 原文

我的表格可以正常工作,所有错误都可以正常工作。 但是,如果出现错误,它会刷新页面并删除单击提交按钮之前插入的所有文本,并且您必须重新输入所有信息。 无论如何要解决这个问题吗?

我认为这与在表单的操作中不使用 $_SERVER["PHP_SELF"] 有关。 相反,我有 action=""

我这样做是因为需要使用相同信息刷新的页面在其 url (monthly_specials_info.php?date=Dec10) 中有一个从上一页放在那里的变量。

我尝试使用

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

它并生成了正确的网址。但无论如何,当提交表单时,文本都被删除了(有错误)..有什么想法吗?

表单代码:

echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';

和验证者:

if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "[email protected]", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}

I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';

and the vaildator:

if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "[email protected]", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

心意如水 2024-10-14 17:32:22

第一:你不能信任'.$_SERVER它可以被修改。小心一点!

第二:您可以(应该?)使用 隐藏 字段而不是在操作中指定它?

但是如果出现错误,它会刷新
页面并删除任何文本
在提交按钮之前插入
点击后您必须重新输入所有内容
的信息。无论如何要修复
这个?

您可以使用 ajax 来修复它(我相信普通的旧 HTML 有这种副作用吗?) 。

First: you cannot trust '.$_SERVER it can be modified. Be carefull with that!

Second: you could(should?) use a hidden field instead of specifing it in the action?

But if you have an error, it refreshes
the page and removes any text that was
inserted before the submit button was
clicked and you have to re-enter all
of the information. Anyway to fix
this?

You could use ajax to fix it(I believe plain old HTML has this side-effect?).

瀟灑尐姊 2024-10-14 17:32:22

浏览器不必重新填写表单。有些是为了方便,但你不能依赖它。

如果您再次显示表单,您可以像这样设置输入的值:

$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';

当然,您应该在将 POST 数据包含在 HTML 中之前检查并清理它,以免造成任何 XSS 漏洞。

A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.

In case you display the form again, you could set the values of the inputs like this:

$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';

Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.

蓝天 2024-10-14 17:32:22

如果您希望表单提交到同一页面,则不需要设置操作,没有它也可以工作。另外我建议您以这种方式发送日期:

<input type="hidden" name="date" value="'.$date.'"/>

If you want the form to submit to the same page, you don't need to set an action, it works without it as well. Also I'd suggest you to send the date in this way:

<input type="hidden" name="date" value="'.$date.'"/>
写给空气的情书 2024-10-14 17:32:22

事实上,验证器和 html 代码内部存在一些大问题以及我要更改的内容,您要问的是:我怎样才能使编译的表单不会在刷新。

基本上不知道有关您的项目的任何信息,提交的字符串去了哪里,如果它们存储在数据库或其他地方,该页面在您的项目上下文中意味着什么我无法编写一个特定的脚本来使提交的字符串在将来重新加载时记住页面,但要澄清一些事情:

如果有一个表单定义为

并使用 (这应该足够了,无需给它命名 name="submit")页面被刷新,并且它不会自动记住输入您之前提交的。
为此,您有 2 个选择:

  1. 使用 Ajax(检查 Jquery 作为 ajax 的良好框架),这将允许您提交表单而无需刷新页面。我选择它作为第一种方式,因为它被每个人过度使用,并且它会变得越来越多,因为它是新的并且工作顺利。
  2. 制作一个 php 脚本,允许您检查输入是否已经提交;如果答案是 true,则恢复值并以这种方式获取它们:>

另请注意,自 ?date='.$date.' 起,您不需要 '.$_SERVER["PHP_SELF"].'?date='.$date.'代码>就足够了。

A part from the fact that that validator and html code has some big issues inside and things i'd change, what you are asking is: How could i make that the form compiled doesn't remove all the text from my input tags after the refresh.

Basically not knowing anything about your project, where the strings submitted goes, if they are stored in a database or somewhere else, what does that page means inside your project context i cannot write a specific script that makes submitted string remembered in a future reload of the page, but to clarify some things:

If there is a form that is defined as <form></form> and is submitted with a <input type="submit"/> (which should be enough, without giving it a name name="submit") the page is refreshed and it does not automatically remember the input your previously submitted.
To do that you have 2 choice:

  1. Use Ajax (check Jquery as good framework for ajax), which will allow you to submit forms without refreshing the page. I choose it as first way because it is over-used by everyone and it is going to became more and more used because it is new and it works smoothly.
  2. Make a php script that allows you to check if the input has already been submitted; in case the answer is true, then recover the values and get them in this way: <input type="text" value="<?php echo $value ?>"/>.

Also notice that you do not need of '.$_SERVER["PHP_SELF"].'?date='.$date.' since ?date='.$date.' is enough.

奢望 2024-10-14 17:32:22

浏览器不会为您重新填充表单,尤其是在执行 POST 时。由于您构建的表单中没有填写 value="" 块的字段,因此浏览器只会为您呈现空字段。

一个非常基本的表单处理脚本看起来像这样:

<?php

if ($_SERVER['REQUEST_METHOD'] = 'POST') {
    # do this only if actually handling a POST
    $field1 = $_POST['field1'];
    $field2 = $_POSt['field2'];
    ...etc...

    if ($field1 = '...') {
       // validate $field1
    }
    if ($field2 = '...') {
       // validate $field2
    }
    ... etc...

    if (everything_ok) {
        // do whatever you want with the data. insert into database?
        redirect('elsewhere.php?status=success')
    } else {
       // handle error condition(s)
    }
} // if the script gets here, then the form has to be displayed

<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>

?>

注意在最后一位输出表单字段时使用 htmlspecialchars() 。考虑一下有人在字段中输入 html 元字符("<>)的情况。如果出于某种原因必须显示表单,这些字符将被输出到 html 中并“破坏”表单,并且每个浏览器都会以不同的方式“破坏”,有些浏览器(*咳嗽*IE*咳嗽*)会吐出所有内容。通过使用 htmlspecialchars(),这些元字符将被“转义”,以便它们能够正确显示并且不会破坏表单

。 HTML 块,并且可能在其中嵌入 PHP 变量,您最好阅读 HEREDOC。是一种特殊的构造,充当多行双引号字符串,但使您不必进行任何引号转义,它们使代码更具可读性,并且您不必担心选择正确的类型。当您跳入/跳出“字符串模式”以输出变量时,引号或正确数量的引号。

Browsers will not re-populate a form for you, especially when doing a POST. Since you're not building the form with fields filled out with value="" chunks, browsers will just render empty fields for you.

A very basic form handling script would look something like this:

<?php

if ($_SERVER['REQUEST_METHOD'] = 'POST') {
    # do this only if actually handling a POST
    $field1 = $_POST['field1'];
    $field2 = $_POSt['field2'];
    ...etc...

    if ($field1 = '...') {
       // validate $field1
    }
    if ($field2 = '...') {
       // validate $field2
    }
    ... etc...

    if (everything_ok) {
        // do whatever you want with the data. insert into database?
        redirect('elsewhere.php?status=success')
    } else {
       // handle error condition(s)
    }
} // if the script gets here, then the form has to be displayed

<form method="POST" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($field1) ?>" />
<br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($field2) ?>" />
etc...
<input type="submit" />
</form>

?>

Notice the use of htmlspecialchars() in the last bit, where form fields are being output. Consider the case where someone enters an html meta-character (", <, >) into the field. If for whatever reason the form has to be displayed, these characters will be output into the html and "break" the form. And every browser will "break" differently. Some won't care, some (*cough*IE*cough*) will barf bits all over the floor. By using htmlspecialchars(), those metacharacters will be "escaped" so that they'll be displayed properly and not break the form.

As well, if you're going to be outputting large chunks of HTML, and possibly embedding PHP variables in them, you'd do well to read up on HEREDOCs. They're a special construct that act as a multi-line double-quoted string, but free you from having to do any quote escaping. They make for far more readable code, and you don't have to worry about choosing the right kind of quotes, or the right number of quotes, as you hop in/out of "string mode" to output variables.

烟─花易冷 2024-10-14 17:32:22

首先,进行一些常规更改:

更改

<form method="post" action="'.$_SERVER["PHP_SELF"].'">
    <input type="hidden" name="data" value="'.$date.'" />

原始问题的答案:

使用 $_POST['whatever'] 设置每个 input 元素 value 属性 if array_key_exists('whatever ', $_POST);

例如:姓名字段

<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />

first, a few general changes:

change

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

to

<form method="post" action="'.$_SERVER["PHP_SELF"].'">
    <input type="hidden" name="data" value="'.$date.'" />

the answer to your original question:

set each input elements value attribute with $_POST['whatever'] if array_key_exists('whatever', $_POST);

For example: the name field

<input type="text" name="name" value="<?php echo array_key_exists('name', $_POST) ? $_POST['name'] : ''; ?>" />
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文