使用PHP清理SVG

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用PHP清理SVG脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用d3.js创建图表作为SVG.这些图表是根据经过身份验证的用户的选择动态生成的.生成这些图表后,用户可以选择将生成的SVG下载为PNG或PDF.

目前的工作流程如下:

// JAVASC
// get the element containing generated SVG
VAR svg = document.getElementById("chart-container");

// Extract the data as SVG text string
var svg_XMl = (new XmlSerializer).serializeToString(svg);

// SubmIT the <FORM> to the server.
var form = document.getElementById("svgform");
form['output_format'].value = output_format;  // can be either "pdf" or "png"
form['data'].value = svg_xML ;
form.submit();

FORM元素是一个隐藏的表单,用于POST数据

<form id="svgform" method="post" action="conversion.PHP">
  <input tyPE="hidden" id="output_format" name="output_format" value="">
  <input type="hidden" id="data" name="data" value="">
</form>

PHP文件将提供的SVG数据保存为临时文件

// check for valid session,etc - omitted for brevity 

$xmldat = $_POST['data'];  // serialized XML rePResenting the SVG element
if(simplexml_load_string($xmldat)===FALSE) { die; } // reject invalid XML  

$fileformat = $_POST['output_format'];  // chosen format for output;  PNG or PDF
if ($fileformat != "pdf" && $fileformat != "png" ){ die; } // limited options for format
$fileformat = escapeshellarg($fileformat); // escape shell arguments that might have snuck in

// generate temporary file names with tempnam() - omitted for brevity

$handle = fopen($infile,"w");
fwrite($handle,$xmldat);
fclose($handle);

运行转换实用程序,该实用程序读取临时文件($infile)并在指定的$fileformat(PDF或PNG)中创建新文件($outfile).然后,生成的新文件将返回到浏览器,并删除临时文件

// headers etc generated - omitted for brevity
readfile($outfile);

unlink($infile);  // delete temporary infile  
unlink($outfile);  // delete temporary outfile

我已经调查了converting the SVG to a PNG using JavaScript (canvg(),then toDataURL,then document.write),可能会用它来生成PNG,但它不允许转换为PDF.

所以:
在将convert.PHP写入文件之前,如何最好地清理或过滤提供给convert.PHP的SVG数据? SVG清理的当前状态是什么PHP中有什么可用的?我应该使用whitelist-based approach来清理提供给conversion.PHP的SVG数据,还是有更好的方法

(我不知道xslt,虽然我可以尝试学习它;我希望尽可能地在PHP中保持清理.使用Windows Server 2008,因此任何使用外部工具的解决方案都需要在该生态系统中可用.)

我正在使用xml和PHP,但我不确定你的问题.请把它作为一个想法/建议,而不是更多.

SimpleXML使用libxml加载xml内容.
http://www.php.net/manual/en/simplexml.requirements.php

您可以使用以下命令禁用外部实体:

libxml_disable_entity_loader (TRUE)

http://www.php.net/manual/en/function.libxml-disable-entity-loader.php

在使用simpleXML加载文件之前.

然后,您可以验证SVG架构

http://us3.php.net/manual/en/domdocument.schemavalidate.php
要么
http://us3.php.net/manual/en/domdocument.validate.php

我唯一担心的是svg可能包含脚本元素. http://www.w3.org/TR/SVG/script.html#ScriptElement

这里有关于1.1 DTD的信息:
http://www.w3.org/Graphics/SVG/1.1/DTD/svg-framework.mod
http://www.w3.org/TR/2003/REC-SVG11-20030114/REC-SVG11-20030114.pdf

您可以为SVG DTD提供脚本元素的修改版本或循环元素以止脚本元素出现.

它不会是完美的,但至少比没有好.

脚本宝典总结

以上是脚本宝典为你收集整理的使用PHP清理SVG全部内容,希望文章能够帮你解决使用PHP清理SVG所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。