Link Search Menu Expand Document

XPath Injection in PHP

Play SecureFlag Play PHP Labs on this vulnerability with SecureFlag!

Prevention

As with other injection attacks, avoid direct string concatenation when constructing XPath queries.

Where available, use DOMXPath::quote() to safely escape user-supplied input before incorporating it into an XPath expression. This method ensures that the input is properly quoted and reduces the risk of XPath Injection.

If DOMXPath::quote() is not available, consider the following alternatives:

  • Embedding user input within the XML document and referencing it from the XPath query, which avoids direct interpolation into the expression.

      $xml['search'] = $query;
      $xpath = "//product[contains(name, /*/@search)]";
    

    This ensures the input is treated as data, not as part of the XPath syntax.

  • Manual escaping of user input (error-prone, should only be used when safer methods are unavailable).