Hello,
I'm trying to create an external PHP script to be used in a web browser, but it should work only if the admin is logged in.
<?php require __DIR__ . '/../app/bootstrap.php'; $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER); $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('adminhtml'); $backendSession = $objectManager->get('Magento\Backend\Model\Auth\Session'); if ($backendSession->isLoggedIn()) { // do something }
Looks like I'm missing something - `$backendSession->isLoggedIn()` always returns false. Can you help please?
Thanks
It's possible that the session is not being properly initialized. Here are a few things you can try:
Make sure that the script is being executed in the context of the admin panel. This means that you need to access the script through the admin panel, not directly through a web browser.
Check that the session cookie is being properly set. You can check this by inspecting the cookies in your browser's developer tools. The cookie should have a name like adminhtml and a value that corresponds to the session ID.
Check that the session storage is configured correctly. In Magento 2, sessions can be stored in files, a database, or Redis. Make sure that the correct storage backend is being used and that it is properly configured.
Try logging in to the admin panel and then running the script. If the session is not being properly initialized, logging in to the admin panel may trigger the session to be created.
If none of these steps solve the problem, you may need to do some further debugging to figure out what's going wrong. You can add some var_dump() statements to print out the values of various variables and see where the script is getting stuck.