如何使用$ _GET& $ _POST功能正常吗?

时间:2014-01-18 20:46:42

标签: php post get

我刚刚遇到一个问题,我找不到可能的解决方案。我会试着向你们解释一下。

假设我们创建了一个函数,我们将检查所提供的Field是否已设置。它可以使用$ _POST或$ _GET提交。让我们看看这个理论的一个例子:

// The field is the name of the submitted form element, the method should be either POST or GET

        function isset_test($field, $method)
        {
            if ($method === 'POST')
            {
                if (isset($_POST[$field]) === true)
                {
                    echo 'POST field isset';
                }
            }
            elseif ($method === 'GET')
            {
                if (isset($_GET[$field]) === true)
                {
                    echo 'GET field isset';
                }
            }
        }

正如您在本示例中所看到的,代码应该正常工作,但它几乎是一个重复的代码。

这就是我考虑的原因:我们可以获得$method的值(应该是POST还是GET)并将其放在代码中作为变量?像这样的东西(但我知道它不起作用):

// The field is the name of the submitted form element, the method should be either POST or GET

        function isset_test($field, $method)
        {
            if ($method === 'POST' || $method === 'GET')
            {
                if (isset($_ . $method . [$field]) === true)
                {
                    echo $method . ' field isset';
                }
            }
        }

上面的代码不起作用,因为PHP将$method视为字符串。有没有解决方案,所以PHP会将它们作为真正的$_POST[]$_GET[]变量?

编辑:

我实际上对这两个字段都不好,所以我不想使用$ _REQUEST。我只是想创建一个可以用于两种请求类型的函数,并在需要时调用其中一个。

5 个答案:

答案 0 :(得分:1)

使用$ _REQUEST获取GET或POST

这样你可以检查

if (isset($_REQUEST["variable_name"])) {
    // This will give GET and POST values
}

答案 1 :(得分:0)

如果你对$_POST$_GET中的字段感到满意,只需使用$_REQUEST即可。它包含来自post和get的数据。

答案 2 :(得分:0)

你在函数中写的内容,我将对此进行一些修改。

Here is my coding:


        if ($_SERVER['REQUEST_METHOD'] === 'POST')
            {
              if (isset($_POST[$field]))
                 {
                   echo 'POST field isset';
                 }
            }

        else
           {
               if (isset($_GET[$field]))
                  {
                     echo 'GET field isset';
                  }
           }

$ _ SERVER ['REQUEST_METHOD'] 可帮助您检查请求方法类型。

你也可以试试这个:

 if ($_SERVER['REQUEST_METHOD'] === 'POST')
      {

         echo 'POST field isset';

      }

   else
      {

          echo 'GET field isset';

      }



Hope it will work
Thank you 
Dron

答案 3 :(得分:0)

简单的解决方案:

function isset_test($field)
{
    if (isset($_POST[$field]))
    {
            echo 'POST field isset';
    }
    elseif (isset($_GET[$field]))
    {
        echo 'GET field isset';
    }
    else
    {
        echo 'Neither GET or POST';
    }
}

答案 4 :(得分:-1)

PHP variable variables允许您访问$$method[$field]

但是,在您的具体情况下,您也可以使用$_REQUEST