Drupal Command Line Script Template
There are development tasks better suited to running in a command-line script than in the Drupal web interface. The two most notable in my experience are code fragment testing, especially when exploring how an API works, and data import/export. Happily, this kind of scripting is possible with Drupal.
$stdout = fopen('php://stdout', 'w');
fwrite($stdout, "Script Template\n");
// Site specific variables
$username = "Dale";
$drupal_base_url = parse_url('http://www.example.com');
$_SERVER['HTTP_HOST'] = $drupal_base_url['host'];
$_SERVER['PHP_SELF'] = $drupal_base_url['path'].'/index.php';
$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'] = $_SERVER['PHP_SELF'];
$_SERVER['REMOTE_ADDR'] = NULL;
$_SERVER['REQUEST_METHOD'] = NULL;
$user = user_load(array('name' => $username));
// Drupal code here
- I strongly recommend using this only in a development environment and not on a production site.
- Change the site specific variables $drupal_base_url and $username to values appropriate to your site.
- The template code, as shown, must go in a file in the Drupal root directory. It can be moved as long as you set the working directory to the Drupal root directory (See drush module for examples).
- If you want to output to your command line console before Drupal bootstrap, use fopen/fwrite, not echo or print. This avoids the warning: "Warning: Cannot modify header information - headers already sent". An example is provided in the script.
For those of you who might not be familiar with the Drupal Shell, or drush module, check it out before creating anything too fancy.
Running the Script
To run a script from the command line you need PHP configured to do so. Describing how to do so is outside the scope of this post. At the time of writing, the following Google search gave good results for "how to" references: Google Search: php command line. Some packages, such as XAMMP for Windows, set this up for you.
To quickly see if PHP is configured issue the command: php –v
You'll see the PHP version number if PHP is configured and an error if it isn't. It's also good to check which version of PHP is configured by default if your host or configuration supports multiple versions.
Running the script is as simple as: php my_script_name.php
For more information on PHP command line options, check out: PHP.net: Using PHP from the command line.
I'd like to acknowledge the authors of the following posts for their initial examples: