Home > Backend Development > PHP Tutorial > How to Fix PHP cURL HTTPS Connection Issues?

How to Fix PHP cURL HTTPS Connection Issues?

Mary-Kate Olsen
Release: 2024-12-17 05:37:24
Original
211 people have browsed it

How to Fix PHP cURL HTTPS Connection Issues?

PHP CURL and HTTPS

The provided function is an excellent tool for retrieving web pages. However, it encounters issues when dealing with HTTPS URLs. To resolve this, we need to make the necessary adjustments to enable HTTPS support.

Solution 1: CURLOPT_SSL_VERIFYPEER

The first and quickest solution is to add the following option to the $options array:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
Copy after login

This disables certificate verification, effectively allowing you to connect to any host. However, this is not recommended as it leaves you vulnerable to man-in-the-middle attacks.

Solution 2: Updated Function

An alternative approach is to incorporate the fix directly into the 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 = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => '',
        CURLOPT_USERAGENT => 'spider',
        CURLOPT_AUTOREFERER => true,
        CURLOPT_CONNECTTIMEOUT => 120,
        CURLOPT_TIMEOUT => 120,
        CURLOPT_MAXREDIRS => 10,
        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;
}
Copy after login

This updated function now supports both HTTP and HTTPS URLs by disabling certificate verification at the cost of security.

The above is the detailed content of How to Fix PHP cURL HTTPS Connection Issues?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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