";if else语句“;当不存在$_REQUEST时


"if else statement" when no $_REQUEST exist

我正在做一个简单的if and else语句来从请求的链接中获取值,我的代码是

if($_REQUEST['f_id']=='')
{
    $friend_id=0;
}
else
{
    $friend_id=$_REQUEST['f_id'];
}

并且假设链路是www.example.com/profile.php?f_id=3

现在它很简单,就好像f_id是空的,或者上面的if和else语句中的任何一个都将运行。但什么是用户只是在玩链接,他删除了整个CCD_ 3,链接还剩下用CCD_ 4打开,那么如何检测到CCD_ 5不存在,并且在这种情况下重定向到错误页面?

if ( isset( $_REQUEST['f_id'] ) ) {
    if($_REQUEST['f_id']=='') {
        $friend_id=0;
    } else {
        $friend_id=$_REQUEST['f_id'];
    }
} else {
    REDIRECT TO ERROR PAGE
}

更新因为URLS-s看起来像www.example.com/profile.php?f_id=3,所以应该使用$_GET而不是$_REQUEST

您可以使用isset()php函数来测试:

if(!isset($_REQUEST) || $_REQUEST['f_id']=='')
{ 
   $friend_id=0; 
} 
else 
{ 
  $friend_id=$_REQUEST['f_id']; 
} 

答案很晚,但这里有一个我一直使用的"优雅"解决方案。我从我感兴趣的所有变量的代码开始,然后从那里开始。PHP EXTRACT文档中也显示了您可以对提取的变量执行许多其他操作。

// Set the variables that I'm allowing in the script (and optionally their defaults)
    $f_id = null        // Default if not supplied, will be null if not in querystring
    //$f_id = 0         // Default if not supplied, will be false if not in querystring
    //$f_id = 'NotFound'    // Default if not supplied, will be 'NotFound' if not in querystring
// Choose where the variable is coming from
    extract($_REQUEST, EXTR_IF_EXISTS); // Data from GET or POST
    //extract($_GET, EXTR_IF_EXISTS);   // Data must be in GET
    //extract($_POST, EXTR_IF_EXISTS);  // Data must be in POST
if(!$f_id) {
    die("f_id not supplied...do redirect here");
}

您可以使用empty将2x isset组合为1语句(除非您实际的friend_id为0,这将导致empty为true)

if(empty($_REQUEST['f_id'])) {
   $friend_id=0;
} else {
  $friend_id=$_REQUEST['f_id'];
}