Debugging Drupal

October 31, 2011

My least favourite part of developing is trying to fix other people’s bugs. Most of the time the code isn’t properly commented, isn’t nicely formatted, and it often isn’t even clear what is supposed to happen. Here are a few things that can sometimes help. As well as the indispensable Devel module, PHP’s native magic constants can be a real help. Here is an example:

<?php

$vars = array(
  '@file' => __FILE__,
  '@line' => __LINE__,
  '@function' => __FUNCTION__,
);

watchdog('Malcolm debug', 'debug statement from @function : @file  @line', $vars, WATCHDOG_DEBUG);

Drupal’s permissions system can be really useful, but on a complex site it can be confusing trying to figure out just why permission has been denied, and it’s often a pain to find out which permission is relevant. This hack to the user_access function in Drupal 6’s user.module helps ease that pain:

<?php

if (!isset($perm[$account->uid][$string])) {
  watchdog('user', 'Access denied: @user does not have @perm permission', array('@user' => $account->name, '@perm' => $string), WATCHDOG_DEBUG);
  dsm('Access denied ' . $string);
}

You will end up with a lot of these debug statements, and it might take you an insanely long time to wade through them and figure out what’s relevant, but somewhere in there might be the answer. Needless to say, don’t do this on a production site… Here are some useful resources I’ve found:

debugging Drupal