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:

  1. Log in to your Joomla administrator
  2. Go to Components → Tassos Code Snippets
  3. Click New
  4. Enter a descriptive Title (e.g. "Redirect Non-Logged-In Users")
  5. Select PHP as the Code Type.
  6. 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.
  7. 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 onAfterRoute Joomla 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
  8. When using the Shortcode insertion method, place {tcs snippet.alias} anywhere Joomla processes content — in articles, modules, or component output.
  9. Write your code in the editor without including the opening <?php or closing ?> tags.
  10. 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.
  11. 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:

  1. Go to the backend (Components → Tassos Code Snippets)
  2. Review the error message and stack trace to identify the issue
  3. Edit the snippet to fix the problem
  4. 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 pages
  • json — JSON API responses
  • raw — Raw output (often used by AJAX)
  • xml — XML feeds
  • feed — 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 operations
  • unlink, rmdir — Delete operations
  • dl — Load extensions
  • escapeshellarg, escapeshellcmd — Shell escaping
  • exec, passthru, shell_exec, system — Command execution
  • proc_close, proc_open, pcntl_exec — Process control
  • symlink — Create symbolic links
  • eval, 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:

  1. Using Joomla's built-in APIs (e.g. JFile, JFolder for file operations)
  2. Using JHttp or curl_exec() for external requests
  3. Restructuring your code to use safe alternatives

Troubleshooting

PHP Snippet Not Executing

  1. Check event hook: Ensure you're using the correct event for your needs
  2. Check conditions: Verify conditional logic isn't preventing execution
  3. Look for errors: Enable error reporting and check error logs
  4. 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:

  1. Enable error reporting in Joomla Global Configuration
  2. Check PHP error log (error_log file)
  3. Add error handling to your snippet
  4. Unpublish the snippet via database if admin is inaccessible

Learn more in How to Debug PHP Errors.

Last updated on Mar 3rd 2026 14:03