Home > Mobile >  PHP allow_url_include alternative for Wordpress Plugin
PHP allow_url_include alternative for Wordpress Plugin

Time:08-19

I'm on a XAMPP for Windows 8.0.3 installation, developing a payments gateway plugin for my ecommerce site made via Wordpress. I moved some of my code to an includes directory, and then used require_once plugins_url('/includes/class-wc-payment-gateway-elavon.php', __FILE__ ); to require the file from my includes directory.

In my website, I'm now receiving a fatal error, telling me "Failed to open stream: no suitable wrapper could be found" on that line that I just mentioned. It also gives me a warning which states "require_once(): https:// wrapper is disabled in the server configuration by allow_url_include=0", which to me means that the method to fix this error would be to change allow_url_include to yes in my php.ini file. To my understanding, it's bad practice to have allow_url_include set to YES in your php.ini file, as it poses security risks. Also, in Wordpress by default, the function "plugins_url" retrieves a URL within the plugins or mu-plugins directory, which is the directory where my plugin resides. Here is a reference to the function in the developer documentation for Wordpress: https://developer.wordpress.org/reference/functions/plugins_url/

So, my questions are as follows. Why is my file failing to be retrieved with this method? Why would it mention that the https:// wrapper is disabled in the server configuration if I'm trying to access a file locally? Is there a better way to require this include than the method that I am using? I'm relatively new to PHP and coding as a whole, so I'd appreciate if you are verbose, or point me to other resources I may use to learn. Thank you for any responses or help.

CodePudding user response:

The reason that your code doesn't work with plugins_url is because that returns a URL such as https://www.example.com/wp-content/plugins/your-plugin/includes/class-wc-payment-gateway-elavon.php which will be executed on the server as PHP and the result of that execution return, not the code itself.

My recommendation is in your main plugin entry file do something like this:

define('MY_AWESOME_PLUGIN_PATH', __DIR__);

Replace that constant name as you see fit.

Then, whenever you need to include something you can just use:

require_once MY_AWESOME_PLUGIN_PATH . '/includes/class-wc-payment-gateway-elavon.php';

In the longer run, if you have more classes you might want to explore using an autoloader instead.

  • Related