This is opencart tips and tricks to check if Customer or Admin is logged in the front page of Opencart 2.3 and Opencart version 3. You can force login to customer. To check admin you should log in the same browser.
Force login for customer
Open catalog/controller/common/header.php
Find the index method: public function index() { then paste the following lines of code:
if ($this->request->get['route'] != "account/login") { if (!$this->customer->isLogged()) { $this->session->data['redirect'] = $this->url->link('common/home', '', true); $this->response->redirect($this->url->link('account/login', '', true)); } }
The above code check if route is login page or not and if it is not then it checks whether the customer is logged in or not, if not logged in then it redirects to login page. If the customer is logged in then it acts as normally.
Check whether Admin is logged in or not from the catalog or frontend
Now go to any controller and insert the code to check if user_id is set in the session. For example: Go to catalog/controller/common/header.php
Inside the index() method add the following code:
if($this->session->data['user_id']){ echo 'Admin is logged in'; }else{ echo 'Admin is not logged in'; }
Another way initialize the user object and check with isLogged() method
$loggeduser = new Cart\User($this->registry); if($loggeduser->isLogged()){ echo "Admin is in"; }else{ echo "Admin not in"; }
This is how we can use Opencart library global objects methods.
Let us know if you find any difficulties or need any help from us. Likewise, you can see other Opencart tips and tricks and Opencart tutorial
First way gives me:
in front page:
`Notice: Undefined index: user_id in C:wamp64wwwitwcatalogcontrollercommonheader.php on line 62Admin is not logged in`
while trying to login to /admin:
`( ! ) Parse error: syntax error, unexpected ‘$data’ (T_VARIABLE), expecting function (T_FUNCTION) in C:wamp64wwwitwadmincontrollercommonlogin.php on line 39`
In second way, front is clean but /admin:
`( ! ) Parse error: syntax error, unexpected ‘$data’ (T_VARIABLE), expecting function (T_FUNCTION) in C:wamp64wwwitwadmincontrollercommonlogin.php on line 39`
https://ibb.co/fX99bF
The error was on my side. Its working with the second way! thanks a lot!
But what if you have logged as admin to the back, and as a customer to the front (i’ve do this all the time while development)? In this case method gerLogged will return cusomer data, not admin.
It will return Admin getLogged.
To check the customer check with something like below:
$loggeduser = new Cart\Customer($this->registry);
if($loggeduser->isLogged()){
echo “Customer is in”;
}else{
echo “Customer not in”;
}
Hope it helps.
Thanks