Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用simplexml提高安全性_Php_Xml_Security_Simplexml - Fatal编程技术网

Php 使用simplexml提高安全性

Php 使用simplexml提高安全性,php,xml,security,simplexml,Php,Xml,Security,Simplexml,我有一个xml文档,使用simplexml我可以轻松地解析成我想要的内容 我的Xml: <?xml version="1.0" encoding="UTF-8"?> <noticias> <noticia url="noticia-1"> <titulo>título da notícia 1</titulo> <desc>some description</desc>

我有一个xml文档,使用simplexml我可以轻松地解析成我想要的内容

我的Xml:

<?xml version="1.0" encoding="UTF-8"?>

<noticias>
    <noticia url="noticia-1">
        <titulo>título da notícia 1</titulo>
        <desc>some description</desc>
        <texto>some text here</texto>
        <img>filename here</img>
        <in>some reference to where it came from</in>
    </noticia>
    ...
</noticias>

título da notícia 1
一些描述
这里有一些文字
文件名在这里
关于它从哪里来的一些参考
...
PHP simplexml解析器

$file = 'xml/noticias.xml';
if(file_exists($file)) {
    $xml = simplexml_load_file($file);
    foreach($xml as $item) {
        $url = $item['url'];
        $titulo = $item->titulo;
        ...

        echo '<div><h2>'.$titulo.'</h2></div>';
    }
}
$file='xml/noticias.xml';
如果(文件_存在($file)){
$xml=simplexml\u load\u文件($file);
foreach($xml作为$item){
$url=$item['url'];
$titulo=$item->titulo;
...
回声“.$titulo.”;
}
}
我的问题是:这安全吗?如何提高安全性?
提前谢谢。

不是。但是,源代码中的问题与SimpleXML无关。将外部数据源(XML文件)中的字符串值作为HTML源输出。这允许一种叫做HTML注入的东西。它可以打断您的输出,或者在用户没有注意到的情况下对其进行操作

以下是一个基于您的来源的小示例:

$xmlString = <<<'XML'
<noticias>
    <noticia url="noticia-1">
        <titulo>título da &lt;i>notícia&lt;/i> 1</titulo>
    </noticia>
</noticias>
XML;

$xml = simplexml_load_string($xmlString);
foreach($xml->noticia as $item) {
  $titulo = $item->titulo;
  echo '<div><h2>'.$titulo.'</h2></div>';
}
$xmlString=noticia作为$item){
$titulo=$item->titulo;
回声“.$titulo.”;
}
输出:

<div><h2>título da <i>notícia</i> 1</h2></div>
título da notícia 1
i
元素是XML中的文本内容,但输出中是HTML源代码。标题的一部分将在浏览器中显示为斜体。这是一个无害的HTML注入示例,但是想象一下,有人的意图不太好


如果您向HTML输出任何值,请确保使用
htmlspecialchars()
转义特殊字符,或使用API(如DOM)为您转义。

在安全性中,了解数据的来源和去向非常重要。谁或什么人可以使用它?谁或什么人被允许访问它?等等。由于您没有告诉我们这些,我们无法回答您的问题。@KIKOSoftware xml文件位于名为xml的子文件夹中。这是一个简单的xml文件,将直接编辑,并将使用php解析,例如在index.php中。目前,它对所有人开放,但我可以在.htaccess文件中制定一条规则,拒绝访问xml文件。不知道这是否有帮助。由于没有数据来自服务器外部,并且任何人都可以访问这两个文件,因此没有安全问题。