1
votes

I have placed my own php file in /sites/all/modules/<myfolder> and call it via $.post(<myphppage>) from a static html page (javascript function) also in /sites/all/modules/<myfolder>.

However, the php does not appear to be executing as expected, but is getting called (access logs in Apache HTTPD show it is post'ed to).

If I try to manually request the same php page, I receive this error:

Fatal error: Call to undefined function db_insert() in /full/path/to/sites/modules/<myfolder>/<myphppage> on line x.

The echo statement I have in the php page is outputted properly above this error, and simply uses $_GET['paramname']. (And _POST, changed for testing direct request) to print a few query string parameters for debugging).

Also, when I added a call to watchdog, I receive:

Fatal error: Call to undefined function watchdog() in /full/path/to/sites/modules/<myfolder>/<myphppage> on line x.

Is it not possible to access the PHP page directly? Or is there a Drupal library I need to import? Or am I just plain missing something else with how Drupal works?

1

1 Answers

1
votes

You are getting those errors about undefined functions because your PHP file is independent from Drupal and it is not bootstrapping it.

The Drupal way of doing what you are trying to do is to create a module (see Creating Drupal 7.x modules, and Creating Drupal 6.x modules) that defines a URL it handles with hook_menu(); that URL is then used with $.post().

As example of the way of bootstrapping Drupal, see the content of the index.php file that comes with every Drupal installation. (The following code is the one used from Drupal 7.)

/**
 * Root directory of Drupal installation.
 */
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

The code changes from Drupal 6 to Drupal 7, but drupal_bootstrap() is defined in both Drupal versions.

The correct way is to create a module, anyway. For a list of reasons why a module should use a PHP file that bootstraps Drupal, see Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php?