【发布时间】:2013-12-12 12:01:43
【问题描述】:
我想知道验证输入变量的最佳方法在哪里。你可以对每个框架都应用这个问题,但在我的例子中是 Symfony2:控制器是一个类,它处理像单个控制器这样的方法。
例如我有一个控制器类,其中每个操作都是一个方法:
namespace MSD\HomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MSD\HomeBundle\Entity\Imagen as Imagen;
class HomeController extends Controller
{
public function indexAction()
{
if( isset( $_POST['whatever'] ) && $whatever = intval( $_POST['whatever'] ) )
{
$iFoo1 = $whatever * 25;
$iFoo2 = $whatever / 32;
return $this->render( 'MSDHomeBundle:Home:template.html.twig', array( 'foo'=> array( 'foo1'=>$iFoo1, 'foo2'=>$iFoo2 ) ) );
}
}
//...
}
$whatever 在控制器操作中得到验证。但是您可以为每种操作创建一个方法。例如
private function multiply( $iNum1, $iNum2 )
{
return ( $iNum1 * $iNum2 );
}
private function divide( $iNum1, $iNum2 )
{
return ( $iNum1 / $iNum2 );
}
你应该验证每个函数的参数:
private function multiply( $iNum1, $iNum2 )
{
return ( intval( $iNum1 ) * intval( $iNum2 ) );
}
private function divide( $iNum1, $iNum2 )
{
return ( intval( $iNum1 ) / intval( $iNum2 ) );
}
并从控制器调用它们:
namespace MSD\HomeBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use MSD\HomeBundle\Entity\Imagen as Imagen;
class HomeController extends Controller
{
public function indexAction()
{
if( isset( $_POST['whatever'] ) && $whatever = intval( $_POST['whatever'] ) )
{
$iFoo1 = $this -> multiply( $whatever, 25 );
$iFoo2 = $this -> divide( $whatever / 32 );
return $this->render( 'MSDHomeBundle:Home:template.html.twig', array( 'foo'=> array( 'foo1'=>$iFoo1, 'foo2'=>$iFoo2 ) ) );
}
}
//...
}
但是你验证$_POST['whatever'] 三次:在if 条件和两个私有函数中。但是,我猜这应该是更安全的验证方式,因为您不能“忘记”验证,因为每个函数都会验证自己的参数。但也意味着重复验证。
我不确定是否有更好的方法。我找不到更好的解决方案,在不重复验证的情况下保持最大安全性。
【问题讨论】:
-
使用 symfony 你应该使用请求包而不是直接点击 $_POST、$_GET 等参数。
标签: php validation symfony model-view-controller