In this tutorial, we will see how to create a custom root script in our Magento 2 and use it to perform Magento 2 specific operations.
For this create a file inside the Magento root directory with some unique name based on the activity you are going to perform, suppose you want to get a customer’s email by id then name it like getCustomerEmailById.php
You can use Object Manager in the custom script to get objects of specific classes.
Here is an example of a custom root script, which is used to fetch customer email from a given customer ID.
Example :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php //to display errors ini_set('display_errors', 1); ini_set('display_startup_errors', 1); ini_set('memory_limit', '5G'); error_reporting(E_ALL); //use Magento\Framework\App\Bootstrap; use Magento\Framework\App\Bootstrap; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); // Instance of object manager $objectManager = $bootstrap->getObjectManager(); // Set the state $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); /* Example to get customer by ID */ $id = 1; //customer id $customerRepository = $objectManager->get('Magento\Customer\Api\CustomerRepositoryInterface'); $customer = $customerRepository->getById($id); if ($customer) { echo "Customer Email : ".$customer->getEmail(); } else { echo "customer doesn't exists!"; } |
After creating this file, Now you can call it using PHP in the terminal by specifying the file name as below.
1 |
php getCustomerEmailById.php |
It will print customer email if exists.