Друзья, замучил меня CURL. Не знаю почему, но:
1. вообще не влияет установка параметра CURLOPT_TIMEOUT (остается 30 сек, хъотел меньше — никак)
2. Самое главное. Этот TIMEOUT отрабатывает как-то не на открытие одной страницы, а на открытие нескольких страниц суммарно.
Вот пример: если я дергаю _my_GetFileContent_curl много раз, то по истечении 30 секунд после обращения к первому URL выдается ошибка «Fatal error: Maximum execution time of 30 seconds exceeded».
Во-первых не ясно, почему 30, если я устанавливаю 10.
Во вторых не ясно, почему это число (30 сек) работает не как время открытия ОДНОЙ страницы, а фактически как СУММАРНОЕ время работы CURL по всем страницам.
Код:
function _my_GetFileContent_curl($iurl)
{
$vUrl=urldecode($iurl);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, ‘User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0’);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_PROXY, ‘proxy.net.site.ru:8080’);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, ‘user:password’);
$file_content=curl_exec($ch);
$Error=curl_error($ch);
curl_close($ch);
return $file_content;
}
Вот результат работы кода:
echo date(«H:i:s»);
_my_GetFileContent_curl(«http://mysite.ru?param=1»);
echo date(«H:i:s»);
_my_GetFileContent_curl(«http://mysite.ru?param=1»);
echo date(«H:i:s»);
_my_GetFileContent_curl(«http://mysite.ru?param=1»);
echo date(«H:i:s»);
_my_GetFileContent_curl(«http://mysite.ru?param=1»);
echo date(«H:i:s»);
_my_GetFileContent_curl(«http://mysite.ru?param=1»);
echo date(«H:i:s»);
_my_GetFileContent_curl(«http://mysite.ru?param=1»);
echo date(«H:i:s»);
11:34:38
11:34:43
11:34:47
11:34:51
11:34:57
11:35:05
Fatal error: Maximum execution time of 30 seconds exceeded
то есть как видно падает через 30 секунд после ПЕРВОГО обращения, что за бред!?!
I have a script that runs through a list of websites and checks the html code for links….however the script will run for a long time (up to an hour sometimes depending on the amount of sites I tell it to check) and then when it gets to the end I get this error:
Fatal error: Maximum execution time of 30 seconds exceeded…..on line 137
When I go to line 137 it is this code:
$ch = curl_init( $website);
I am not sure what is causing this error. Is it a website is causing the connection to time out or what? If that is the case then how can I make it so if a maximum execution error occurs, the script keeps going on just moves onto the next website? I have pasted the function below.
function getwebpage($userAgent,$website)
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => true, // return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => $userAgent, // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $website);
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;
print($header[0]);
return $header;
}
Open in new window
In this quick article, we’ll explore the different options that allow you to increase the maximum amount of time a script is allowed to run before it’s terminated by the parser in PHP.
What Is the max_execution_time
Directive in PHP?
The max_execution_time
directive sets the maximum amount of time a script is allowed to run before it is terminated. The default is 30 seconds, and you can increase it to a reasonable limit as per your requirements.
More often than not, you will have noticed that if a script takes too long to execute, PHP throws the famous maximum execution time exceeded error:
1 |
Fatal error: Maximum execution time of 30 seconds exceeded |
In most cases, the max_execution_time
directive is not customized, and thus it defaults to 30 seconds, and you could end up with this error.
In the next section, we’ll discuss a couple of different ways to increase the value of the max_execution_time
directive.
How to Increase max_execution_time
in PHP
There are a few different ways to increase the script execution time.
The ini_set
Function
This is one of the easiest ways to increase the value of the max_execution_time
directive. The ini_set
function is used to change the value of the configuration directives that are available in the php.ini configuration file. And thus, we can use it to change the value of the max_execution_time
directive.
To increase the script execution time, you can use the following snippet at the top of your script.
1 |
ini_set('max_execution_time', '300'); |
In the above example, it would set the max_execution_time
directive to 300 seconds.
On the other hand, if you set it to 0, it would allow the script to run for an infinite amount of time. You must be very careful when you exercise this option, and it’s never recommended in production.
The php.ini Configuration File
If you want to increase the value of the max_execution_time
directive globally, you should use this option. Of course, you need permission to change the php.ini file.
Go ahead and locate the php.ini file on your server. If you don’t know how to do it, I explain how to find the php.ini file in another article.
Once you’ve located the php.ini file, open it with your favorite text editor and look for the following line:
1 |
; Maximum execution time of each script, in seconds |
2 |
; https://php.net/max-execution-time |
3 |
; Note: This directive is hardcoded to 0 for the CLI SAPI |
4 |
max_execution_time = 30 |
Change it as per your needs, save it, and restart your web server.
The set_time_limit
Function
Apart from the ini_set
function which we’ve just discussed, there’s also another PHP function which allows you to set the maximum execution time of a script. The set_time_limit
function allows you to set the number of seconds a script is allowed to run.
Let’s quickly look at how the set_time_limit
function works.
As you can see, the set_time_limit
function takes a single argument: the number of seconds. If you set it to 0, a script is allowed to run for an infinite amount of time.
In fact, the set_time_limit
function works a bit differently from the max_execution_time
directive. When the set_time_limit
function is called, it resets the timeout counter to zero. And from there onward, it measures the script execution time which you’ve set with the set_time_limit
function.
Let’s assume that a script is executed for 10 seconds, and then the set_time_limit
function is called to set the script execution time to 30 seconds. In that case, a script would run for a total of 40 seconds before it’s terminated. So if you want to use the set_time_limit
function to set the maximum execution time of a script, you should place it at the top of your script.
Apache Users: The .htaccess File
If you’re using the Apache server to power your website, it provides the .htaccess configuration file, which allows you to set php.ini configuration directives. In this section, we’ll see how you can use the .htaccess file to set the max_execution_time
directive.
First of all, you need to locate the .htaccess file in your project. In most cases, you should be able to find it in the document root of your project. If you can’t find it in the project root, you need to make sure that it’s not hidden by your file manager software, since the dot before the .htaccess file name indicates that it is a hidden file. You can use the show hidden files option in your file manager to see all the hidden files in your document root. If you still can’t find it, you need to create one.
Open the .htaccess file in your favorite text editor and add the following line at the end.
1 |
php_value max_execution_time 300 |
Save it, and you’re done!
Conclusion
Today, we discussed a few different ways to change the value of the max_execution_time
directive in PHP.
Learn PHP With a Free Online Course
If you want to learn PHP, check out our free online course on PHP fundamentals!
In this course, you’ll learn the fundamentals of PHP programming. You’ll start with the basics, learning how PHP works and writing simple PHP loops and functions. Then you’ll build up to coding classes for simple object-oriented programming (OOP). Along the way, you’ll learn all the most important skills for writing apps for the web: you’ll get a chance to practice responding to GET and POST requests, parsing JSON, authenticating users, and using a MySQL database.
Did you find this post useful?
Software Engineer, FSPL, India
I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies.
Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce.
I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!
Почему возникает ошибка
Ошибка maximum execution time появляется когда скрипт работает дольше, чем разрешено в настройках PHP:
<?php
// Устанавливаем максимальное время (1 секунда)
set_time_limit(1);
// Ждём 2 секунды и получаем ошибку
sleep(2);
Результатом работы этого скрипта будет ошибка:
Fatal error:
Maximum execution time of 1 second exceeded in
D:ProgramsOpenServerdomainstest.localindex.php on line 6
Почему скрипт чаще всего выполняется медленно:
- Слишком много вычислений в коде, которые сервер не может выполнить за разрешённое время
- Медленные SQL-запросы
- Медленные внешние запросы к другим сайтам/веб-сервисам
- Бесконечные циклы или рекурсия
Как исправить ошибку
В каждой ситуации решение индивидуальное. Часто проблему можно решить просто увеличив максимально разрешённое время работы скрипта (разрешено не на всех хостингах).
Увеличение времени работы скрипта в .htaccess (указывается в секундах):
php_value max_execution_time 300
В php.ini:
max_execution_time = 300;
Либо напрямую в PHP:
ini_set('max_execution_time', 300);
// Или так
set_time_limit(300);
У функции set_time_limit есть одна особенность — она начинает отсчёт времени работы скрипта с нуля.
Т.е. если время работы изначально было 10 секунд, а через 5 секунд был выполнен код set_time_limit(20);, то в итоге скрипт будет выполняться не более 25 секунд.
Отлов и обработка ошибки
Хоть ошибка и является фатальной, её появление можно отловить и обработать с помощью функции register_shutdown_function():
<?php
// Отключаем вывод текста ошибки на экран
ini_set('display_errors', 0);
register_shutdown_function(function() {
$e = error_get_last();
if($e and $e['type'] == 1) {
echo 'Фатальная ошибка!';
}
});
// Устанавливаем макс время - 1 секунду
set_time_limit(1);
// Ждём 2 секунды и получаем ошибку
sleep(2);
При выполнении этого кода на экран выведется сообщение Фатальная ошибка!.
Единственный нюанс — условие $e[‘type’] == 1 отработает для любых фатальных ошибок, а не только для Maximum execution time.