Inserting and Using PHP in your Drupal Site's Content

Welcome to another tutorial in my How to Customize a Drupal Web Site series. Previous tutorials in this series include tips on smart searching for Drupal information, how to tell if a Drupal theme supports local modification, how and why you should be creating sub-themes, and how to make changes to a Drupal Theme. In this tutorial, I show how to insert and use PHP in your site’s content, as well as explain the PHP environment this capability provides.

Background
Drupal is a web site framework that dynamically generates each page as a user requests to view that page. Unlike a plain HTML web site, where an HTML file describes an unchanging page, Drupal uses logic written in PHP that is responsible for generating the HTML of a page. The reason for this indirection is to enable a Drupal web site to behave different depending upon the situation – such as provide different links, pages, and functionality to an administrator versus a casual web surfer.

Adding PHP to your content is very simple; that content can be a node, such as this article, or a block, such as the information found in a web site’s sidebars, header and footer. Perhaps because adding PHP to your content is so easy in Drupal, I will spend a bit more time covering why you might want to do this and the security implications involved.

Adding PHP Directly to Your Site’s Content
Adding PHP into your content is a capability built into Drupal, meaning no additional module download or installation is required. However, it has security implications, so by default the capability is turned off in a fresh Drupal installation. Essentially, you need to make sure that only specific user roles are allowed to insert PHP into nodes and blocks, otherwise the maturity challenged web surfing population will fill your site with porn, and malware that attacks future site visitors. If you are unfamiliar with the concepts of user roles and permissions, I suggest you visit the first two sections of my tutorial on creating pages only customers can see. Those first two sections explain user roles and how they are used to provide different sets of site permissions to different types of site visitors. It is very important that when enabling the insertion of PHP into your content, that ability is extended only to people you trust.

The first step to enabling PHP insertion is visiting the admin/build/modules page of your site. Although no additional module is needed, practically everything in Drupal is a module, and this is too. It is one of the core modules that make up Drupal itself. Once you have navigated your browser to the admin/build/modules, scan down to the Core – optional section and look for this:

Drupal's PHP filter module on the admin/build/modules page
Enabling the PHP filter module is the first step in activating PHP use in your content

Now, before you click that and jump out of this tutorial, there are more steps required as well as some essential information you need to understand about what this does and how you use what you’ve just enabled. You’ll notice the item you enable is called PHP filter. What this enables is the availability of an additional input filter when creating content. For people new to Drupal, the input filters are often a cause of confusion. Any time you are editing content, meaning you are editing a block or a node, beneath the content editing field is a collapsed fieldset labeled “Input format”. Expanding the “Input format” fieldset allows you to select a format for the content you are editing. Regardless of what format you select, everything you enter into the body field of your block or node is going to be saved to the database when you save that content. For example, let’s say you are creating a really simple node like this:

A real simple node using the wrong input filter
A simple node with the wrong input format selected

The content is a simple line of text, with an image. The input format is “Filtered HTML”, which actually does not allow use of the img tag. What happens when this is saved?

  1. The entire text is saved to the database, including the img tag, its contents, as well as the selected input filter;
  2. When viewing this node, the text is pulled from the database and the selected input filter is applied to the text before sending it to your browser for display.

In the above situation, because “Filtered HTML” does not allow the img tag, it will be removed on its way to the browser. This may seem counter-intuitive to many people. Because these are called “Input formats” and “Input filters”, you would think they are applied when content is entered, but they are not. Input filters are applied to content when it is output to the user’s browser.

It is essential that Drupal operate in this manner for this exact use situation: I wanted an image in my node, but I forgot so set the appropriate input format. Drupal has no idea what I actually intended, but happily takes my input and displays the final content according to the input format selected. Because I can view the new node and see that my image is missing, I easily realize that I forgot to set the input format to allow the img tag. To fix my error, all I have to do is navigate to the node's edit page, select the correct input format and re-save the node. If Drupal had removed the img tag because it was not allowed, I would have had to type the img tag in again, and most likely I’d be cursing Drupal for the wasted time of having to re-enter the same information twice.

What does this have to do with inserting PHP into your nodes? This explains what’s going on under the hood, and hopefully provides that additional understanding to you so Drupal’s handling of your content is less mysterious.

Okay, now that you know how your new blocks and nodes will be handling your content, the steps to add PHP directly into a node requires three steps. First, you enable the “PHP filter” module I showed you above. Next, you visit your admin/settings/filters page, and visit each one of the listed “Input formats” you would like to enable use of PHP insertion, and enable the “PHP Evaluator” option:

The PHP Evaluator option in each Input Filter's confguration page
You will need to edit each input filter in admin/setting/filters you want to be able to use PHP

Once you have enabled the PHP Evaluator for your Input filters, you can create blocks and nodes with PHP in them by simply surrounding any PHP with the traditional PHP tags, (making sure you’ve selected an Input format allowing PHP when editing the block or node):

Using PHP in a Drupal node
Use PHP tags to enclose PHP logic in your node (with an Input format allowing PHP)

That pretty much handles how to insert PHP into a block or node, so I’ll talk a bit about this environment, and quick and easy things that make sense to use this for, rather than writing your own module.

First off, any PHP you put into your content via this technique is maintained inside your web site’s database – meaning you would not a have a file with your code in it, unless you copy it there, and as such it is a bit of a pain to work with any amount of PHP logic beyond a few lines. There is also the issue of reading and writing data to your web site’s database. It’s fairly straight forward to both read and write pre-existing records using Drupal’s API, but there is no real good way for you to create user input forms without having to learn an amount of Drupal and the Drupal API. A method of creating user input forms in Drupal is to create a custom Content Type using widgets from the CCK (Content Construction Kit) module, and then creating a View or custom logic that processes users’ submitted forms into some form of output. (Hoever, creating forms is easier using Drupal's Form API in your own module.) You can access the complete Drupal API from this environment, but you quickly encounter the issue of wanting to use a proper code editor, or IDE (integrated development environment) as you create anything significant. Plus, it is really simple to create a module shell you can throw any amount of PHP into, which you then call from your content using this technique.

That is actually what I’d recommend for people without the time to properly learn Drupal’s API who are working on web projects with very tight deadlines. (I’m writing another tutorial covering this, but until that’s completed you can look at this comment thread on Drupal.org where I explain how to create just a module shell for this purpose: http://drupal.org/node/703828.)

This is not the best way to go, since you are more or less jury-rigging how your logic is going to work and appear within Drupal’s environment. However, if you are working with pre-existing information in the web site’s database, or are able to get your information from an online source, this can be quite an effective way of getting logic running in Drupal without learning a lot of the Drupal API. With a module shell, you can create functions you call from your node or block to generate arbitrary output. In your node, you only have a few calls to your larger logic in the module, and that larger logic is inside a file you are able to load into a proper code editor and work like a proper developer.

That pretty much covers what you need to know about inserting PHP into your nodes. If you are thinking about my previous mention of using the CCK module to create a user input form, and then something like what I describe above to be the output processing of this user collected data… do not waste your time pursing that angle. I’ve spent time investigating that option, actually learned a lot of my Drupal knowledge finally figuring out that such a technique is way more work than doing it the proper Drupal way with the Form API. And that tutorial should be ready very soon, so be sure to check back soon if you’re interested!

If you have any questions about this tutorial, would like to point out places where my descriptions are unclear, or you have any constructive suggestions for improving this tutorial, please write a comment. All constructive critism will be followed to the best of my ability.


Comments

Very clear tutorial, managed

Very clear tutorial, managed to get it working first time. Many thanks!

Tony.
- hp 6735s

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre>
  • Lines and paragraphs break automatically.
  • Syntax highlight code surrounded by the {syntaxhighlighter OPTIONS}...{/syntaxhighlighter} tags with the rich text editor turned off or set to source mode.

More information about formatting options