如何在php中转义xpath [英] How to escape xpath in php

查看:28
本文介绍了如何在php中转义xpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

逃避提供给 xpath 的 var 的最佳方法是什么.

What is the best way to escape a var given to xpath.

$test = simplexml_load_file('test.xml');
$var = $_GET['var']; // injection heaven
$result = $test->xpath('/catalog/items/item[title="'.$var.'"]');

通常我使用 PDO 绑定.或类似的东西,但它们都需要数据库连接.仅 addslasheshtmlentities 就足够了.
或者有更好的方法吗?

Normally I use PDO binding. OR stuff like that but they all require a database connection. Is it enough to just addslashes and htmlentities.
Or is there a better to do this?

推荐答案

你不能真正制作一个通用的 xpath escape 函数,但你可以制作一个 XPath quote函数,可以像

you can't really make a general xpath escape function, but you can make an XPath quote function, which can be used like

$result = $test->xpath('/catalog/items/item[title='.xpath_quote($var).']');

实现:

//based on https://stackoverflow.com/a/1352556/1067003
function xpath_quote(string $value):string{
    if(false===strpos($value,'"')){
        return '"'.$value.'"';
    }
    if(false===strpos($value,'\'')){
        return '\''.$value.'\'';
    }
    // if the value contains both single and double quotes, construct an
    // expression that concatenates all non-double-quote substrings with
    // the quotes, e.g.:
    //
    //    concat("'foo'", '"', "bar")
    $sb='concat(';
    $substrings=explode('"',$value);
    for($i=0;$i<count($substrings);++$i){
        $needComma=($i>0);
        if($substrings[$i]!==''){
            if($i>0){
                $sb.=', ';
            }
            $sb.='"'.$substrings[$i].'"';
            $needComma=true;
        }
        if($i < (count($substrings) -1)){
            if($needComma){
                $sb.=', ';
            }
            $sb.="'\"'";
        }
    }
    $sb.=')';
    return $sb;
}

它基于 https://stackoverflow.com/a/1352556/1067003 中的 C# xpath 引用函数

and it's based on the C# xpath quote function from https://stackoverflow.com/a/1352556/1067003

仅添加斜线和 htmlentities 就足够了.或者有更好的方法吗?

Is it enough to just addslashes and htmlentities. Or is there a better to do this?

通过使用适当的 xpath 引用函数,而不是 addlashes/htmlentities,我会在晚上睡得更好,但我真的不知道这些在技术上是否足够.

i would be sleeping better at night by using a proper xpath quote function, rather than addslashes/htmlentities, but i don't really know if those technically are sufficient or not.

这篇关于如何在php中转义xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆