Skip to content

Instantly share code, notes, and snippets.

@vensires
Created December 7, 2017 09:34
Show Gist options
  • Save vensires/483357751b014b0fcdbaa88407e0092c to your computer and use it in GitHub Desktop.
Save vensires/483357751b014b0fcdbaa88407e0092c to your computer and use it in GitHub Desktop.
For anyone trying to use Drupal code in command line and having issues, use the following code as an example. When using Drupal in CLI, a warning about "Undefined index: REMOTE_ADDR" will appear for bootstrap.inc file. The following code fixes this.
<?php
/**
* @file
* The following code is retrieved from a comment in drupal.org/forum with
* minor modifications, mostly in comments.
*
* @see https://www.drupal.org/forum/support/module-development-and-code-questions/2010-12-29/drupal-7-and-bootstrapinc-problem#comment-4327272
*/
$uid = 1;
// Prevent this from running under Apache.
if (array_key_exists('REQUEST_METHOD', $_SERVER)) {
echo 'Nope. Not executing except from the command line.';
exit(1);
}
// Set HTTP_HOST or Drupal will refuse to bootstrap.
$_SERVER['HTTP_HOST'] = 'example.org';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
// Initialise Drupal.
define('DRUPAL_ROOT', getcwd());
include_once 'includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
/*
* The following code creates a new node.
* Feel free to use your own code below to achieve what
* you want. Since we have previously initialized
* Drupal with DRUPAL_BOOTSTRAP_FULL, every module you
* might have need of is available to you.
*/
$node = new stdClass();
$node->type = 'page';
$node->status = 1;
$node->uid = $uid;
$node->title = "I am the name";
$node->body['und'][0]['format'] = 'full_html';
$node->body['und'][0]['value'] = "I am the body";
$node->created = time();
$node->changed = $node->created;
$node->promote = 1;
$node->sticky = 0;
$node->format = 1;
$node->language = 'en';
node_save($node);
echo "Saved node: $node->nid\n";
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment