Skip to content

libxml_set_external_entity_loader()

Today, we will discuss the libxml_set_external_entity_loader() function in PHP. This function registers a custom callback to handle external entities in XML documents, primarily to prevent XML External Entity (XXE) attacks.

What is libxml_set_external_entity_loader() Function?

The libxml_set_external_entity_loader() function is a built-in PHP function that registers a custom callback to intercept external entity loading in XML documents. Introduced in PHP 5.1.0, it is primarily used to secure XML parsing against XXE vulnerabilities. Note that PHP 8.0.0 updated the callback signature to include type hints and a return type, improving type safety and compatibility.

How to Use libxml_set_external_entity_loader() Function

The libxml_set_external_entity_loader() function is straightforward to use. You define a callback that receives the entity's public ID, system ID, and context, then return the entity content as a string or null to block loading.

Here is an example of how to use the libxml_set_external_entity_loader() function:

How to Use libxml_set_external_entity_loader() Function in PHP?

php
<?php
// Define a custom function to load external entities
function my_entity_loader(?string $publicId, ?string $systemId, ?array $context): ?string
{
  // Block loading if systemId is missing or invalid to prevent XXE/SSRF
  if ($systemId === null || !is_string($systemId)) {
    return null;
  }

  // Load the external entity safely
  $content = @file_get_contents($systemId);
  return $content !== false ? $content : null;
}

// Set the custom entity loader function
libxml_set_external_entity_loader('my_entity_loader');

// Load an XML file into a DOMDocument object
$doc = new DOMDocument();
$doc->load('example.xml');
?>

In this example, we define a PHP 8-compatible callback that validates the systemId and safely fetches the entity using file_get_contents(). Returning null tells libxml to skip loading the entity, which is the standard way to block potentially dangerous external resources. We then register the callback with libxml_set_external_entity_loader() and load the XML file.

Conclusion

The libxml_set_external_entity_loader() function is a critical tool for securing XML parsing in PHP. By intercepting external entity requests, developers can effectively mitigate XXE attacks and control resource access. This guide covered the function's purpose, PHP 8 signature requirements, and a secure implementation example.

Practice

What is the main purpose of the PHP libxml_set_external_entity_loader() function?

Dual-run preview — compare with live Symfony routes.