如何从 PHP 访问表单的“名称”变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/846020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:04:08  来源:igfitidea点击:

How to access the form's 'name' variable from PHP

phpforms

提问by David says reinstate Monica

I'm trying to create a BMI calculator. This should allow people to use either metric or imperial measurements.

我正在尝试创建一个 BMI 计算器。这应该允许人们使用公制或英制测量。

I realise that I could use hidden tags to solve my problem, but this has bugged me before so I thought I'd ask: I can use $_POST['variableName']to find the submitted variableName field-value; but...I don't know, or see, how to verify which form was usedto submit the variables.

我意识到我可以使用隐藏标签来解决我的问题,但这之前一直困扰着我,所以我想我会问:我可以使用$_POST['variableName']来查找提交的 variableName 字段值;但是......我不知道,或看,如何验证其形式用于提交的变量。

My code's below (though I'm not sure it's strictly relevant to the question):

我的代码如下(虽然我不确定它是否与问题严格相关):

<?php
    $bmiSubmitted     = $_POST['bmiSubmitted'];

    if (isset($bmiSubmitted)) {
        $height        = $_POST['height'];
        $weight        = $_POST['weight'];
        $bmi        = floor($weight/($height*$height));

        ?>
            <ul id="bmi">
            <li>Weight (in kilograms) is: <span><?php echo "$weight"; ?></span></li>

            <li>Height (in metres) is: <span><?php echo "$height"; ?></span></li>

            <li>Body mass index (BMI) is: <span><?php echo "$bmi"; ?></span></li>

            </ul>
        <?php
    }

    else {
    ?>

    <div id="formSelector">

    <ul>
        <li><a href="#metric">Metric</a></li>
        <li><a href="#imperial">Imperial</a></li>
    </ul>

        <form name="met" id="metric" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">

            <fieldset>
                <label for="weight">Weight (<abbr title="Kilograms">kg</abbr>):</label>
                    <input type="text" name="weight" id="weight" />

                <label for="height">Height (<abbr title="metres">m</abbr>):</label>
                    <input type="text" name="height" id="height" />

                <input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
            </fieldset>

            <fieldset>
                <input type="reset" id="reset" value="Clear" />

                <input type="submit" id="submit" value="Submit" />
            </fieldset>
        </form>

        <form name="imp" id="imperial" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">

            <fieldset>

            <label for="weight">Weight (<abbr title="Pounds">lbs</abbr>):</label>
                <input type="text" name="weight" id="weight" />

            <label for="height">Height (Inches):</label>
                <input type="text" name="height" id="height" /
            <input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
            </fieldset>

            <fieldset>
                <input type="reset" id="reset" value="Clear" />
                <input type="submit" id="submit" value="Submit" />
            </fieldset>
        </form>

    <?php
    }
?>

I verified that it worked (though without validation at the moment -I didn't want to crowd my question too much) with metric; I've added the form but not the processing for the imperial yet.

我用公制验证了它的工作原理(尽管目前没有验证 - 我不想过多地拥挤我的问题);我已经添加了表格,但还没有添加帝国的处理。

回答by Ayman Hourieh

To identify the submitted form, you can use:

要识别提交的表单,您可以使用:

  • A hidden input field.
  • The name or value of the submit button.
  • 一个隐藏的输入字段。
  • 提交按钮的名称或值。

The name of the form is not sent to the server as part of the POST data.

表单名称不会作为 POST 数据的一部分发送到服务器。

You can use code as followed

您可以使用如下代码

<form name="myform" method="post" action="" enctype="multipart/form-data">
    <input type="hidden" name="frmname" value=""/>
</form>

回答by Seb

You can do it like this:

你可以这样做:

<input type="text" name="myform[login]">
<input type="password" name="myform[password]">

Check the posted values

检查发布的值

if (isset($_POST['myform'])) {
    $values = $_POST['myform'];

    // $login = $values['login'];
    // ...
}

回答by Paolo Bergantino

The form name is not submitted. You should just add a hidden field to each form and call it a day.

未提交表单名称。您应该只为每个表单添加一个隐藏字段并收工。

回答by Ruwantha

In the form submitting button (id method of form is post):

在表单提交按钮中(表单的 id 方法是post):

<input type="submit" value="save" name="commentData">

In the PHP file:

在 PHP 文件中:

if (isset($_POST['commentData'])){
    // Code
}

回答by albator

For some reason, the name of the submit button is not passed to the superglobal $_POSTwhen submitted with Ajax/jQuery.

出于某种原因,$_POST使用 Ajax/jQuery 提交时,提交按钮的名称不会传递给超全局变量。

Just in case it helps someone...

以防万一它可以帮助某人...

回答by Elttob

You can use GET in the form's action parameter, which I use whenever I make a login/register combined page.

您可以在表单的操作参数中使用 GET,每当我创建登录/注册组合页面时都会使用该参数。

For example: action="loginregister.php?whichform=loginform"

例如: action="loginregister.php?whichform=loginform"

Hope this helps!

希望这可以帮助!

回答by Lachlan McD.

As petervandijck.compointed out, this code may be susceptible to XSS attacks if you have it behind some kind of log-in system or have it embedded in other code.

正如petervandijck.com指出的那样,如果您将其置于某种登录系统之后或将其嵌入其他代码中,则此代码可能容易受到 XSS 攻击。

To prevent an XSS attack, where you have written:

为了防止 XSS 攻击,您在其中编写了:

<?php echo "$weight"; ?>

You should write instead:

你应该写:

<?php echo htmlentities($weight); ?>

Which could even be better written as:

甚至可以更好地写成:

<?=htmlentities($weight); ?>

回答by xinthose

Use a unique value on the submit button for each form like so

像这样在每个表单的提交按钮上使用唯一的值

index.html

索引.html

<form method="post" action="bat/email.php">
    <input type="text" name="firstName" placeholder="First name" required>
    <input type="text" name="lastName" placeholder="Last name" required>
    <button name="submit" type="submit" value="contact">Send Message</button>
</form>

<form method="post" action="bat/email.php">
    <input type="text" name="firstName" placeholder="First name" required>
    <input type="text" name="lastName" placeholder="Last name" required>
    <button name="submit" type="submit" value="support">Send Message</button>
</form>

email.php

电子邮件.php

<?php
    if (isset($_POST["submit"])) {
      switch ($_POST["submit"]) {
          case "contact":
              break;
          case "support":
              break;
          default:
              break;
      }
    }
?>

回答by James Anderson Jr.

I had a similar problem which brought me to this question. I reviewed all the preceding answers but ultimately I ending up figuring out my own solution. I hope it helps someone else with this same issue:

我有一个类似的问题,这让我想到了这个问题。我查看了所有前面的答案,但最终我找到了自己的解决方案。我希望它可以帮助其他人解决同样的问题:

<form name="ctc_form" id="ctc_form" action='' method='get'>

<input type="hidden" name="form_nm" id="form_nm">

<button type="submit" name="submit" id="submit" onclick="document.getElementById('form_nm').value=this.closest('form').name;">Submit</button>

</form>

It seamlessly and efficiently accomplishes the following:

它无缝且高效地完成以下工作:

  • Passes the form nameattribute via a hidden inputfield, without using the fallible valueattribute of the submitbutton.
  • Works with both GETand POSTmethods.
  • Requires no additional, independent JavaScript.
  • 通过隐藏的输入字段传递表单名称属性,而不使用提交按钮的错误属性。
  • 适用于GETPOST方法。
  • 不需要额外的、独立的 JavaScript。

回答by Adrian Fischer

You could just give a name to the submit button and do what needs to be done based on that. I have several forms on a page and do just that. Pass the button name and then if button name = button name do something.

您可以只为提交按钮命名,然后根据该名称执行需要完成的操作。我在一个页面上有几个表格,就这样做了。传递按钮名称,然后如果按钮名称 = 按钮名称执行某些操作。