11

I wanted to add custom php script to magento2 root folder and run from the browser.I tried to add it in magento2 root folder but it redirects to 404 page.

I also tried to add it in pub folder but no success.

Also cleared cache and generation.

I am running magento2 on nginx server

2
  • Sounds strange. I created test.php script in magento2 root dir, then I just call it from browser http://%magento-base-url%/test.php and it's work. Commented Jan 14, 2016 at 11:07
  • I am running magento2 on nginx server Commented Jan 14, 2016 at 11:17

4 Answers 4

25

If you are using nginx configuration that comes with magento you need to put a file inside pub folder to allow access to it from the browser as pub is the document root of the vhost. Magento root dir is one level up.

Second of all default config for nginx allows only to access index.php, get.php, static.php, report.php, 404.php and 503.php files. Any other are not processed by the php. You can see this in line with location ~ (index|get|static|report|404|503)\.php$ { in nginx.conf.sample. If you are not using it check your config for similar rule.

To allow another file to be accessible from browser simple add another name after 503 or change entire brackets with location ~* \.php$ {

3
  • Do i need restart nginxafter change ?
    – Ravi Soni
    Commented May 8, 2018 at 17:58
  • Yes, any change to vhost requires at least reload.
    – Zefiryn
    Commented May 8, 2018 at 20:22
  • Thanks man its working Commented Jan 11, 2020 at 15:04
22

For example, to get a product name by the custom script

Example 1:

Create test.php at the root of Magento var/www/html/magento2/test.php

<?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');

$id = 1;
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load($id);

echo $product->getName();

You can run script test.php by

http://127.0.0.1/magento2/test.php

Example 2:

Step 1: create index.php at the root of Magento 2

var/www/html/magento2/test/index.php

<?php
require __DIR__ . '/../../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication('customScript');
$bootstrap->run($app);

Step 2: create customScript.php

/var/www/html/magento2/test/customScript.php

<?php
class customScript
    extends \Magento\Framework\App\Http
    implements \Magento\Framework\AppInterface {
    public function launch()
    {
        $this->_state->setAreaCode('frontend'); //Set area code 'frontend' or 'adminhtml
        $id = 12;
        $_product = $this->_objectManager->create('\Magento\Catalog\Model\Product')->load($id);
        
        echo $_product->getName();

        return $this->_response;
    }
 
    public function catchException(\Magento\Framework\App\Bootstrap $bootstrap, \Exception $exception)
    {
        return false;
    }
 
}

Now you can run this custom script by

http://127.0.0.1/magento2/test/

enter image description here

10
  • 1
    I got an error 'class customScript not found' so I added 'require './customScript.php' before '$app = $bootstrap->createApplication('customScript');' and that worked.
    – Zankar
    Commented May 7, 2018 at 9:58
  • I'm getting page not found error
    – Ravi Soni
    Commented May 8, 2018 at 18:06
  • 1
    @ravisoni, that means you did something wrong. Make sure to create folder /test/ and two files index.php and other one customScript.php
    – electroid
    Commented May 9, 2018 at 7:13
  • 1
    @Zankar, you need to place your customScript.php file in the same folder (subfolder from sitedir) as index.php file. From your code ./customScript.php I can see that your customScript.php is one level up from index.php
    – electroid
    Commented May 9, 2018 at 7:16
  • @electroid in my case the customScript.php file is in the same directory as index.php. If I was including it from a folder one level up I would do ../customScript.php (note the two dots)
    – Zankar
    Commented May 9, 2018 at 9:48
6

If you want to allow more than one php script to be executable like I need (import.php for ERP import product, stock.php for update the inventory with my ERP etc...) :

  • create a new directory scripts in the /pub folder
  • edit your magento vhost and add lines under ##Allow pub/srcipts/ folder to execute php custom

     listen 80;
     server_name example.com www.example.com;

     set $MAGE_ROOT /var/www/html/magento2;
     include /var/www/html/magento2/nginx.conf.sample;

     ## Allow pub/srcipts/ folder to execute php custom
     location /scripts/ {
        location ~* \.php$ {
                try_files $uri =404;
                fastcgi_pass   fastcgi_backend;
                fastcgi_buffers 1024 4k;

                fastcgi_read_timeout 600s;
                fastcgi_connect_timeout 600s;

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

With this you can now run your scripts by accessing them at :

http://www.example.com/scripts/your_custom_code.php
1
  • Very helpful. Thank you.
    – ItsJhonny
    Commented Jan 22, 2020 at 13:32
0

Simple Step to follow

<?php
    use Magento\Framework\App\Bootstrap;   
    use Magento\Framework\App\ObjectManager;

   // Include Magento Bootstrap file
      require __DIR__ . '/../app/bootstrap.php';

  // Initialize the Magento application
     $bootstrap = Bootstrap::create(BP, $_SERVER);
     $objectManager = $bootstrap->getObjectManager();
     $state = $objectManager->get('Magento\Framework\App\State');
     $state->setAreaCode('frontend');

   // Retrieve the product repository
      $productRepository = $objectManager - 
           >get('\Magento\Catalog\Model\ProductRepository');

  // Replace 'your_sku' with the SKU of the product you want to retrieve
     $sku = 'your product sku';

 try {
   // Load the product by SKU
  $product = $productRepository->get($sku);

// Display product details
echo "Product ID: " . $product->getId() . "<br>";
echo "Name: " . $product->getName() . "<br>";
echo "SKU: " . $product->getSku() . "<br>";
echo "Price: " . $product->getPrice() . "<br>";
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
echo "No product found with SKU: $sku";
}

/* *

  • File location = inside the pub directory i.e = /opt/homebrew/var/www/local/pub
  • To Run on Terminal = cd /opt/homebrew/var/www/local/pub
  •                = php Test.php
    
  • To Run on Frontend = http://magento.local/Test.php

*/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.