Last updated April 8, 2012. Created by BozHogan on January 31, 2011.
Edited by shamio, authentictech. Log in to edit this page.
This article is for Drupal 7 developers who have tried to put PHP code in the body of a Custom Block, but can't get it to run. It assumes that you are logged in with administrative priveleges and are not yet advanced enough to be aware of the PHP filter Module ( Like me, when I first ran into this problem). It also assumes you know how to create a block and place it on your page, although you should be able to get through this without that knowledge.
To begin, create a custom Block by navigating to the Add Block page found at [your site]/admin/structure/block/add or on the Drupal 7 menu: Administration > Structure > Blocks > Add Block. After filling in the Block description and Block title, go ahead and put your PHP code in the Block body. You can mix text, HTML, and PHP code (sometimes called PHP snippets). Here is a simple example:
Hello
<p>Welcome!</p>
Today's date is:
<?php
echo date('m/d/Y');
?>After entering this, move down to the Text Format dropdown. This needs to be set to "PHP code". If this doesn't appear, just leave it at Filtered HTML. But realize that this is a problem we are going to have to fix. (If "PHP code" is an option on the Text Format dropdown, you should be all set and need not read any further. You have probably done what is necessary sometime in the past.)
Now, save your block, enable it by placing it on one of your theme's regions, and test it out. Most likely Drupal 7 will print out the PHP code instead of interpreting it, giving you an unexpected and ugly result.
Here is the critical fix and the point of this article:
Drupal 7 Core contains a module called "PHP filter". A fresh install of Drupal 7 has this module disabled by default. We need to enable it.
To do this, make sure you've saved your block and navigate to the Module Administration page. This is found at [your site]/admin/modules or on the Drupal 7 menu system: Administration > Modules. Scroll down to the PHP filter module and check the Enabled box. Press the Save Configuration button. At this point you should be all set, but hold on for just a second. Scroll back down to the PHP filter module again and notice that two links have been added. The first is "help". It's not long and worth reading, so check it out. The second new link is "permissions". Click on this to go to the Permissions page. Scroll down to the Filter section and notice that there is a new item called "Use the PHP code text format" and it's checkbox for the Administrator is not checked. The permission box must be checked for the role that needs to use PHP code in order for the PHP filter to show on input boxes.
(Note: User 1 automatically has all permissions including use of the PHP filter regardless whether permission is granted to any role.)
Important note: There are security considerations in enabling the PHP filter module. The PHP input filter introduces the possibility for malicious users to attack your website with malicious scripts. You should only grant permission to use the PHP filter to people you trust. Also, make sure those you grant permission to are competent PHP coders as malformed code can break your website and stop it functioning altogether. It is a good idea to create a separate role for this module (and other potentially dangerous ones) like 'developer' or 'webmaster', distinct from 'administrator' who may be a Drupal expert but not an expert coder, so you can grant it only to those who fulfill such criteria.
Anyway, back to the task at hand. Make sure you save your changes on the Permissions page, and navigate back to your Block's configuration page. (Administration > Structure > Blocks), then click on the "configure" link next to your block. Scroll down to the Text Format dropdown. You should now see a new option called "PHP code". Select it.
Remember to save your change and go test your block. It should now work as expected.
Have fun PHPing in your Blocks!
Comments
Thnks for this text. i got
Thnks for this text. i got idea how to use PHP code in content :)
Want to create a user registration block
I want to create a custom block (D7) for the 'user registration form'. What should be the php code for that?
The Php codes which worked in D6 are not working in D7
Thanks for the help
Thanks I was going crazy trying to figure out why the PHP code did not work.
php variables in blocks
Is there some documentation on available drupal php variables that can be used inside a block?
API variables
These are the API variables available on a page:
http://api.drupal.org/api/drupal/modules--system--page.tpl.php
Thanks--Saved Me a Hassle
Learning Drupal from a book.
Book says use "PHP code" but not an option.
Found this well written how to fix.
Thanks, now on with more Drupal.
Thank you
Thank you
Thanks
Thank you so much for your text
OMG its Awsome
Thanks for this.. Its really help me.
Not working for me
I've enabled the module and given my admin rol permission to use the PHP Filter but it's still not showing up in the block editing page. I've also cleared all my Drupal caches thinking that it might have something to do with that but no-go.
Had to add an input filter
I had to add a new input filter (Configuration>Content Authoring>Text Formats>Add Text Format) and tick the "PHP evaluator" option. I am on Drupal 7.10.
Nice write up
I have a quick question though. What would you do when you get a white screen from a php error?
How would you get it back to normal as I assume you wont be able to access the site?
Thanks
php code in basic page content
Hi
I have created a webform contact form and am trying to put it on my contact us page. But the code is not working.
I have php filters activated, and also the PHP text format. Other php codes I put in the contact us page works, but not the webform one. I have checked the webform button for display as block, created a region to put the webform block in, and am using the following code to call the block, inside the contact us content:
<?phpecho render($page['contactus']);
?>
This code works if I put it in any tpl.php file, but I only want it in one contact us page, not all the pages.
Any help would be appreciated.
Thanks
I have the option PHP under text formats (underneath the editor)
..but the moment I choose for -PHP code- in the dropdown menu, the hole editor disappears.. Wot to do?!
Thanks
Thanks for this guide. It really helps me.
THANK YOU
Thanks for simple & current info on enabling the PHP filter.
Not supported by Drupal Gardens
After reading the bolded section (well, I kind of assumed this anyway), I can see why Drupal Gardens doesn't not support PHP filter. Everything is locked down there.
Hiiii............
Hii am nw newbie to drupal and nw am using drupal7 .. this is nice snippet that we can insert into block bt can u tell me that we r also can put the php code related to database i. e can we fetch data from mysql database using php-mysql- normal connection.That i want to use in created contents body.
please if yes then give me example...
help will appreciated....
thanxxx..........
Facebook connect
Hello,
I used to make php blocks with your suggestions but since I have installe the module facebook connect It doesnot run really good ... do you know any possiblity that what is wrong?
Thanks and regards
help inserting php code on pa ge in drupal 7
Hi
I'm trying since many days to insert my php cod on a page on drupal usig php filter but i doesn't work.
I've enabled php filter inserted code both on a page or on a block with php filter and set up to be showed on a specific page by drupal but nothing happens.
I read on drupal pages that I have to use drupal snippets to correctly insert php code on drupal? is it right?
this is the cose I have to insert:
<?php
//error_reporting(E_ERROR);
/*** turn off error reporting ***/
//ini_set('display_errors', 0);
/*** turn on error logging ***/
//ini_set('log_errors', 1);
include 'DataProvider.php';
$pagina = filter_var($_SERVER['PHP_SELF'], FILTER_SANITIZE_STRING);
// Trim array values using this function "trim_value"
/*function trim_value(&$value)
{
$value = trim($value); // this removes whitespace and related characters from the beginning and end of the string
}
array_filter($_REQUEST, 'trim_value'); // the data in $_REQUEST is trimmed */
$_REQUEST['prov'] = isset($_REQUEST['prov']) ? trim($_REQUEST['prov']) : false;
if(!$_REQUEST['prov']) {
// primo giro
echo '<h1>Ricerca responsabile Area</h1>';
echo '<form name="ricercaAreaRespForm" method="post" action="'.$pagina .'">';
echo '<fieldset><legend>Scelta Provincia</legend><br /><ul>';
global $global;
$ORAData = new CDataProvider($global);
if (!$ORAData) {
//error_log("Classe CDataProvider NON istanziata\n",3,"/home1/storico_newweb/pietro/debug.log");
die("Impossibile connettersi al database");
}
global $ORAData; // VARIABILE DA CDATAPROVIDER
// QUERY
$result = $ORAData->getAllProvincia();
if ($result && is_array($result) && count($result)) {
$html = '<li><label for="prov">Provincia : </label>';
$html .= '<select name="prov" id="prov"><option></option>';
for ($i=0;$i<count($result);$i++)
{
$html .= '<option value="'.$result[$i]["ID_PROVINCIA"].'">'.$result[$i]["NOME"].'</option>';
}
$html .= '</select></li>';
}
echo $html;
echo '<label for="invia">';
echo '<button name="invia" id="invia" class="g-button blue">Ricerca »</button>';
echo '<br/><br/></ul></fieldset>';
echo '</form>';
exit;
} else {
// secondo giro
echo '<h1>Dettaglio Ufficio Territoriale di Governo</h1>';
echo '<br />';
global $global;
$ORAData = new CDataProvider($global);
if (!$ORAData) {
//error_log("Classe CDataProvider NON istanziata\n",3,"/home1/storico_newweb/pietro/debug.log");
die("Impossibile connettersi al database");
}
global $ORAData; // VARIABILE DA CDATAPROVIDER
// QUERY
// dati prefettura
$result = $ORAData->getPrefettura($_REQUEST['prov']);
if ($result && is_array($result) && count($result)) {
$html = '<h2>UTG di '.$result[0]["NOME"].'</h2><br />';
$html .= '<div class=\'outer\' style=\'min-width:500px\'>';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Indirizzo :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["INDIRIZZO"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>C.A.P. :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["CAP"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Telefono :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["PREFISSO"].' - '.$result[0]["TELEFONO"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Fax :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["PREFISSO"].' - '.$result[0]["FAX"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>E-mail :</span>';
$html .= ' <span class=\'text\'> <a title="Link all\' indirizzo e-mail." href="mailto:'.$result[0]["EMAIL"].'">'.$result[0]["EMAIL"].'</a></span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class="descr">Sito Web : </span>';
$html .= ' <span class=\'text\'> <a title="Link al Sito Web" href="'.$result[0]["SITO_WEB"].'">'.$result[0]["SITO_WEB"].'</a></span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Prefetto :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["COGNOME_PREFETTO"].' '.$result[0]["NOME_PREFETTO"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Data Ultimo Aggiornamento :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["DATA_AGGIORNAMENTO"].'</span>';
$html .= '</div><br />';
$html .= '</div><br />';
echo $html;
}
echo <<<EOT
<script type="text/javascript">
<!--
$.getDocWidth = function(){
return Math.max(
$(document).width(),
$(window).width(),
/* For opera: */
document.documentElement.clientWidth
);
};
$.getDocHeight = function(){
return Math.max(
$(document).height(),
$(window).height(),
/* For opera: */
document.documentElement.clientHeight
);
};
function f_scrollTop() {
return f_filterResults (
window.pageYOffset ? window.pageYOffset : 0,
document.documentElement ? document.documentElement.scrollTop : 0,
document.body ? document.body.scrollTop : 0
);
}
function f_filterResults(n_win, n_docel, n_body) {
var n_result = n_win ? n_win : 0;
if (n_docel && (!n_result || (n_result > n_docel)))
n_result = n_docel;
return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
function ShowDialog(refer)
{
var top = ($.getDocHeight() - $("#dialog"+refer).height()) /2;
var left = ($.getDocWidth() - $("#dialog"+refer).width()) /2;
//faccio apparire il box lightbox al centro dello schermo con effetto fadeIn impostabile
$("#overlay").show();
$("#dialog"+refer).css({"top":top+f_scrollTop(),"left":left}).fadeIn(300);
//$("#dialog"+refer).fadeIn(300);
$("#overlay").click(function (e)
{
HideDialog(refer);
});
$("#dialog"+refer).click(function (e)
{
HideDialog(refer);
});
}
function HideDialog(refer)
{
$("#overlay").hide();
$("#dialog"+refer).fadeOut(300);
}
//-->
</script>
EOT;
$result = $ORAData->getRespPrefettura($_REQUEST['prov']);
if ($result && is_array($result) && count($result)) {
echo '<div id="tabe" class="tabella">';
echo '<table cellpadding="2" style="min-width:500px">';
echo '<thead><tr><th>Area</th><th>Referente</th></tr></thead>';
echo '<tbody>';
echo '<tr>';
$codici_resp = array();
for ($i=0;$i<count($result);$i++)
{
$html = '<tr>';
$html .= '<th>'.$result[$i]["DESCRIZIONE"].'</th>';
$html .= '<td><a href="javascript:ShowDialog(\''.$result[$i]["ID_RESPONSABILE"].'\');" onkeypress="javascript:ShowDialog(\''.$result[$i]["ID_RESPONSABILE"].'\')" class="linkTitle" title="Si aprirà in un nuovo browser il dettaglio del referente selezionato." onclick="javascript:ShowDialog(\''.$result[$i]["ID_RESPONSABILE"].'\');">';
$html .= ' '.$result[$i]["COGNOME"].' '.$result[$i]["NOME"].' </a></td>';
$html .= '</tr>';
$codici_resp[] = $result[$i]["ID_RESPONSABILE"];
echo $html;
}
echo '</tbody></table>';
echo '</div><br /><br />';
echo '<div id="overlay" class="web_dialog_overlay"></div>';
for ($i=0;$i<count($codici_resp);$i++)
{
global $ORAData; // VARIABILE DA CDATAPROVIDER
// QUERY
// dati prefettura
$result = $ORAData->getDatiResp($codici_resp[$i]);
if ($result && is_array($result) && count($result)) {
$html = '<div id="dialog'.$result[0]["ID_RESPONSABILE"].'" class="web_dialog">';
$html .= '<div class="heading">Dettaglio del Referente';
$html .= '<a class="align_right" href="javascript:HideDialog('.$result[0]["ID_RESPONSABILE"].')" onkeypress="javascript:HideDialog('.$result[0]["ID_RESPONSABILE"].')" id="btnClose">Chiudi</a>';
$html .= '</div>';
$html .= '<div class="content"><p>';
$html .= '<div class=\'outer\' style=\'width:330px\'>';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Area :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["DESCRIZIONE"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Qualifica :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["QUALIFICA"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Nome :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["NOME"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Cognome :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["COGNOME"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Telefono :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["TELEFONO"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>Fax :</span>';
$html .= ' <span class=\'text\'> '.$result[0]["FAX"].'</span>';
$html .= '</div><br />';
$html .= '<div class=\'container\'><div class=\'filler\'></div>';
$html .= ' <span class=\'descr\'>E-mail :</span>';
$html .= ' <span class=\'text\'> <a title="Link all\' indirizzo e-mail." href="mailto:'.$result[0]["EMAIL"].'">'.$result[0]["EMAIL"].'</a></span>';
$html .= '</div><br />';
$html .= '</div><br />';
$html .= '</div></p></div>';
echo $html;
}
}
}
echo '<a title="Nuova ricerca" href="'. $pagina .'">Effettua una nuova ricerca</a>';
echo '</div>';
}
?>
Webdesign | Soundesign | http://www.francescogiannico.com
My case worked by making my
My case worked by making my own php-filter based on http://drupal.org/node/1046700#comment-5451466 and only checking PHP.
greetings, Martijn