How do I use cURL in place of the PHP option allow_url_fopen?

Updated 6 months ago by Josselyn Rodriguez

cURL is a command line tool for transferring files with a URL syntax, supporting FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. cURL supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form-based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, Kerberos, etc.), file transfer resume, proxy tunneling, and other useful tricks. 

Here's how to use cURL in place of the PHP option allow_url_fopen:

Fetching a web page
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
?>
Alternative for file_get_contents()

Instead of: 

$file_contents = file_get_contents('http://example.com/');
// display file
echo $file_contents;
?>

Use this:

$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);

// display file
echo $file_contents;
?>
Alternative for file()

Instead of: 

$lines = file('http://example.com/');
// display file line by line
foreach($lines as $line_num => $line) {
echo "Line # {$line_num} : ".htmlspecialchars($line)."
n";
}
?>

Use this:

$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://example.com');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
$lines = array();
$lines = explode("n", $file_contents);

// display file line by line
foreach($lines as $line_num => $line) {
echo "Line # {$line_num} : ".htmlspecialchars($line)."
n";
}
?>

Having trouble? Contact us and our team will be happy to help.


How did we do?