Magento2 – Fix RuntimeException When Calling Custom File on Root

custommagento2server-setup

I'm calling Magento 2 Outside Magento using below ones

How can I bootstrap Magento 2 in a test.php script?

My URL abc.com/test.php in 'test.php` it contains code.

It gives below error

Fatal error: Uncaught RuntimeException: The specified "/var/www/html/magento/var/generation/Magento/Customer/Model/CustomerFactory.php.10709" file could not be written Warning!file_put_contents(/var/www/html/magento/var/generation/Magento/Customer/Model/CustomerFactory.php.10709): failed to open stream: Permission denied in /var/www/html/magento/vendor/magento/framework/Code/Generator.php:115 Stack trace: #0 /var/www/html/magento/vendor/magento/framework/Code/Generator/Autoloader.php(35): Magento\Framework\Code\Generator->generateClass('Magento\Custome…') #1 [internal function]: Magento\Framework\Code\Generator\Autoloader->load('Magento\Custome…') #2 [internal function]: spl_autoload_call('Magento\Custome…') #3 /var/www/html/magento/vendor/magento/framework/ObjectManager/Relations/Runtime.php(38): class_exists('Magento\Custome…') #4 /var/www/html/magento/vendor/magento/framework/Interception/Config/Config.php(153): Magento\Framework\ObjectManager\Relations\Runtime->has('Magento\Custome…') #5 /var/www/html/m in /var/www/html/magento/vendor/magento/framework/Code/Generator.php on line 115

Before this line it works fine

$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');

After this line it gives error.

Best Answer

No permission change is required. Instead you need to add a line at the beginning of this script. The revised code is below :

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$storeManager = $obj->get('Magento\Store\Model\StoreManagerInterface')->getStore()->getId();
Related Topic