Curl error operation timed out after 0 milliseconds with 0 out of 0 bytes received

I use CURL to perform upload/download operations via HTTP from an openstack Swift server (www.hubic.com). I get random errors "Operation timed out after 0 milliseconds with 0 out of 0 bytes re...

I’m suffering the same thing, that error just randomly happens:

    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_USERAGENT, 'Merchant');
    curl_setopt($ch, CURLOPT_USERPWD, "XXX:YYY");
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
    curl_setopt($ch, CURLOPT_NOPROGRESS, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);


$: curl -V
curl 7.40.0 (x86_64-redhat-linux-gnu) libcurl/7.40.0 NSS/3.19.1 Basic ECC zlib/1.2.7 libidn/1.28 libssh2/1.4.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp scp sftp smb smbs smtp smtps telnet tftp
Features: AsynchDNS IDN IPv6 Largefile GSS-API Kerberos SPNEGO NTLM NTLM_WB SSL libz UnixSockets Metalink

Some time this error in Joomla appear because some thing incorrect with SESSION or coockie.
That may because incorrect HTTPd server setting or because some before CURL or Server http requests

so PHP code like:

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
  curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
  curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
  curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

will need replace to PHP code

  curl_setopt($ch, CURLOPT_URL, $url_page);
  curl_setopt($ch, CURLOPT_HEADER, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
//curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
  curl_setopt($ch, CURLOPT_REFERER, $url_page);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
//curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__) . "./cookie.txt");
//curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // !!!!!!!!!!!!!
  //if( $sc != "" ) curl_setopt($ch, CURLOPT_COOKIE, $sc);

May be some body reply how this options connected with «Curl error: Operation timed out after ..»

So you’re trying to use your favorite WordPress plugin but an ugly cURL error 28 is being displayed in your screen or error log… Something like

cURL error 28: Connection timed out after X milliseconds

or

cURL error 28: Operation timed out after X milliseconds with 0 out of 0 bytes received

What’s going on? If you search in Google you will find that in fact it’s a very common issue and it’s not tied to any plugin or WordPress itself, it’s something directly related with a server component, the cURL library, so it can affect to any web software using cURL.

In this article I’m going to explain you a few things that hopefully will help you to understand what’s the issue and things that you may check in order to fix it.

But what the hell is cURL?

cURL LogoWhen talking about WordPress, cURL is a PHP library that helps WordPress to communicate with other sites. Being a PHP library means that if you’re using an obsolete PHP version (anything older than PHP 7.0) you’re for sure also using an obsolete cURL version. So the first thing you need to do if you’re having issues with cURL is to upgrade your PHP version to at least 7.0.x or the latest PHP 7.x stable release.

Note that on some server setups (e.g. cheap shared hosting) selecting a newer PHP version to run your site doesn’t necessarily means that you’re going to use a recent cURL version.

To be clear, I would recommend you to ensure that your site meet actual requirements for secure connections. Your server must be able to perform connections using SHA-2 and TLS 1.2, as this is required for third-party services as PayPal, Stripe, Authorize.net and many others that are using the HTTPS protocol to ensure privacy in connections to their services. So make a favor to yourself and ensure that your site is hosted on a server with at least cURL version 7.34.0 or higher, a recent build of OpenSSL/1.0.1 or higher (another library) and also a recent version of PHP, currently 7.1 is the recommended choice.

I have an up to date PHP, cURL and OpenSSL but still getting cURL error 28

The cURL error 28 literally means that your site tried to perform a request using the cURL library but the specified timeout period was reached before getting a successful result for the request.

In general terms, this could be caused by a very short timeout time specified for the cURL request or because the server is not able to establish the connection or complete the operation before reaching the timeout for whatever reason.

Things to check in the server

If you already checked that you’re running the recent versions mentioned above. Other common causes at server side for this error are:

  • Issues with the DNS resolving (your server is not able to resolve the IP for the third-party domain or at least not in time).
  • Firewalls or security modules (e.g. mod_security ) blocking the outgoing request.
  • Your host is not able to “talk” with the third-party server due to unavailable required protocols. This can occur if the server has a recent cURL/OpenSSL but it’s not correctly configured to use TLS 1.2 as SSL procotol.
  • Network issues (something at network level prevents your server to reach the third-party server).
  • Your server is blocking connections to your own site. Some hosts don’t allow sites hosted in their servers to connect their self using cURL. It’s very common for a WordPress site to perform connections to itself (e.g. AJAX requests) and I can’t see any valid reason to apply this blocking in a server. But for some reason there are many hosts doing this (specially in cheap hosting plans). So you will want to contact with your host support about this and request to remove that limitation if it’s set in the server.
  • Something in the site setup disabled certificate validation and the host doesn’t allow requests without certification validation.

These are only a few things, the most common causes, your server admin should be able to check anything that could cause cURL to fail at server side.

Also checking the PHP and web server (Apache, nginx, etc) error logs can probably give you additional information about what’s going on. If you don’t have access to these logs ask for them to your server admin.

Things to check in WordPress when cURL fails

First thing I would recommend you to do is to enforce the certificate validation by using the https_local_ssl_verify filter in your theme’s functions.php file or a custom functionality plugin:

If the above doesn’t help try setting a higher timeout value. By default WordPress set the timeout value in wp-includes/class-wp-http-curl.php to 5 seconds and the same value is also set in wp-includes/class-http.php that is a newer class for making HTTP requests that can use also cURL if it’s present in the server.

You may think that 5 seconds is a very short time, but in terms of doing an HTTP request 5 seconds should be enough in most cases.

Anyway this value can be overridden using a few WordPress core filers: http_api_curl, http_request_timeout or http_request_args. Below you can find an example of how to set the timeout value to 30 seconds using all these filters.

To troubleshoot the issue you can temporarily set the timeout value to a crazy high value like 120 seconds just to see if the HTTP request is completed at some point… Bear in mind with this value in the timeout you will need to wait up to 2 minutes to see the result.

Note that the correct value for the timeout will be directly related to the amount of data that you’re sending in the cURL request. For example, if you’re sending a small single file, that will require a low timeout value, if you’re sending a very big file or multiple files, you will need to set a higher timeout value.

You can also use the Core Control plugin to monitor all outgoing connections done by WordPress providing you a lot of useful information like the time taken for the request and even the response headers and body. It’s a very handy companion for the troubleshooting!

Another WordPress plugin that can help you is TLS 1.2 Compatibility Test, with this plugin you can test your server compatibility for TLS 1.2 directly in your WP dashboard.

Finally, don’t forget to check this post comments, some users posted their own solution for specific scenarios that maybe could help in your case too.

The third-party side of things

If your site is trying to connect to a third-party server, you need to keep in mind also that you don’t have any control over the third-party server, and they could have also issues at their side or things (e.g. server busy or network issues) or they could be blocking your requests… So if all other fails you should start considering this also and try to contact with the third-party service for assistance.

And… That’s all Folks! ;)

Estimated reading time: 1 min

In this article

  • 1. How to fix it ?

This quick article helps your solve a  cURL error 28 displayed in your WordPress admin :

cURL error 28: Connection timed out after n milliseconds

or

cURL error 28: Operation timed out after n milliseconds with 0 out of 0 bytes received

This problem is a very common server related issue. In most of the cases not created by a particular theme or plugin, nor by WordPress.

How to fix it ?

The first thing to do is to update your WordPress to the latest version if not already done.

Then if the problem is still there, contact your hosting company and ask the hosting support team to check the following points :

  • Make sure your server is running a recent version of PHP and the cURL library.
  • Try to increase your Server Memory Limits settings.
  • The cURL error can be a dns related issue. Your hosting company might need to switch dns configuration to OpenDNS : https://www.howtogeek.com/164981/how-to-switch-to-opendns-or-google-dns-to-speed-up-web-browsing/
  • Ask your host if there is some limitation with wp-cron, or if loopback is disabled.
  • Ask your host if there a firewall or security modules (e.g. mod_security ) that could block the outgoing cURL requests.

You can also install the Query Monitor plugin and check the status of the HTTP API Calls in the admin page where the error is displayed.

Was this article helpful?

Like 3 Dislike 3

ochibka-v-wordpress-001Приветствуем вас! Вы видите ошибку cURL 28: Превышено время ожидания соединения на вашем сайте WordPress? Ошибка cURL 28 — распространенная проблема WordPress REST API, которая может повлиять на производительность вашего веб-сайта и привести к его непредсказуемому поведению.

В этой статье мы покажем вам, как легко исправить проблему cURL error 28 на вашем веб-сайте WordPress.

Что такое cURL в WordPress?

CURL — это программная утилита, используемая WordPress и многими другими веб-приложениями для отправки и получения запросов данных с использованием URL-адресов.

WordPress использует cURL для обработки нескольких запросов API. Он доступен как расширение языка программирования PHP, и ваша хостинговая компания WordPress позаботится об этом.

Библиотека cURL играет решающую роль в том, как WordPress работает за кулисами. Если он не настроен должным образом, ваш веб-сайт не будет работать должным образом.

Что вызывает ошибку cURL 28 в WordPress?

Неспособность своевременно ответить на запросы данных сервера вызывает ошибку 28 cURL в WordPress.

WordPress использует REST API (метод программирования) для отправки и получения запросов данных. Если время ожидания этих запросов истекло, вы увидите это как критическую проблему в отчете о работоспособности сайта с заголовком «Ошибка REST API».

Расширение ошибки покажет вам дополнительную информацию, включая сообщение об ошибке:

Error: cURL error 28: Operation timed out after x milliseconds with x bytes received (http_request_failed)

Вы также можете увидеть другую связанную проблему с заголовком «Ваш сайт не может выполнить запрос обратной связи». В нем будет аналогичное сообщение об ошибке со следующим описанием.

«Запрос обратной связи к вашему сайту не удался, это означает, что функции, использующие их, в настоящее время не работают должным образом».

Что может вызвать тайм-аут cURL?

Ряд сценариев может вызвать тайм-аут cURL в WordPress:

  • Например, плагин брандмауэра WordPress может блокировать запрос REST API, считая его подозрительным действием.
  • Если ваш DNS-сервер работает некорректно, это также может вызвать сбой HTTP-запросов и вызвать ошибку тайм-аута cURL в WordPress.
  • Плохо настроенный хостинг-сервер может просто иметь очень низкий порог тайм-аута, что может помешать правильной работе определенных процессов WordPress.

Давайте посмотрим, как устранить и исправить данную проблему.

1. Временно отключите брандмауэр WordPress

Если вы используете брандмауэр WordPress или плагин безопасности, временно отключите его.

ochibka-v-wordpress-01

После этого вам нужно посетить страницу отчета о работоспособности сайта WordPress, чтобы узнать, решена ли ваша проблема.

Если да, то вам нужно проверить журналы брандмауэра WordPress, чтобы узнать, какие запросы API были заблокированы. Это либо определит источник проблемы, либо вы можете настроить параметры брандмауэра, чтобы не блокировать законные запросы API.

2. Отключите все плагины WordPress

Плагины WordPress создают собственные запросы API для отправки и получения данных. Если эти вызовы слишком часты или для выполнения требуется слишком много времени, это может вызвать ошибку cURL в отчете о работоспособности вашего сайта.

Самый простой способ выяснить это — отключить все плагины WordPress. Просто перейдите на страницу «Плагины»-«Установленные» и выберите все плагины.

ochibka-v-wordpress-02

После этого щелкните раскрывающееся меню «Массовые действия», чтобы выбрать «Деактивировать», а затем нажмите кнопку «Применить».

Теперь вы можете посетить отчет о работоспособности сайта, чтобы узнать, исчезла ли проблема. Если это устранило проблему, вы можете активировать свои плагины один за другим, пока проблема не появится снова.

Это поможет вам найти плагин, который может вызывать проблему.

3. Убедитесь, что ваш хостинг-сервер использует новейшее программное обеспечение

Следующий шаг — убедиться, что ваш хостинг-сервер WordPress использует последние версии PHP, библиотеки cURL и OpenSSL.

Вы можете проверить это, просмотрев вкладку системной информации на странице «Инструменты»-«Здоровье сайта».

ochibka-v-wordpress-03

Просто перейдите на вкладку «Информация» и разверните раздел «Сервер». Отсюда вы можете получить информацию о программном обеспечении, установленном на вашем хостинг-сервере WordPress.

ochibka-v-wordpress-04

В идеале ваш сервер должен использовать PHP 7.4.13 или выше, curl 7.74.0 или выше и OpenSSL 1.1.1 или выше.

Если это не так, вам необходимо связаться с вашей хостинговой компанией и попросить их обновить программное обеспечение для вашей учетной записи хостинга.

4. Устранение проблем с небезопасным контентом SSL

Если ваш сайт использует HTTPS / SSL, но он не настроен должным образом, это также может привести к тому, что ваш веб-сервер заблокирует небезопасные запросы cURL.

Точно так же, если ваш веб-сайт не использует HTTPS / SSL, но он сделал вызов API с использованием URL-адреса HTTP, то эти запросы тоже не будут выполнены, и вместо этого вы можете увидеть следующую ошибку cURL:

Ошибка: ошибка cURL 7: не удалось подключиться к порту localhost 443: в соединении отказано (http_request_failed)

Чтобы исправить это, вы можете попросить своего хостинг-провайдера переустановить сертификат SSL для вашего сайта.

5. Обратитесь за помощью к поставщику услуг хостинга

Если описанные выше действия не помогли устранить ошибку cURL 28 то, проблема, скорее всего, связана с средой хостинга.

Есть много факторов, которые могут контролироваться и исправляться только вашей хостинговой компанией. Например, если их DNS-серверы не могут своевременно разрешать запросы, это приведет к тайм-ауту запросов cURL.

Другой сценарий может заключаться в более медленном подключении или сетевых проблемах с вашим хост-сервером.

Просто отправьте им запрос в службу поддержки с подробными сведениями об ошибке, и их технический персонал сможет устранить неполадки и применить исправление для ее решения. Ну что, у нас на этом все. Всем пока!

С уважением Вячеслав и Валерия!

Понравился материал? Поделитесь с друзьями!

Интересное на блоге

Image credits : pexels.com

This quick article helps your solve a  cURL error 28 displayed in your WordPress admin :

cURL error 28: Connection timed out after n milliseconds

or

cURL error 28: Operation timed out after n milliseconds with 0 out of 0 bytes received

This problem is a very common server related issue. In most of the cases not created by a particular theme or plugin, nor by WordPress.

How to fix it ?

The first thing to do is to update your WordPress to the latest version if not already done.

Then if the problem is still there, contact your hosting company and ask the hosting support team to check the following points :

  • Make sure your server is running a recent version of PHP and the cURL library.
  • Try to increase your Server Memory Limits settings.
  • The cURL error can be a dns related issue. Your hosting company might need to switch dns configuration to OpenDNS : https://www.howtogeek.com/164981/how-to-switch-to-opendns-or-google-dns-to-speed-up-web-browsing/
  • Ask your host if there is some limitation with wp-cron, or if loopback is disabled.
  • Ask your host if there a firewall or security modules (e.g. mod_security ) that could block the outgoing cURL requests.

You can also install the Query Monitor plugin and check the status of the HTTP API Calls in the admin page where the error is displayed.


If you are experiencing this issue or other ones when updating your theme, we have gathered a list of common problems ( with solutions ) that can occur when updating your theme.

Did this answer your question?


Thanks for the feedback

There was a problem submitting your feedback. Please try again later.

Last updated on January 11, 2021

If you see this error message displayed in your WordPress admin, it means something is preventing your emails to be sent. You may notice the sending is paused or the automated newsletters are not being sent.

cURL error 28: Connection timed out after X milliseconds.

or

cURL error 28: Operation timed out after X milliseconds with 0 out of 0 bytes received.

This is a common issue and it’s not tied to any plugin or WordPress itself. It’s something directly related to a server component, the cURL library, and it affects any web software using cURL.

Here’s what you can do and check in order to fix it:

Wise Builds cURL Options plugin

You can install this plugin, which allows configuration and testing of cURL connection options for individual services.

Then go to WordPress dashboard > Settings > cURL Options and click on the «Add Rule» button twice to create two rules:

Host Protocol Option Value
your website’s URL (i.e.: mailpoet.com) https CURLOPT_TIMEOUT 20 or 30
bridge.mailpoet.com https CURLOPT_TIMEOUT 20 or 30

After you’ve done it, check if the message is gone and sending has been resumed.


Contact your hosting company

If using the plugin doesn’t fix the issue, we recommend contacting your hosting company and ask their support team to check the following points :

  • Make sure your server is running a recent version of PHP and the cURL library;
  • Try to increase your Server Memory Limits settings;
  • Ask your host if there is some limitation with wp-cron, or if loopback is disabled;
  • Ask your host if there a firewall, CDN, or security modules (e.g. mod_security) that could block the outgoing cURL requests.

Did this answer your question?


Thanks for the feedback

There was a problem submitting your feedback. Please try again later.

Last updated on April 12, 2022

  • Documentation
  • Troubleshoot / Extend
  • How to fix a “cURL error 28: Connection timed out” in WordPress

Curl Error 28 WordPress

This quick article helps you solve a cURL error 28 in your WordPress site.

cURL error 28: Operation timed out after n milliseconds

or:

cURL error 28: Operation timed out after 30001 milliseconds with 0 bytes received

This problem is a very common server-related issue. In most cases not created by a particular theme or plugin, nor by WordPress.

How to fix it?

The first thing to do is to update your WordPress to the latest version if not already done.

Then if the problem is still there, contact your hosting company and ask the hosting support team to check the following points :

  • Make sure your server is running a recent version of PHP and the cURL library.
  • Try to increase your Server Memory Limit settings.
  • The cURL error can be a DNS related issue. Your hosting company might need to switch DNS configuration to OpenDNS: https://www.howtogeek.com/164981/how-to-switch-to-opendns-or-google-dns-to-speed-up-web-browsing/
  • Ask your host if there is some limitation with wp-cron, or if loopback is disabled.
  • Ask your host if there a firewall or security modules (e.g. mod_security ) that could block the outgoing cURL requests.

You can also install the Query Monitor plugin and check the status of the HTTP API Calls on the admin page where the error is displayed.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Curl error message php
  • Curl error limit reached 100 consecutive messages printed
  • Curl error handler
  • Curl error codes
  • Curl error code 28 fivem

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии