Using WordPress ‘http_api_curl’ PHP action

The http_api_curl WordPress PHP action fires before a cURL request is executed, allowing plugins to handle cookies themselves.

Usage

add_action('http_api_curl', 'your_custom_function', 10, 3);

function your_custom_function($handle, $parsed_args, $url) {
  // your custom code here
}

Parameters

  • $handle (resource): The cURL handle returned by curl_init() (passed by reference).
  • $parsed_args (array): The HTTP request arguments.
  • $url (string): The request URL.

More information

See WordPress Developer Resources: http_api_curl

Examples

Set custom cURL options

This example sets custom cURL options for timeouts and redirects.

add_action('http_api_curl', 'custom_curl_options', 10, 3);

function custom_curl_options($handle, $parsed_args, $url) {
  curl_setopt($handle, CURLOPT_TIMEOUT, 10); // Set timeout to 10 seconds
  curl_setopt($handle, CURLOPT_MAXREDIRS, 5); // Set maximum number of redirects to 5
}

Add a custom User-Agent

This example adds a custom User-Agent to the cURL request.

add_action('http_api_curl', 'custom_user_agent', 10, 3);

function custom_user_agent($handle, $parsed_args, $url) {
  curl_setopt($handle, CURLOPT_USERAGENT, 'My Custom User-Agent');
}

Set custom proxy settings

This example sets custom proxy settings for the cURL request.

add_action('http_api_curl', 'custom_proxy_settings', 10, 3);

function custom_proxy_settings($handle, $parsed_args, $url) {
  curl_setopt($handle, CURLOPT_PROXY, 'http://proxy.example.com:8080');
  curl_setopt($handle, CURLOPT_PROXYUSERPWD, 'username:password');
}

Enable verbose logging

This example enables verbose logging for the cURL request.

add_action('http_api_curl', 'enable_verbose_logging', 10, 3);

function enable_verbose_logging($handle, $parsed_args, $url) {
  curl_setopt($handle, CURLOPT_VERBOSE, true);
}

Follow redirects for specific domains

This example enables following redirects only for specific domains.

add_action('http_api_curl', 'follow_redirects_for_domains', 10, 3);

function follow_redirects_for_domains($handle, $parsed_args, $url) {
  if (strpos($url, 'https://example.com') !== false) {
    curl_setopt($handle, CURLOPT_FOLLOWLOCATION, true);
  }
}