就 XSS 攻击而言,在 php 中回显格式化的 DateTime 是否安全?

Is it safe to echo formatted DateTime in php in terms of XSS attack?

我有一个相当复杂的 Web 应用程序。我需要使用 htmlspecialchars() 函数清理发送到视图(MVC 架构)的所有变量,以防止 XSS 攻击。因为它不仅仅是我发送到视图的原始数据类型,所以我正在实现一个函数,它遍历变量数组并根据它们的类型以不同的方式清理它们中的每一个(我正在使用 gettype() 来区分一下)。

我的问题是,当我通过 format() 方法回显它们的内容时,是否需要以某种方式清理 DateTime 对象。 DateTime 对象是否会以某种方式被滥用于 XSS 攻击,或者它们是否被认为是安全的?

我想我应该只将原始数据类型传递给我的视图,但我也有点需要传递对象。

这是我使用的函数:

private function sanitize(array $data)
{
    foreach ($data as $propertyName => $propertyValue)
    {
        if (gettype($propertyValue) === 'array')
        {
            //Sanitize each element of the array by recursion
            $data[$propertyName] = $this->sanitize($data[$propertyName]);
        }
        else if (gettype($propertyValue) === 'NULL')
        {
            //NULL can stay NULL
            continue;
        }
        else if ($propertyValue instanceof DatabaseItem)
        {
            //Sanitize instances of my custom class DatabaseItem
            $propertyValue->sanitizeSelf();
        }
        else if ($propertyValue instanceof DateTime)
        {
            //TODO - is DateTime safe?
        }
        else
        {
            //boolean, integer, double, string
            $data[$propertyName] = htmlspecialchars($propertyValue, ENT_QUOTES);
        }
    }
    return $data;
}

短:是的。 如果您的值不是日期,它只会导致错误:

<?php
$d=new DateTime (" <script> malicious </script>");
#test
echo $d->format("y");
/*will cause something like 
Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string ( <script> malicious </script>)*/