In PHP 8.2 and later, libxml_set_external_entity_loader() lets you register your own function that decides how libxml loads external entities and DTDs.
Instead of letting libxml fetch files or URLs on its own, your callback receives the request and can block it, redirect it to a safe local file, or return nothing. Pass null to go back to the default loader.
Syntax
Call libxml_set_external_entity_loader() with the values you need. Start with this line.
Restores the default libxml loader and returns true.
Available as of PHP 8.2.0. The callback receives three arguments: the public ID (string or null), the system ID (the URL or path), and a context array. It should return a stream resource, a file path string, or null to refuse the request.
Required. A callable with the signature function(?string $public, string $system, array $context) that returns a resource, a string path, or null. Pass null to restore the default loader.
Return Value
Return Value
Description
bool
Returns true on success.
PHP Examples
Example 1 — Block Every External Entity
Register a loader that returns null so no external entity is ever loaded.
PHP
<?php
libxml_use_internal_errors(true);
$calls = 0;
libxml_set_external_entity_loader(function ($public, $system, $context) use (&$calls) {
$calls++;
return null;
});
$xml = '<?xml version="1.0"?>
<!DOCTYPE root [<!ENTITY data SYSTEM "secret.txt">]>
<root>&data;</root>';
$doc = new DOMDocument();
$doc->loadXML($xml, LIBXML_NOENT);
echo $calls > 0 ? "Loader was called: yes" : "Loader was called: no", PHP_EOL;
Output
Loader was called: yes
How It Works
The loader counts how many times libxml asks for an external entity and always returns null.
The XML defines an entity that points to secret. txt.
LIBXML_NOENT asks libxml to expand the entity, so it calls our loader.
Because the loader returns null, nothing from secret. txt is loaded.
Example 2 — Reset to the Default Loader
Pass null to remove your custom loader and use the built-in behavior again.