Test PHP code before putting it in blocks

Last modified: July 29, 2009 - 16:34

Drupal provides a great deal of power and flexibility when using PHP code in blocks. Unfortunately, a stray character or a missing semicolon may break code. Drupal then attempts to evaluate this broken code on any requested page, the PHP interpreter chokes on it and aborts, and a whole site can become inaccessible.
Fortunately, there is a very simple solution. Instead of writing and testing code inside the Administer >> Site building >> Blocks page, go to Create content and create a new story or page node. Use PHP input format, write the code, and the Preview to debug your code. Once the code is working, copy and paste the code into the block.

Alternate methods include:

  • Create a block and set use the visibility section to restrict it to a single page until its functionality is confirmed

As of Drupal 6 the PHP input filter is a separate module. It is not available unless the optional PHP Filter module is enabled. It is considered bad coding style to have php code stored in the database for maintain and security reasons so after testing with the php filter the php code should go into a template file. (For example block-block-1.tpl.php)

Note: see http://drupal.org/node/166556 for suggestions on recovering from an inaccessible site caused by a block with bad PHP code in it.

 
 

Drupal is a registered trademark of Dries Buytaert.