无法使用PHP exit()隐藏页面内容;

时间:2015-01-06 12:02:03

标签: php oop exit

我有添加待办事项的功能:

function add() {
    //Access control
    $session=new Auth();
    $session->start();
    $access=new Access();
    $role=$_SESSION['userinfo']['role'];
    $action=2;
    $access->restrict($role,$action);
    $todo = $_POST['todo'];
    $this->set('title','Success - My Todo List App');
    $this->set('todo',$this->Item->query('insert into items (item_name) values (\''.mysql_real_escape_string($todo).'\')'));   
}

通常添加说todo成功添加的页面是这样的:

<a class="big" href="../items/viewall">Todo successfully added. Click here to go back.</a>

但是因为我想限制普通用户访问以添加待办事项,所以这里是限制功能:

function restrict($role,$action){
    $sql=mysql_query("SELECT * FROM permissions WHERE role_id='$role' AND action_id='$action'");
    $count=mysql_num_rows($sql);
    if($count>0){
        echo "<div class='warning_positive'>Access Granted</div>";
    }
    else{
        echo "<div class='warning_negative'>Access Denied</div>";
        exit();
    }
}

要拒绝访问,它会显示访问被拒绝,并且不会添加该待办事项。但它仍然显示Todo成功添加。如你所见,我把那个退出();使那个字符串没有看到,但仍然是看到。我该怎么办?提前致谢

2 个答案:

答案 0 :(得分:1)

因为你在函数restrict()中调用exit(),其范围以函数作用域结尾。

不是在函数restrict()中显示错误sting,而是返回行数。

根据返回的计数,授予访问权限或只显示错误消息。

这种方法会减少代码行。

更正后的代码:

function restrict($role,$action){
  $sql=mysql_query("SELECT * FROM permissions WHERE role_id='$role' AND action_id='$action'");
  $count=mysql_num_rows($sql);
  return $count;
}

function add() {
  //Access control
  $session=new Auth();
  $session->start();
  $access=new Access();
  $role=$_SESSION['userinfo']['role'];
  $action=2;
  $access = $access->restrict($role,$action);
  if ($access > 0) {
    echo "<div class='warning_positive'>Access Granted</div>";
    $todo = $_POST['todo'];
    $this->set('title','Success - My Todo List App');
    $this->set('todo',$this->Item->query('insert into items (item_name) values (\''.mysql_real_escape_string($todo).'\')'));   
  }
  else {
        echo "<div class='warning_negative'>Access Denied</div>";
  }
}

答案 1 :(得分:0)

尝试下面,应该工作。

function add() {
    //Access control
    $session=new Auth();
    $session->start();
    $access=new Access();
    $role=$_SESSION['userinfo']['role'];
    $action=2;
    if($access->restrict($role,$action)){
        echo "<div class='warning_positive'>Access Granted</div>";    
    }else{
        echo "<div class='warning_negative'>Access Denied</div>";
        exit();
    }
    $todo = $_POST['todo'];
    $this->set('title','Success - My Todo List App');
    $this->set('todo',$this->Item->query('insert into items (item_name) values (\''.mysql_real_escape_string($todo).'\')'));   
}


function restrict($role,$action){
    $sql=mysql_query("SELECT * FROM permissions WHERE role_id='$role' AND action_id='$action'");
    $count=mysql_num_rows($sql);
    if($count>0){
        return true;
    }
    else{
        return false;
    }
}