Home >Backend Development >PHP Tutorial >How Can I Use PHP cURL to Securely Retrieve Data from HTTPS URLs?

How Can I Use PHP cURL to Securely Retrieve Data from HTTPS URLs?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 11:22:10248browse

How Can I Use PHP cURL to Securely Retrieve Data from HTTPS URLs?

PHP CURL & HTTPS

This article addresses the issue of using PHP CURL to retrieve web files from HTTPS URLs.

The Dilemma

The provided function, get_web_page, encounters a snag when attempting to fetch content from HTTPS URLs.

The Fix

To enable HTTPS support, we can implement one of two solutions:

Solution 1: Manual Option

Add this line to your options array:

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)

Caution: This quick fix disables certificate verification, making your system vulnerable to man-in-the-middle attacks.

Solution 2: Function Update

Incorporate the same code snippet into the updated get_web_page function:

/**
 * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
 * array containing the HTTP server response header fields and content.
 */
function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}

The above is the detailed content of How Can I Use PHP cURL to Securely Retrieve Data from HTTPS URLs?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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