How to Create a Custom PHP Script on Root Directory of Magento 2
A PHP script is a great way to insert one-time data into the system. As a Magento 2 developer, you often need to run such a script to manipulate data into your Magento 2 database. Today we will see how we can create a custom PHP script on the root directory of Magento 2 and run it.
Create a Custom PHP Script on Root Directory of Magento 2
Create customer.php
file under root directory of Magento 2 and add below code. You can give any name to your file but make sure you delete the file once your job is done.
<?php 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; require 'app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $objectManager = $bootstrap->getObjectManager(); $state = $objectManager->get('Magento\Framework\App\State'); $state->setAreaCode('frontend'); $storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface'); $storeId = $storeManager->getStore()->getId(); $websiteId = $storeManager->getStore($storeId)->getWebsiteId(); try { $customerModel = $objectManager->get('\Magento\Customer\Model\CustomerFactory')->create(); $customerModel->setWebsiteId($websiteId); $email = 'name@example.com'; $customerModel->setEmail($email); $customerModel->setGroupId(2); $customerModel->setFirstname($firstName); $customerModel->setLastname($lastName); $customerModel->setPassword($password); $customerModel->save(); echo 'Create customer successfully' . $customerModel->getId() . "<br>"; } catch (Exception $e) { echo $e->getMessage(); }
Here we have created a script to create a customer in Magento 2. Once your script is ready you can run it from the terminal using the PHP command.
php customer.php
Note: It is recommended to move your script under var directory and run it from terminal only. Because if you create it under the root directory then anyone can run it from the browser and that leads to unwanted database operation.
Conclusion
To run a PHP script on the root directory of Magento 2 is easy. It is advisable to create a custom Magento 2 console command for repetitive operation instead of creating a custom PHP script.
Leave a Comment
(0 Comments)
Useful Magento 2 Articles
Author Info
Chirag
Connect With Me