Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include php file in drupal 7

I'm coding a form in Drupal 7, and I want to 'include' a php file that adds my DB connection variables to my code.

I've tested my code in several ways, and I'm sure that the 'include' makes me get a WSOD when I run Cron in my site.

I've Googled about this and I tried:

include("/sites/all/libraries/php/connection.inc");

include("./sites/all/libraries/php/connection.inc");

include"./sites/all/libraries/php/connection.inc";

I also tried the above with '.php' extension.

And my last try:

define('__ROOT__', dirname(dirname(__FILE__)));
include(__ROOT__.'/sites/all/libraries/php/connection.inc');

Sometimes I get a WSOD when trying to run Cron, and sometimes my page styles get broken when I submit a form.

What is the correct way to include a PHP file manually in Drupal? Note that I don't want to use the 'Drupal way' to do this or to use the webform module. I want to code it manually with PHP.

like image 399
donbuche Avatar asked Nov 29 '22 01:11

donbuche


1 Answers

The libraries directory should only be used to store files shipped as a library through the libraries module (see here https://drupal.org/project/libraries).

For both examples lets assume library.inc is our file and relative_path_to is the relative path based on the module directory to our library.inc file.

To just include a file you can use:

require(drupal_get_path('module', 'module_name') . '/relative_path_to/library.inc');

And to do it the Drupal way (https://api.drupal.org/api/drupal/includes!module.inc/function/module_load_include/7):

module_load_include('inc', 'module_name', '/relative_path_to/library');

Cheers, j

like image 104
2 revs Avatar answered Nov 30 '22 15:11

2 revs