Run PHP script using drupal bootstarp on drupal site | Drupal 8

Run PHP script using drupal bootstarp on drupal site

Submitted by editor on Fri, 10/11/2019 - 14:20
Question

How to run a php script to execute actions on a drupal site ?

This is usefull if you want to do some actions just one time.

The drush comman is php-script alias src

On drupal 8 with drush

Example :
drush --uri=drupal.loc scr /modules/custom/mymodule/scripts/test-script.php

Example:
<?php
$nid = 10;
$node = \Drupal\node\Entity\Node::load($nid);
$node->setTitle('The new Title')
$node->save();

 

On drupal 7 without drush command

1. put the script to the drupal root folder.
2. run using 'php cli'

Example:
php cli test-script.php [NID]

Example:
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Delete a node
$nodeId = 10;
echo "\r\nNode ID = $nodeId";
node_delete($nodeId);
echo "\r\n";
echo "\r\n";

 

Example 2

<?php
define('DRUPAL_ROOT', getcwd());
$_SERVER['SCRIPT_NAME'] = '/script.php';
$_SERVER['SCRIPT_FILENAME'] = '/path/to/this/script.php';
$_SERVER['HTTP_HOST'] = 'domain.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'POST';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
// Delete a node
$nodeId = $argv[1];
echo "\r\nNode ID = $nodeId";
node_delete($nodeId);
echo "\r\n";
echo "\r\n";

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.