1

I am using XPath to select XML nodes in a SimpleXMLElement. My XPath expression is variable:

$xml->xpath("a[@href = '{$some_specific_value_of_href}']");

Since I do not have full control over the value of the $some_specific_value_of_href variable, the above code is prone to an injection attack, where a malicious value of the variable will produce an arbitrary set of elements.

Most mature XML APIs, such as the lxml library for Python, allow the user to specify placeholder variable names in an XPath expression, and compile the XPath expression without running the risk of an injection attack:

xml.xpath(
    "a[@href = $placeholder_variable_name]",  # Python performs no substitution here
    placeholder_variable_name=some_specific_value_of_href
);

Is there similar functionality available for PHP 7?

Witiko
  • 3,167
  • 3
  • 25
  • 43
  • Not really a duplicate, related perhaps. The other question is asking how to sanitize. This question is asking whether PHP requires the programmer to sanitize, or whether there is support for pre-compiled XPath expressions. – Witiko Jul 31 '18 at 16:59
  • The question and the answer are the same: It's bad design to be passing user-providing strings into XPath expressions (accepted, correct answer) and there's sample sanitizing code (other answer) if you want to disregard the good advice to change your design. – kjhughes Jul 31 '18 at 17:03
  • The answer in the duplicate containing the `xpath_quote` function is probably the useful part. No, PHP doesn't have native support for a parameterised xpath query, so you'll need to do something yourself. – iainn Jul 31 '18 at 17:03
  • @kjhughes The accepted answer advises to “use pre-compiled XPath expression”. That is a fairly useless piece of advice in the context of this question, since as we have learnt, PHP does not support pre-compiled XPath expression. – Witiko Jul 31 '18 at 18:30
  • The accepted answer primarily advises against what you wish to do, and the other answer there offers a way to do so if you insist. Further, I've added a second Q/A on the topic to the duplicate box. If you feel your answer is still distinct, please explain how. Thanks. – kjhughes Jul 31 '18 at 19:06

0 Answers0