Created
December 11, 2017 13:34
-
-
Save jfstenuit/a3e1140d52c534fb8a3605435b3c13df to your computer and use it in GitHub Desktop.
Safer XML web service call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function saferXML($url){ | |
// Not bullet-proof | |
// but already much better than simplexml_load_string(file_get_contents('https://...')) | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL,$feed_url); | |
curl_setopt($ch, CURLOPT_PROXY, WP_PROXY_HOST); // your proxy url | |
curl_setopt($ch, CURLOPT_PROXYPORT, WP_PROXY_PORT); // your proxy port number | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_HEADER, false); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); | |
$xml = curl_exec($ch); | |
curl_close($ch); | |
$oldValue = libxml_disable_entity_loader(true); | |
libxml_use_internal_errors(true); | |
$data = false; | |
$collapsedXML = preg_replace("/[:space:]/", '', $xml); | |
if(preg_match("/<!DOCTYPE/i", $collapsedXml)) { | |
echo "Invalid XML: Detected use of illegal DOCTYPE\n"; | |
} elseif(preg_match("/<!ENTITY/i", $collapsedXml)) { | |
echo "Invalid XML: Detected use of illegal ENTITY\n"; | |
} else { | |
$data = simplexml_load_string($xml); | |
if ($data === false) { | |
echo "Failed loading XML\n"; | |
foreach(libxml_get_errors() as $error) { | |
echo "\t", $error->message; | |
} | |
} | |
} | |
libxml_disable_entity_loader($oldValue); | |
return $data; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment