PHP
PHP snippets execute server-side code during Joomla's page generation cycle, before any HTML is sent to the browser. They are suited for tasks that require access to Joomla's internals: setting up custom redirects, querying the database, modifying how Joomla behaves on specific pages, integrating with external APIs, or running any logic that must happen on the server rather than in the browser.
How to Create a PHP Snippet
To learn how to run a custom PHP snippet in Joomla, follow the steps below:
- Log in to your Joomla administrator
- Go to Components → Tassos Code Snippets
- Click New
- Enter a descriptive Title (e.g. "Redirect Non-Logged-In Users")
- Select PHP as the Code Type.
- Choose the Insertion Method
- To auto-insert the snippet to a predefined location, select Auto-Insert.
- To run the snippet manually via a shortcode, select Shortcode.
- When using Auto-Insert, unlike other snippet types, PHP snippets do not use layout positions like Header or Footer. Instead, they have the following locations:
- On Page Load: The snippet runs automatically during the
onAfterRouteJoomla event, the earliest point in the page lifecycle when routing and component information is available. This is the default and covers most use cases. - On Demand: Coming Soon
- Via a Webhook: Coming Soon
- On Page Load: The snippet runs automatically during the
- When using the Shortcode insertion method, place
{tcs snippet.alias}anywhere Joomla processes content — in articles, modules, or component output. - Write your code in the editor without including the opening
<?phpor closing?>tags. - Open the Conditional Logic tab to restrict which pages or users the snippet runs on. Leave it empty to run it site-wide. Learn more in Using Snippet Logic.
- Set Status to Published and click Save & Close.
Example
By default your code runs at the onAfterRoute event. To execute code at a different point in the page lifecycle, register an event callback using Joomla's Factory class:
use Joomla\CMS\Factory;
$app = Factory::getApplication();
$app->registerEvent('EVENT_NAME', function()
{
// your code here
});
For example, to hook into onUserAfterSave:
use Joomla\CMS\Factory;
$app = Factory::getApplication();
$app->registerEvent('onUserAfterSave', function($user)
{
// $user contains the saved user data
});
Or to modify the full HTML output of the page via onAfterRender:
use Joomla\CMS\Factory;
$app = Factory::getApplication();
$app->registerEvent('onAfterRender', function() use ($app)
{
$body = $app->getBody();
$body = str_replace('search-text', 'replace-text', $body);
$app->setBody($body);
});
You can register multiple event callbacks within a single PHP snippet, each responding to different lifecycle events. See the official Joomla Plugin Events documentation for a complete list of available events.
Automatic Error Protection
PHP snippets include built-in safety mechanisms to protect your site from errors. If your PHP snippet throws an error or exception during execution, the snippet will be automatically unpublished to prevent it from breaking your site on subsequent page loads.
When an error occurs, you'll receive a detailed error message containing:
- The specific error message that was triggered
- A complete stack trace showing where the error occurred
- A warning notification stating that the snippet has been disabled to protect your site
This automatic disable feature ensures that a single problematic snippet won't take down your entire website. Once you see the error notification, you can:
- Go to the backend (Components → Tassos Code Snippets)
- Review the error message and stack trace to identify the issue
- Edit the snippet to fix the problem
- Re-enable the snippet by publishing it again
This safety mechanism gives you confidence to experiment with PHP code, knowing that errors won't cause cascading failures across your site.
Accessing Shortcode Attributes In Your Snippet as Variables
If you are writing a PHP snippet you can access the shortcode attributes as PHP variables based on the name of the attribute you added to your shortcode. For example, if your attribute is named "name" you can access that attribute in PHP as $name.
Basic Example
Given this shortcode:
{tcs snippet.my-php --name=Tassos}
You can use $name directly in your PHP snippet:
echo 'Hello, ' . $name;
// Output: Hello, Tassos
Multiple Attributes
You can pass as many attributes as you need:
{tcs snippet.greeting --name=Tassos --color=blue --age=40}
All attributes become available as variables:
echo $name; // Tassos
echo $color; // blue
echo $age; // 40
Best Practices
Always Check Document Type
This is extremely important: Unlike other snippet types (HTML, CSS, JS) which automatically run only when the document type equals HTML, PHP snippets do not perform this check automatically. This means PHP snippets can execute on:
- Regular HTML page requests
- AJAX requests
- XML feeds
- JSON API responses
- Raw responses
- Any other document type
Without proper document type checking, your PHP snippet can inadvertently break:
- Extensions that rely on AJAX functionality
- API endpoints that return JSON data
- RSS/XML feeds
- Third-party integrations
- Component AJAX handlers
How to Check Document Type
In most cases, your PHP code should only run on standard HTML page requests. To ensure this, you must explicitly check the document type in your code.
Without document type check (runs on every request type):
use Joomla\CMS\Factory;
$app = Factory::getApplication();
$app->registerEvent('onAfterRender', function() use ($app)
{
$body = $app->getBody();
$body = str_replace('foo', 'bar', $body);
$app->setBody($body);
});
With document type check (runs only on HTML pages):
use Joomla\CMS\Factory;
$app = Factory::getApplication();
$doc = $app->getDocument();
$app->registerEvent('onAfterRender', function() use ($app, $doc)
{
// Only run on HTML page requests
if ($doc->getType() !== 'html')
{
return;
}
$body = $app->getBody();
$body = str_replace('foo', 'bar', $body);
$app->setBody($body);
});
Common document types in Joomla:
html— Standard web pagesjson— JSON API responsesraw— Raw output (often used by AJAX)xml— XML feedsfeed— RSS/Atom feeds
Always include this document type check unless you specifically need your code to run on non-HTML requests.
Using Joomla Objects
PHP snippets support use namespace imports, so you can access Joomla classes directly. Here are the most commonly used objects:
use Joomla\CMS\Factory;
// Application object
$app = Factory::getApplication();
// Document object
$doc = $app->getDocument();
// Database object
$db = Factory::getDbo();
// Current user object
$user = $app->getIdentity();
You can also import any other Joomla or third-party namespace class at the top of your snippet:
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Language\Text;
$app = Factory::getApplication();
echo Uri::root();
echo Text::_('COM_CONTENT_READ_MORE');
Reusing Code Across Snippets
Because all PHP snippets execute in the same PHP request, anything declared in one snippet — functions, variables, or classes — is available to every other snippet that runs after it. This is a powerful pattern for abstracting shared logic into a single place and reusing it across multiple snippets.
The most reliable way to share code is to define a static class in one snippet and call its methods from any other snippet.
Snippet A — declare the shared helper class (e.g. site-helpers, set to auto-insert on Page Load):
class SiteHelpers
{
public static function getCurrentUserName()
{
use Joomla\CMS\Factory;
$user = Factory::getApplication()->getIdentity();
return $user->name ?: 'Guest';
}
public static function isLoggedIn()
{
use Joomla\CMS\Factory;
return !Factory::getApplication()->getIdentity()->guest;
}
}
Snippet B — use the helper:
if (SiteHelpers::isLoggedIn())
{
echo 'Welcome, ' . SiteHelpers::getCurrentUserName();
}
Snippet C — use the same helper:
if (!SiteHelpers::isLoggedIn())
{
use Joomla\CMS\Router\Route;
$app = Factory::getApplication();
$app->redirect(Route::_('index.php?option=com_users&view=login'));
}
Security Considerations
For security reasons, PHP snippets automatically block certain dangerous PHP functions. If your code contains any of these functions, the snippet will not execute:
Blocked functions:
fopen,popen— File operationsunlink,rmdir— Delete operationsdl— Load extensionsescapeshellarg,escapeshellcmd— Shell escapingexec,passthru,shell_exec,system— Command executionproc_close,proc_open,pcntl_exec— Process controlsymlink— Create symbolic linkseval,create_function— Dynamic code execution- Backticks (
`) — Shell command execution
Note: curl_exec() is allowed for making HTTP requests to external APIs.
If you need functionality that requires these functions, consider:
- Using Joomla's built-in APIs (e.g.
JFile,JFolderfor file operations) - Using
JHttporcurl_exec()for external requests - Restructuring your code to use safe alternatives
Troubleshooting
PHP Snippet Not Executing
- Check event hook: Ensure you're using the correct event for your needs
- Check conditions: Verify conditional logic isn't preventing execution
- Look for errors: Enable error reporting and check error logs
- Test isolation: Temporarily remove other snippets to identify conflicts
Learn more in Why Are My PHP Snippets Not Being Executed.
White Screen of Death
PHP errors can cause white screens:
- Enable error reporting in Joomla Global Configuration
- Check PHP error log (
error_logfile) - Add error handling to your snippet
- Unpublish the snippet via database if admin is inaccessible
Learn more in How to Debug PHP Errors.