使用GET& A进行适当的变量检查。 POST变量

时间:2010-07-31 23:17:03

标签: php

检查通过GETPOST传递的变量是否正确时,我可能会这样:

<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
  if(!isset($_POST['new_email']))
    header('Location: somepage.php');
  else if(empty($_POST['new_email']))
    //Report error to user and prompt to try again
  else
    $newEmail = $_POST['new_email'];

  if(!isset($_POST['full_name']))
    header('Location: somepage.php');
  else if(empty($_POST['full_name']))
    //Report error to user and prompt to try again
  else
    $newName = $_POST['full_name'];

  if(!isset($_POST['new_password_a']))
    header('Location: somepage.php');
  else if(empty($_POST['new_password_a']))
    //Report error to user and prompt to try again
  else
    $newPasswordA = $_POST['new_password_a'];

  if(!isset($_POST['new_password_b']))
    header('Location: somepage.php');
  else if(empty($_POST['new_password_b']))
    //Report error to user and prompt to try again
  else
    $newPasswordB = $_POST['new_password_b'];

  //Do some things with the variables
}
else
{
  header('Location: somepage.php');
}

//View
//Display relevant view here
?>

如何检查GET脚本中的POSTPHP个变量?我想知道是否有更好的方法?

3 个答案:

答案 0 :(得分:4)

也许创建一个函数来避免重复的代码?

function check($varname,$destination,$message) {
    if (!isset($_POST[$varname])) {
        header("Location: $destination");
    } else if (empty($_POST[$varname])) {
        //Do something with $message
    } else {
        return $_POST[$varname];
    }
    return NULL;
}

然后,

<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
  $newEmail = check('new_email','somepage.php','Error message');
  $newName = check('new_name','somepage.php','Error message');
  $newPasswordA = check('new_password_a','somepage.php','Error message');
  $newPasswordB = check('new_password_b','somepage.php','Error message');

  //Do some things with the variables
  //Checking for NULL values (although if some var was null, 
  //it should have either redirected or reported an error)
}
else
{
  header('Location: somepage.php');
}

//View
//Display relevant view here
?>

Pixel Developer说的是真的,你应该至少针对SQL注入(如果你将使用数据库中的数据)和CSRF攻击来清理输入。

答案 1 :(得分:1)

<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
  foreach ($_POST as $key => $value) {
    if (empty($value)) {
      echo 'whoops, remember to set ', $key;
    } else {
      switch($key) {
        case 'new_password_a':
          $newPasswordA = $value;
          break;
        //etc
      }
    }
  }
  if (isset($newPasswordA) && isset($newPasswordB)) { //check all vars have been set or whatever
    header('Location: somepage.php');
  } else {
    header('Location: somepage.php');
  }

对不起我对代码更具体,你的示例代码有点模糊。我希望有所帮助。

答案 2 :(得分:1)

你的代码一开始就是一团糟。请使用括号,更好的代码注释和类/函数。

除非密钥有值,否则您不会检查任何正确的内容。您可能希望添加CSRF令牌以确保请求来自您期望的表单。

请看CSRF on Wikipedia