Home >Backend Development >PHP Tutorial >How to Fix 'SSL operation failed with code 1' Error in PHP's `file_get_contents()`?

How to Fix 'SSL operation failed with code 1' Error in PHP's `file_get_contents()`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 08:58:13968browse

How to Fix

Troubleshooting file_get_contents() SSL Certificate Verification Error

When attempting to access a REST service using file_get_contents() in PHP 5.6, you may encounter the error "SSL operation failed with code 1" due to stricter certificate verification.

Issue Description
The user's PHP page tries to fetch data from an HTTPS endpoint using file_get_contents(). However, it fails with the following errors:

  • Warning: SSL operation failed with code 1. OpenSSL Error messages: certificate verify failed
  • Warning: Failed to enable crypto
  • Warning: Failed to open stream: operation failed

Root Cause
PHP 5.6 introduced stricter SSL verification by default, requiring accurate certificate validation. The error indicates that the client cannot verify the certificate of the remote server.

Resolution
To resolve this issue, an official PHP document on OpenSSL changes in 5.6 recommends disabling certificate verification. Note: this solution has significant security implications and should only be considered in controlled environments where trust between client and server is established.

$arrContextOptions = array(
    "ssl" => array(
        "verify_peer" => false,
        "verify_peer_name" => false,
    ),
);

$response = file_get_contents("remote_url", false, stream_context_create($arrContextOptions));
  1. Create an array ($arrContextOptions) to configure the SSL options.
  2. Set verify_peer to false to disable the certificate verification.
  3. Set verify_peer_name to false to disable the hostname verification.
  4. Create a stream_context using the $arrContextOptions array.
  5. Pass the stream context as the third parameter to file_get_contents().

Important Note
Disabling SSL certificate verification reduces security and can expose your application to eavesdropping and other security breaches. It is strongly recommended to configure your system correctly to use trusted SSL certificates instead of resorting to this workaround.

The above is the detailed content of How to Fix 'SSL operation failed with code 1' Error in PHP's `file_get_contents()`?. 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