How run custom php file in Magento 2

You may happen to run a custom php file placing inside a Magento 2 instance to and read data from Magento 2 database. This article explains all the necessary steps you should follow to get it done properly. This will contain guide to do this on nginx web server only.

Configure Nginx allowing to run custom files

If you look at the nginx.conf.sample file located in the document root directory you will find this section around 180 line.

# PHP entry point for main application
location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check)\.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    fastcgi_buffers 1024 4k;

    fastcgi_param  PHP_FLAG  "session.auto_start=off \n suhosin.session.cryptua=off";
    fastcgi_param  PHP_VALUE "memory_limit=756M \n max_execution_time=18000";
    fastcgi_read_timeout 600s;
    fastcgi_connect_timeout 600s;

    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;

Considering your file is DOCUMENT_ROOT/pub/test.php, please add test at the end of the file list mentioned in this code. After the modification, the file list should look like bellow

location ~ ^/(index|get|static|errors/report|errors/404|errors/503|health_check|test)\.php$ {

Nginx server has to be re-started in order to apply these changes applied to nginx.conf.sample file. Bellow command will do that in ubuntu environment.

sudo /etc/init.d/nginx restart

Use bootstrap to instantiate ObjectManager

In order to run a custom php file in Magento 2, it has to be placed under pub directory. Let’s go ahead and create a test.php file inside DOCUMENT_ROOT/pub/ directory. And bellow code will read the product with entity_id 1 and print the object data to the browser.

require_once ("../app/bootstrap.php");
$params = $_SERVER;

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');

$productId = 1;
$product = $objectManager->get('Magento\Catalog\Model\ProductRepository')

echo '<pre>';
echo '</pre>';

Now, this file can be access through browser using BASE_URL/test.php URL.