Drupal - How can I run PHP code without writing a module?

Yes, there is, but given your description I wonder if it will help you:

  1. Install module Devel
  2. Go to http://yoursite/devel/php
  3. Enter your code and execute it.

If you need to run code just once, you can do it without installing any module, including the Devel module.

Write a PHP file (e.g. tasks.php), put it where the cron.php file that comes with Drupal is, and add the following code.

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

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
drupal_set_time_limit(240);

// Your code here.

If you are already using Drush for maintaining/deploying your site, then you could make a Drush script. In this way, it could be executed by CLI, and it could receive any arguments, making it re-usable for many occasions.

#!/usr/bin/env drush

// Your code here.
// Access the options with drush_get_option(), or any argument with drush_shift().

You could also execute a PHP script with drush php-eval (or just drush ev), for example:

drush php-eval 'print time();'

I would create a Drush script, but if you cannot install Drush, or you need to execute PHP code from the browser, the first method works fine.


Add your code snippet to a file and save the file as file_name.php in your Drupal site root folder. Then run the following command in a terminal, from within the Drupal site root folder as your working directory:

drush scr file_name.php

This command will execute your PHP file. (To get an idea of the execution, you may include some print statements in your file, which will output the text, variable values etc. to the terminal where you execute the drush command.)

Note: As a prerequisite, you need to have drush installed on your system.

Tags:

7