How will you add custom PHP codes in Drupal pages or blocks?

Be default, Drupal doesn’t allow the insertion of PHP codes in its pages. To embed PHP codes, you need to activate a Drupal module called PHP filter. By default, this module remains disabled.

In Drupal, it’s generally discouraged to add custom PHP code directly into pages or blocks due to security and maintainability concerns. Instead, you should utilize Drupal’s theming system, preprocess functions, or custom modules to achieve the desired functionality. Here’s how you can do it:

  1. Theming System: You can create custom theme templates (.tpl.php files) for your pages or blocks and add your PHP logic within those templates. However, it’s important to separate the PHP logic from HTML markup as much as possible for better maintainability.
  2. Preprocess Functions: Drupal provides preprocess functions that allow you to alter variables before they’re rendered in a theme template. You can use preprocess functions to inject custom PHP logic into your pages or blocks. These functions are typically implemented in your theme’s template.php file.
  3. Custom Modules: If the functionality you’re implementing is complex or reusable, it’s best to create a custom module. Within a custom module, you can define hooks to alter or add content, implement custom controllers, or create custom blocks with PHP logic encapsulated within them.

For example, to add custom PHP code within a block:

  • Create a custom module.
  • Implement hook_block_info() to define the block.
  • Implement hook_block_view() to specify the content of the block, including any PHP logic required.

Here’s a basic example:

php
/**
* Implements hook_block_info().
*/

function mymodule_block_info() {
$blocks['my_custom_block'] = array(
'info' => t('My Custom Block'),
);
return $blocks;
}

/**
* Implements hook_block_view().
*/

function mymodule_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'my_custom_block':
$block['subject'] = t('My Custom Block');
$block['content'] = mymodule_custom_function();
break;
}
return $block;
}

/**
* Custom function with PHP logic.
*/

function mymodule_custom_function() {
// Your PHP logic here.
$output = 'This is my custom block content.';
return $output;
}

Remember to always consider security best practices when adding custom PHP code, such as sanitizing user inputs and using Drupal’s APIs instead of raw SQL queries.