Prevent XXE in PHP (libxml)
To prevent XXE in PHP you mostly need to avoid re-enabling a danger that is off by default: since libxml 2.9.0, external entity substitution is disabled, so DOMDocument and SimpleXML are safe unless you explicitly pass LIBXML_NOENT or LIBXML_DTDLOAD when loading untrusted XML.
PHP's XML functions (DOMDocument, SimpleXML, XMLReader) are all built on libxml2. Since libxml 2.9.0 — bundled with PHP for many years — external entities are not substituted by default. The practical rule is: do not opt back in. The flags LIBXML_NOENT (despite the name, it enables entity substitution) and LIBXML_DTDLOAD are the usual cause of PHP XXE.
Secure parser configuration
DOMDocument (safe default)
$dom = new DOMDocument();
$dom->loadXML($untrusted); // safe on libxml 2.9+: no external entity substitution
// DANGEROUS — do NOT do this with untrusted input:
// $dom->loadXML($untrusted, LIBXML_NOENT | LIBXML_DTDLOAD);LIBXML_NOENT substitutes entities; LIBXML_DTDLOAD loads external DTDs. Both re-introduce XXE.
SimpleXML
$xml = simplexml_load_string($untrusted); // safe by default
// Avoid passing LIBXML_NOENT / LIBXML_DTDLOAD as the options argument.XMLReader
$reader = new XMLReader();
$reader->xml($untrusted);
// Do not call $reader->setParserProperty(XMLReader::SUBST_ENTITIES, true)
// and do not enable LOADDTD on untrusted input.Older PHP (< 8.0) defence in depth
// Deprecated in PHP 8.0 and unnecessary on modern libxml, but harmless as
// belt-and-braces on legacy stacks:
if (\PHP_VERSION_ID < 80000) {
libxml_disable_entity_loader(true);
}Do not rely on this alone; the real control is not passing LIBXML_NOENT/LIBXML_DTDLOAD.
Common pitfalls that re-introduce XXE
- Passing LIBXML_NOENT (its name misleads — it enables entity substitution).
- Passing LIBXML_DTDLOAD or LIBXML_DTDVALID on untrusted documents.
- Enabling XMLReader::SUBST_ENTITIES or LOADDTD properties.
- Running an ancient libxml (< 2.9) where external entities are on by default.
Verifying the fix
Send a classic file-read and a php://filter base64 payload; with safe defaults the entity is not substituted and &xxe; comes back empty or literal. Grep the codebase for LIBXML_NOENT, LIBXML_DTDLOAD and SUBST_ENTITIES, and confirm the libxml version with LIBXML_DOTTED_VERSION.