How to Replace fopen With cURL
In PHP, the fopen command allows you to open a URL and retrieve the contents of a remote document. On some PHP servers, you may find the fopen command locked down for security and blocked from opening external resources. If this is the case, the server administrator will usually provide an alternative, such as the open source cURL package, which PHP has built-in support for using the cURL extension. Replacing the fopen command with the PHP cURL commands allows you to continue to retrieve remote content from within your scripts.
Instructions
-
-
1
Open your PHP script in a text editor or Web design application. Locate the block of code that uses fopen to retrieve data from a remote URL, which will look similar to the following.
<?php
$url = "http://www.domain.com/";
$fp = fopen($url,"r");
$data = "";
if ($fp) {
while (($buffer = fgets($fp, 4096)) !== false) {
$data .= $buffer;
}
fclose($fp);
}
?>This code opens a connection to the URL stored in the variable $url and then reads the contents of the page into the $data variable. After all the data is received the connection is closed.
-
2
Replace the code with the following:
<?php
$url = "http://www.domain.com/";
$data = "";
$cp = curl_init();
curl_setopt($cp, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cp, CURLOPT_URL, $url);
curl_setopt($cp, CURLOPT_TIMEOUT, 60);
$data = curl_exec($cp);
curl_close($cp);
echo $data;
?>Replace the example URL stored in $url with the URL to read from. Change the name of variable $data to match the name of the variable storing the contents of the URL in the original code. The code initiates a cURL instance, sets the URL to retrieve and the timeout parameter and then retrieves the contents of the remote document. The cURL instance is then closed and the contents of the remote URL printed.
-
-
3
Save the page and upload to your server. Open the page in a Web browser to verify that you can see the contents of the remote page.
-
1
Tips & Warnings
cURL is extremely versatile and can achieve much more than the fopen command. It is worth reading through the online documentation to discover all of the features available.
References
Resources
- Photo Credit Jupiterimages/Photos.com/Getty Images