PHP - uses __construct () to check for a session

I need to resolve the doubt, I leave the details.

I have a class that has several related database queries with user data, to access these methods you need to check that the user is logged in, and I do this using the php initialization methods "__construct ()", indicate there if user is logged in.

<?php
class User() 
{
    public function __construct() {

        if ( !isset($_SESSION['user']) ) {
            $data = array(
                'response' => false,
                'message'   => 'You must login to access this page'.
            );
            echo json_encode($data);
        }
    }

    public function index() {
        // The user can access if you are logged
    }

    public function edit_profile()  {
        // The user can not access if you have not logged
    }

    public function save_profile_data() {
        // The user can not access if you have not logged
    }
}
?>

My questions:

  • Using __ () construct is a good optimal resource-intensive choice?
  • __ construct () is safe to use and does not allow the user to access other methods that have not indicated whether there is an encoded session variable.

.. edit_profile(), , __ construct(), ?

, , .

+4
1

class Authenticate {
    var $table;
    public function __construct()
    {
        $this->ci =& get_instance();

    }
  public function is_logged_in()
    {
        $sessionid = $this->ci->session->userdata('moderId');
        if($sessionid)
        {
        return isset($sessionid);
        }
         else if(!$sessionid) {
      redirect(base_url() . 'moderator');
 }
    }
}

. ,

class B2bcategory extends CI_Controller {

    function __construct() {
        parent::__construct();

        $this->load->model('moderator/b2bcategory_model');

        $this->authenticate->is_logged_in();
    }
}
+2

Source: https://habr.com/ru/post/1627381/


All Articles