Michael J. Radwin

Tales of a software engineer who keeps kosher and hates the web.

PHP libcurl example

libcurl In one of the sections on my “One Year of PHP at Yahoo!” talk I’m giving next week, I mention the security implications of the allow_url_fopen config setting.

I recommend that people set allow_url_fopen off, and instead use the libcurl extension to do server-side HTTP fetches.

Here’s a comparison of a simple HTTP fetch using both techniques.

allow_url_fopen = On

<?php

$str = file_get_contents("http://www.example.com/");

if ($str !== false) {

// do something with the content

$str = preg_replace("/apples/", "oranges", $str);

// avoid Cross-Site Scripting attacks

$str = strip_tags($str);

echo $str;

}

?>

allow_url_fopen = Off

<?php

$ch = curl_init("http://www.example.com/");

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$str = curl_exec($ch);

if ($str !== false) {

// do something with the content

$str = preg_replace("/apples/", "oranges", $str);

// avoid Cross-Site Scripting attacks

$str = strip_tags($str);

echo $str;

}

curl_close($ch);

?>

It’s not that much additional work to use the curl extension, and you shield all of your regular file I/O against the possibility of accidentally acting as an open proxy. You avoid having to scrutinize every usage of fopen(), readfile(), file_get_contents(), include(), require() and related functions for the possibility that they might be used with a URL.