Question

I know that we can run php scripts by placing our script in root of magento 2 folder and we can load products, orders etc via object manager and perform our desired functionality. although this method a lot easier and quick too but its highly unsecure. Is there any secure way to run php scripts in Magento 2?

Was it helpful?

Solution

You can create a file called test.php in the root of my magento instance.

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

Then you can create a file called TestApp.php in the same place with this content.

<?php
class TestApp
    extends \Magento\Framework\App\Http
    implements \Magento\Framework\AppInterface {
    public function launch()
    {
        //dirty code goes here. 
        //the example below just prints a class name
        echo get_class($this->_objectManager->create('\Magento\Catalog\Model\Category'));
        //the method must end with this line
        return $this->_response;
    }

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

}

In luanch() method, you can write your code to check IP of client (like remote address) and only execute code if IP matches with your IP.

OTHER TIPS

One of the possible solution

With .htaccess it is very easy to password protect a file or folder or directory. The method is called htaccess password protection or htaccess authentication, and works by uploading two files called .htaccess and .htpasswd in the directory you want to password protect. The htaccess file should contain the following:

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /path/to/.htpasswd
Require valid-user

You only need to change /path/to/.htpasswd with the full path to your .htpasswd. Take a look at my article on how to find the full path using PHP. Next you need to upload the .htpasswd file which contains the username and password to enter the password protected folder. The .htpasswd file should contain:

test:dGRkPurkuWmW2

The above code will allow the user “test” to access the password protected area with the password “test”. The text “dGRkPurkuWmW2” is a encrypted version of the password. You will need to use a htpasswd generator to create another password. Each line in the .htpasswd file contains a username and password combination, so feel free to add as many combinations as you like.

I hope this will help

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top