Search code examples
phpdomxpathhtml-escape-characters

How to escape all invalid characters from DOM XPath Query?


I have the following function that finds values within a HTML DOM;

It works, but when i give parameter $value like: Levi's Baby Overall, it cracks, because it does not escape the , and ' chars

How to escape all invalid characters from DOM XPath Query?

private function extract($file,$url,$value) {
    $result = array();
    $i = 0;
    $dom = new DOMDocument();
    @$dom->loadHTMLFile($file);
    //use DOMXpath to navigate the html with the DOM
    $dom_xpath = new DOMXpath($dom);
    $elements = $dom_xpath->query("//*[text()[contains(., '" . $value . "')]]");
    if (!is_null($elements)) {
        foreach ($elements as $element) {
            $nodes = $element->childNodes;
            foreach ($nodes as $node) {
                if (($node->nodeValue != null) && ($node->nodeValue === $value)) {
                    $xpath = preg_replace("/\/text\(\)/", "", $node->getNodePath());
                    $result[$i]['url'] = $url;
                    $result[$i]['value'] = $node->nodeValue;
                    $result[$i]['xpath'] = $xpath;
                    $i++;
                }
            }
        }
    }
    return $result;
}

Solution

  • One shouldn't substitute placeholders in an XPath expression with arbitrary, user-provided strings -- because of the risk of (malicious) XPath injection.

    To deal safely with such unknown strings, the solution is to use a pre-compiled XPath expression and to pass the user-provided string as a variable to it. This also completely eliminates the need to deal with nested quotes in the code.