Using cURL with Self-Signed Certificates: PHP Code Examples

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

You may need to use cURL in your PHP applications to establish secure connections when working with APIs and web services. SSL certificates are crucial in securing these connections, but sometimes you must work with self-signed certificates. So, in this article, we will discuss how to use PHP cURL with self-signed certificate.

How to Use cURL with Self-Signed Certificates

This article will teach you how to use PHP cURL with self-signed certificates effectively. And also you will discover the best practices to avoid potential security risks.

Self-Signed Certificates: with cURL PHP Code Example

<?php
$url = 'https://example.com';
$cert_path = '/path/to/self_signed_cert.crt';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
## This is the option to set a certificate for certificate ##
curl_setopt($ch, CURLOPT_CAINFO, $cert_path);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

Steps to generate a self-signed certificate

  1. Install OpenSSL: OpenSSL is an open-source toolkit for implementing SSL and TLS protocols. It provides a suite of tools for generating and managing certificates. Install OpenSSL on your system if you haven’t already. You can find installation instructions for various platforms on the OpenSSL website.
  2. Generate a private key: Use OpenSSL to create one, specifying the desired encryption algorithm (e.g., RSA) and key length (e.g., 2048 bits).
  3. Create a Certificate Signing Request (CSR): Generate a CSR using the private key from the previous step. You must provide information about your organization and the domain for which the certificate is issued.
  4. Sign the CSR to create the certificate: Sign the CSR using your private key to generate a self-signed certificate. During this step, you can set the certificate’s validity period (e.g., 365 days).

Article Highlights 

  • SSL certificates are essential for securing connections between clients and servers. But self-signed certificates can present challenges due to their lack of trust by default.
  • Self-signed certificates are suitable for testing and development purposes but should not use them in production environments.
  • Create a self-signed certificate using OpenSSL by generating a private key, creating a Certificate Signing Request (CSR), and signing the CSR with the private key.
  • Make secure cURL requests to servers with self-signed certificates by enabling certificate validation and configuring cURL to trust the self-signed certificate using the CURLOPT_CAINFO option.
  • Handle certificate errors by verifying, updating the CA bundle, or using a custom CA bundle that includes the self-signed certificate.
  • Best practices for using self-signed certificates with cURL include avoiding disabling SSL verification, using self-signed certificates for testing and development only, considering trusted Certificate Authorities for production environments, and keeping CA bundles updated.

Table of Contents

In this article, we will cover the following topics.

  1. What is cURL?
  2. Why Use SSL Certificates?
  3. What are Self-Signed Certificates?
  4. What are the Challenges with self-signed certificates?
  5. Prerequisites.
  6. Creating a Self-Signed Certificate.
  7. Connecting to a Server with a Self-Signed Certificate using cURL.
  8. Handling Certificate Errors.
  9. Best Practices for Using Self-Signed Certificates with cURL.
  10. Using cURL with Self-Signed Certificates: PHP Code Examples (2023) Summary.

What is cURL

cURL is a powerful command-line tool and library that allows developers to transfer data via various network protocols, including HTTP, HTTPS, FTP, and more. In PHP, the cURL library is widely used to make HTTP requests and interact with APIs. The PHP cURL extension enables developers to harness cURL’s capabilities within their PHP scripts. It also provides a flexible and efficient way to access and exchange data with other web services.

Check out our articles on What is cURL Used For | 2023 PHP Code Examples & Alternatives

Why Use SSL Certificates

SSL certificates are essential for establishing secure connections between clients and servers. 

They provide multiple benefits, including:

  1. Encryption: SSL certificates help encrypt data transmitted between the client and the server. This ensures that sensitive information, such as login credentials, personal details, and financial data, remains confidential and cannot be intercepted by malicious third parties.
  2. Authentication: SSL certificates provide a way for clients to verify the server’s identity they are connecting to. This is important because it prevents man-in-the-middle attacks, where an attacker could impersonate the server and intercept sensitive data.
  3. Integrity: SSL certificates ensure the integrity of data transmitted between the client and the server. This means that the data cannot be tampered with or altered during transmission, ensuring that the information received is accurate and genuine.
  4. Trust: SSL certificates are issued by trusted Certificate Authorities (CAs), which have a rigorous validation process for verifying the identity of a website or service. When users see the padlock icon or the HTTPS in their browser’s address bar, they know that the connection is secure and that the website is legitimate, boosting their trust and confidence.

What are Self-Signed Certificates

Self-signed certificates are SSL certificates signed by the person or organization that created them rather than a trusted Certificate Authority (CA). They still provide encryption; we can use them to create secure connections. However, because a trusted CA does not issue them, they are not automatically trusted by clients, such as web browsers or applications.

Self-signed certificates are often used for testing and development, as they can be generated quickly and without cost. They are generally not recommended in production environments where trust and security are crucial.

What are the Challenges with Self-Signed Certificates

While SSL certificates are essential for secure connections, using self-signed certificates can introduce challenges. A self-signed certificate is an SSL certificate signed by the creator instead of a trusted Certificate Authority (CA). 

Here are some challenges with self-signed Certificates:

  1. Lack of trust: Since a trusted CA does not issue self-signed certificates, clients like web browsers and applications will not automatically trust them. This can result in security warnings or errors when users try to access a website or service using a self-signed certificate.
  2. Certificate errors: Self-signed certificates can cause certificate errors in clients, such as hostname mismatches, expired certificates, or untrusted certificate chains. These errors can lead to broken connections or security warnings that may deter users from accessing your website or service.
  3. Increased maintenance: Managing self-signed certificates can be more labor-intensive, as you need to generate, distribute, and maintain the certificates yourself. This includes updating expired certificates and ensuring that all clients have the correct certificate information.
  4. Potential security risks: Using self-signed certificates in production environments may expose your website or service to potential security risks. For example, if you disable certificate validation to bypass errors caused by self-signed certificates, you could be vulnerable to man-in-the-middle attacks or other security threats.

Given these challenges, it’s essential to understand the limitations of self-signed certificates. And also follow best practices when using them with cURL or other applications.

Prerequisites

Before diving into using cURL with self-signed certificates, it’s essential to ensure that you have the following prerequisites:

PHP installed

PHP (Hypertext Preprocessor) is a widely-used server-side scripting language primarily used for web development. In this tutorial, we will be using PHP to interact with cURL. To follow along, you should have PHP installed on your development machine. You can download and install PHP from the official PHP website.

cURL library for PHP

A cURL library is a powerful tool enabling PHP to interact with web services and APIs using protocols like HTTP and HTTPS. By default, most PHP installations come with the cURL library. However, if you don’t have it installed, you can follow the installation instructions for your platform from the official PHP cURL documentation.

A basic understanding of SSL certificates

SSL (Secure Sockets Layer) certificates are digital certificates that enable secure connections between a client and a server. They are used to encrypt data transmitted over the internet and to authenticate the server’s identity. To follow this tutorial, you should understand how SSL certificates work, the role of Certificate Authorities (CAs), and the difference between trusted and self-signed certificates.

Familiarity with PHP syntax and cURL

To effectively use cURL with self-signed certificates in PHP, you should be familiar with PHP syntax and understand how to use cURL for making requests. This includes knowing how to initialize cURL sessions, set cURL options, and execute cURL requests. If you are new to PHP and cURL, you may want to review some introductory material on PHP and cURL before diving into this tutorial.

Creating a Self-Signed Certificate

A self-signed certificate is an SSL certificate signed by its creator rather than a trusted Certificate Authority (CA). While they provide encryption and can be used to create secure connections, they are not automatically trusted by clients, such as web browsers or applications. Self-signed certificates are primarily used for testing and development, where trust and security are less critical.

Steps to generate a self-signed certificate

Step-1: Install OpenSSL.

OpenSSL is an open-source toolkit that provides a robust set of cryptographic functions and utilities, including generating self-signed certificates. First, download and install OpenSSL on your system to create a self-signed certificate. Visit the OpenSSL download page to obtain the appropriate version for your platform.

Step-2: Generate a private key.

To create a self-signed certificate, you must first generate a private key. The private key is used to sign the certificate and should be kept secure. Run the following command to create a 2048-bit RSA private key:

openssl genrsa -out my_key.key 2048

Step-3: Create a Certificate Signing Request (CSR).

A Certificate Signing Request (CSR) is a file containing your public key and additional information about your organization or website. The CSR is used to generate the SSL certificate. 

Run the following command to create a CSR, replacing the relevant fields as needed:

openssl req -new -key my_key.key -out my_csr.csr

Step-4: Sign the CSR to create the certificate.

Once you have the CSR, you can sign it using your private key to create the self-signed certificate. 

Run the following command to generate a self-signed certificate valid for 365 days:

openssl x509 -req -days 365 -in my_csr.csr -signkey my_key.key -out my_cert.crt

Installing the certificate on a server

After generating the self-signed certificate, you need to install it on your server to use it for secure connections. Installing the certificate depends on the server software you are using, such as Apache, Nginx, or IIS. Generally, this involves configuring the server to use the certificate file (my_cert.crt) and private key file (my_key.key) for SSL/TLS connections.

For specific instructions on installing the self-signed certificate on your server, refer to the documentation for your server software:

Once the self-signed certificate is installed on your server, you can use it for testing and development purposes. Also, keep in mind the limitations and challenges associated with self-signed certificates.

Connecting to a Server with a Self-Signed Certificate using cURL

To connect to a server with a self-signed certificate using PHP cURL, follow the steps below:

Basic cURL request without certificate validation

We use the following PHP code for basic cURL requests without certificate validation.

<?php
$url = 'https://example.com';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

Explanation of code

In this code, we are making a basic cURL request to a server with a self-signed certificate without validating the certificate.

  • $url: The URL of the server with the self-signed certificate.
  • curl_init($url): Initializes a new cURL session with the URL.
  • CURLOPT_RETURNTRANSFER: This option is set to true to return the response as a string rather than outputting it directly.
  • CURLOPT_SSL_VERIFYPEER: This option is set to false to disable SSL certificate validation. This allows the request to proceed without validating the server’s certificate, which is not recommended for production environments as it can lead to security risks.

Adding certificate validation

PHP code Example:
<?php
$url = 'https://example.com';
$cert_path = '/path/to/self_signed_cert.crt';

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_CAINFO, $cert_path);
$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

Explanation of code

In the above code example, we are making a cURL request to a server with a self-signed certificate and validating the certificate.

  • $url: The URL of the server with the self-signed certificate.
  • $cert_path: The path to the self-signed certificate file (in .crt or .pem format) on your local system.
  • curl_init($url): Initializes a new cURL session with the given URL.
  • CURLOPT_RETURNTRANSFER: This option is set to true to return the response as a string, rather than outputting it directly.
  • CURLOPT_SSL_VERIFYPEER: This option is set to true to enable SSL certificate validation. This is the recommended setting for secure connections.
  • CURLOPT_CAINFO: This option is set to the path of your self-signed certificate. This tells cURL to validate the server’s certificate against your self-signed certificate, allowing the request to proceed if the certificates match.

By adding certificate validation, you ensure a more secure connection when using cURL with self-signed certificates, reducing the risks associated with disabling SSL certificate validation.

Handling Certificate Errors

Common certificate errors

You may encounter some common certificate errors when using cURL to connect to a server with a self-signed certificate. 

These can include:

  1. Untrusted certificate: Since self-signed certificates are not issued by a trusted Certificate Authority (CA), clients such as cURL may not trust them by default, leading to connection errors.
  2. Hostname mismatch: If the certificate’s domain name (or hostname) does not match the server’s domain name you are connecting to, cURL will throw a hostname mismatch error.
  3. Expired certificate: Certificates have a short validity period, and if a certificate is expires. And cURL will throw an error indicating that the certificate is no longer valid.

Potential security risks of ignoring errors

Ignoring or bypassing certificate errors can lead to potential security risks:

  1. Man-in-the-middle (MITM) attacks: If you disable certificate validation or ignore hostname mismatches, your connection may be susceptible to MITM attacks. An attacker could intercept your connection and decrypt your data or impersonate the server, potentially gaining access to sensitive information.
  2. Compromised data: Disabling certificate validation may result in transmitting sensitive data over insecure connections, leaving unauthorised third parties vulnerable to interception and tampering.

Solutions for handling errors

  1. Verify the certificate: Ensure that the self-signed certificate you’re using is correct and that the server you’re connecting to uses the same certificate. Double-check the certificate’s hostname and ensure it matches the server’s domain name.
  2. Update CA bundle: Although self-signed certificates are not trusted by default, you can add the self-signed certificate to your local CA bundle to make it trusted by cURL. To do this, append the contents of your self-signed certificate to the CA bundle file used by cURL (often named cacert.pem). Then, configure cURL to use the updated CA bundle by setting the CURLOPT_CAINFO option to the path of the updated CA bundle.
  3. Use a custom CA bundle: Instead of modifying the system-wide CA bundle, you can create a custom CA bundle that includes your self-signed certificate. To do this, copy the contents of your self-signed certificate into a new file (e.g., custom_cabundle.pem). Then, configure cURL to use the custom CA bundle by setting the CURLOPT_CAINFO option to the path of the custom CA bundle. This allows cURL to trust your self-signed certificate while keeping the system-wide CA bundle unchanged.

By handling certificate errors responsibly and following best practices, you can maintain secure connections when using cURL with self-signed certificates.

Best Practices for Using Self-Signed Certificates with cURL

The following are some best practices for using self-signed certificates with cURL:

Avoid disabling SSL verification

Disabling SSL verification, such as setting CURLOPT_SSL_VERIFYPEER to false, bypasses the validation of the server’s SSL certificate. This can expose your connection to security risks, such as man-in-the-middle (MITM) attacks. Always validate certificates, even when using self-signed certificates, by configuring cURL to trust your self-signed certificate using the CURLOPT_CAINFO option.

Use self-signed certificates for testing and development only

Self-signed certificates are helpful for testing and development purposes. And as they allow you to set up secure connections without purchasing or obtaining a certificate from a trusted Certificate Authority (CA). However, self-signed certificates are not recommended for production environments, as clients and web browsers will not trust them by default, leading to security warnings and potential connection issues.

Consider using a trusted Certificate Authority (CA) for production environments.

Obtaining an SSL certificate from a trusted Certificate Authority (CA) is best for production environments. Trusted CAs are recognized by clients and web browsers, which means that connections to your server will be trusted and secure without any additional configuration. Many CAs offer free certificates, such as Let’s Encrypt, making it easy and cost-effective to secure your production environment.

Keep CA bundles updated

CA bundles are collections of trusted root certificates from various Certificate Authorities. It’s essential to keep your CA bundles updated to maintain trust in the certificates issued by these CAs. Regularly updating your CA bundles ensures that your cURL connections are secure and you can trust the certificates presented by the servers you connect to. If you use a custom CA bundle, update it with any new or updated certificates, including your self-signed certificates.

By following these best practices, you can ensure that using self-signed certificates with cURL remains secure and suitable for your development and testing needs.

Using cURL with Self-Signed Certificates: PHP Code Examples Summary

Secure connections are vital in today’s digital landscape, as they protect sensitive information and maintain the privacy of both clients and servers. SSL certificates are crucial in securing connections by providing encryption and authentication. When using cURL to connect to servers with self-signed certificates, it is essential to follow best practices to ensure connections remain secure and avoid potential security risks.

This article provides a comprehensive guide on using cURL with self-signed certificates in PHP. It covers the importance of SSL certificates, the challenges of using self-signed certificates, and creating and installing them on a server. 

The article also demonstrates how to make secure cURL requests to servers with self-signed certificates by enabling certificate validation and handling potential certificate errors. This article also explains best practices for using self-signed certificates with cURL. And emphasizing the importance of avoiding disabling SSL verification, using self-signed certificates for testing and development only, considering a trusted Certificate Authority for production environments, and keeping CA bundles updated. 

By following the guidelines provided, you can ensure secure connections when using cURL with self-signed certificates for your development and testing needs.

Continue Learning About cURL

This article is part of a more extensive series on using cURL in PHP. Feel free to browse through the articles to dig deeper into the topic.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.