Can CURL Be an Alternative to file_get_contents for Fetching External Links?

Susan Sarandon
Release: 2024-10-17 21:34:30
Original
812 people have browsed it

Can CURL Be an Alternative to file_get_contents for Fetching External Links?

Using CURL to Fetch External Links (Alternative to file_get_contents)

For fetching external links on a specific page, the file_get_contents function is typically employed. However, when the server you're using doesn't support this function, CURL can serve as a viable alternative.

To implement CURL, you can utilize the following code:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

// Usage Example
echo file_get_contents_curl('http://google.com');
Copy after login

But in cases where this code returns a blank page, it's likely that enabling URL redirection is necessary. To address this issue, modify the code in the following manner:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}
Copy after login

The above is the detailed content of Can CURL Be an Alternative to file_get_contents for Fetching External Links?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template