How can we check if the website is using pub directory or not, independent of its mode?
Is there any Magento function present to check the root document?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityAnd finally after many testing, I found the most relevant solution to handle this. Code is as below:
use Magento\Framework\App\Filesystem\DirectoryList;
protected $_directoryList;
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
DirectoryList $directoryList,
array $data = []
) {
$this->_directoryList = $directoryList;
parent::__construct($context, $data);
}
And now the pub directory can be checked by the condition
$pub = $this->_directoryList->getUrlPath("pub");
if ($pub == "pub") {
//pub is not being used
} else {
//pub directory is being pointed
}
pub: The pub directory is where the publicly exposed files are located. This is the directory that we should set as root when setting up Apache or Nginx. The pub/index.php file is what gets triggered when the storefront is opened in a browser.
Try following code to get Directory Path and Current Mode:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
try{
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$directoryList = $objectManager->get('\Magento\Framework\Filesystem\DirectoryList');
$root = $directoryList->getRoot();
$state = $objectManager->get('\Magento\Framework\App\State');
$mode = $state->getMode();
echo "Project Directory Path: " . $root . "<br/>";
echo "Current Mode: " . $mode;
} catch (Exception $e) {
echo $e->getMessage();
}
I don't know If I understand your question correctly but let me try, If you want to find your project root directory then you can find it like,
use Magento\Framework\Filesystem\DirectoryList;
protected $directoryList;
public function __construct(
...
DirectoryList $directoryList
....
) {
....
$this->directoryList = $directoryList;
....
}
$rootDir = $this->directoryList->getRoot()
And yes, you are right Magento2
use pub
directory index.php
If your current mode is production
otherwise It uses root index.php
. If you want to check current mode by code then you can check it like this,
use Magento\Framework\App\State;
protected $state;
public function __construct(
...
State $state
....
) {
....
$this->state = $state;
....
}
$currentMode = $this->state->getMode();
$currentMode
can be developer
or production
or default
.