0

How do we include_once an external (outside of Magento 2 code but on the same web server) PHP file?

I added the events.xml and adminuserlogin.php files below, into an already activated and fucntioning admin module, but my attempts to have the Observer call/include the PHP file does nothing. Do you see anything wrong with the code?

The module folder structures and the code are as follows:

/home/abc/public_html/app/code/abcCo/Backend/etc/adminhtml/events.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

    xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
        <event name="backend_auth_user_login_success">
            <observer name="backend_activity" instance="abcCo\Backend\Observer\adminuserlogin" />
        </event>
    </config>

/home/abc/public_html/app/code/abcCo/Backend/Observer/adminuserlogin.php:

<?php

namespace abcCo\Backend\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;

class adminuserlogin implements ObserverInterface
{
   public function __construct() 
{ 
    //Observer initialization code...
    //You can use dependency injection to get any class this observer may need.
    }

public function execute(\Magento\Framework\Event\Observer $observer)
    {
       // execute an external php script when I log in.

include_once '/home/abc/public_html/app/code/abcCo/testModule/Controller/Index/login_test.php';

    } 
} 

?>

Thank you.

0

This is not tested

<?php

namespace abcCo\Backend\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
//location is determined whether you use <working_root>/index.php or <working_root>/pub/index.php if pub/index.php you'll want to use  ../app/code/... in require_once funct.
require_once(__DIR__ .'app/code/abcCo/testModule/Controller/Index/login_test.php');
class adminuserlogin implements ObserverInterface
{
    public function __construct() 
    { 
     //Observer initialization code...
     //You can use dependency injection to get any class this observer may need.
    }

     public function execute(\Magento\Framework\Event\Observer $observer)
    {
     // use login_test.php functions here. 
    } 
} 

?>

Now that being said, you probably should just create a helper class that provides the functionality in the included file.

Here's something for reference: Custom helper in custom module in Magento 2 about helper classes.

  • Thanks for replying. The added code did not work, even with some variations that I made to it. I'll give the custom helper a look as you suggested. – Krang Jul 16 '18 at 16:53
  • Yeah thats a better direction, I hope it works out for you. – Chris Anderson Jul 16 '18 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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