php script timed out before returning headers php

Script timed out before returning headers: index.php

Script timed out before returning headers is one of the most common errors you will see while developing web applications, or if you are a system administrator. It can be caused by many different things, but it’s always related to timeout configurations (or a very bad programmed script).

How to fix Script timed out before returning headers error?

First: Script timed out before returning headers is just a normal issue on web development, and it can affect many kind of programming languages.

We will focus on php timeous, that are often the cause of the issue, however if your programming language is python, perl or another you should explore the error from that point.

As we said before, there are a few reasons to explain this issue, and it’s related to the timeouts set in various web services like: Apache, PHP and MySQL. Let’s start exploring each one of the options.

Apache Timeouts

Where can I find the TimeOut variable in Apache service configuration? On cPanel servers you can modify and see the current value in

WHM > Apache Configuration > Global Configuration area.

There is a chance you have a very low timeout and this may be causing the famous “Script timed out before returning headers” issue. Try raising the value up to 60 or 120 for example.

You can also modify the same variable by editing /usr/local/apache/conf/httpd.conf

After you are done editing, save and run this commands to apply the changes:

MySQL timeouts

Another reason for this error can be low MySQL timeouts, many times I’ve seen MySQL queries requiring more execution time than the one set in the MySQL configuration, it’s not common at all, but on badly programmed queries, or huge databases it can happen.

In this scenario “Script timed out before returning headers” error may appear together with anoter one: “MySQL server has gone away” may appear. In order to solve it, you just need to adjust the wait_timeout variable in /etc/my.cnf file:

Then restart MySQL to apply changes:

PHP timeouts

When your script timeout before completing its execution one of the varibles to check is max_execution_time in PHP server configuration. On cPanel servers you can find this variable at:

WHM > PHP Configuration Editor > Options & Information > max_execution_time

Or you can also edit using the terminal:

Restart to apply changes:

If you don’t have access to the shell, you may get the max_execution_time value using a simple PHP script:

Then you can ask your hosting provider to raise the limit a little bit more for your account.

FastCGI / mod_fcgid timeouts (running with Apache)

FastCGI is an alternative way to execute PHP scripts than using mod_php (the traditional/default way to do it with Apache web server). mod_fcgid is responsible for executing PHP scripts if you are using this FastCGI configuration, and is also the one you should look at when you are facing this kind of timeout issues.

On old mod_fcgid configurations you may find this variables, be sure to set each one high as you see it here, or raising up to 3600.

On newer versions of mod_fcgid variables are as you see below:

This variables must be placed inside your Apache configuration. After you are done, restart httpd to apply changes:

PHP-FPM timeouts (running with Nginx)

PHP-FPM means FastCGI Process Manager, and it’s an alternative way to execute PHP scripts, especially high traffic websites.

How can I increase PHP execution time if I’m using PHP-FPM?

First: if you are using php-fpm there is a highly chance that you are not using any control panel at all, and that your server is just a plain Linux one.

Second: find your www.conf file and set this variable up to 30, 60 or 120, depending on your needs. On CentOS systems you can find it at /etc/php-fpm.d/www.conf

Edit the file and configure this variable:

This variable sets the timeout for serving a single request after which the worker process will be killed. Set to 0 for unlimited time or up to 30, 60 or more as you need.

Edit your traditional php.ini file, usually located at /etc/php.ini and also raise max_execution_time as we explained before at the beginning of this article.

Finally let’s move to Nginx configuration, it’s recommended to raise a little bit the fastcgi_read_timeout variable, this variable is responsible for reading a response from the FastCGI server.

Edit your nginx configuration file

Find your PHP-FPM configuration and set/add this variable:

It should look like this:

Conclusion

As we’ve seen on this article, Script timed out before returning headers is a very usual error while developing or troubleshooting website errors, it can affect any kind of programming languages, not only PHP.

However, on this time we just focused on PHP, which is the most widely used language nowadays. Remember this error is always related to timeouts, explore the timeouts of your web services and you’ll find a fix for sure.

Источник

«End of script output before headers» in Apache + PHP

UPDATE: This issue was caused by the server request timing out before the script completed.*

I have legacy code running on a shared LAMP host (nearlyfreespeech.net), and I recently added a new script that refuses to work in production.

According to other StackOverflow posts, this error message is usually due to a file permissions error. However, the file permissions on the new script are the same as all the others.

Here are the relevant file permissions:

With these include() heirarchies:

All requests are for switch.php and include a parameter value causing either auth/cloudsaves.php or auth/cloudsaves.2.php to be included.

In my local test environment everything works just fine. In production when I use the parameter that causes switch.php to include the cloudsaves.2.php script I get the error.

I’ve tried changing the group and permissions on rumpus_migration.php and cloudsaves.2.php to exactly match other files that are properly being included by the parent switch.php script, always with the same outcome. This new script ( cloudsaves.2.php ) is the only script included by switch.php that itself includes another script.

I’m not familiar with Apache or PHP, and the production code is on a shared host where I have extremely limited admin access. The fact that the code works locally but not in production makes it seem that a permissions issue is a likely culprit, but I don’t know how to move forward since none of the working permissions options seem to fix it.

Источник

Problems with script php to execute correctly «End of script output before headers»

I have a script programmed in PHP that makes a query to an MYSQL view that is already prepared to display information. The view is somewhat «complicated» because it makes many queries to obtain the information, it takes about 52 seconds to obtain the information when it is the «first time» that it is consulted.

Well, when I check the view using PHP, the first time, I can’t seem to finish executing the script and I get the message on the screen:

«Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root @ localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log. «

Later if I «refresh» the site again, it takes a little longer and now if the script finishes executing. It seems as if part of the query work the server had it in a job cache and then when you call it again it does it very fast.

I have my memory and PHP execution parameters very high to try to avoid that the script cannot be finished with PHP but it still has a hard time finishing. Checking the error logs I found this:

2021-02-11 14:16:08 Error 189.178.185.40 End of script output before headers: emptiedGeneralExcelNuevo1.php

Does anyone think of how to get the script to finish the first time it is called?

Источник

Выполнение php скрипта в centos

Добрый день. Пытаюсь запустить тяжелый php скрипт в centos на vds тремя способами: через Shell ISP Manager, SSH и непосредственно через веб с помощью nginx. Скрипт представляет собой парсер объемного excel файла. Если в файле содержится

50 000 строк, то скрипт отлично отрабатывает, как через веб, так и шелл. Но если файл становится тяжелее, то nginx отдает 500 ошибку с логами: [cgi:warn] [pid xxx] [client xxx] AH01220: Timeout waiting for output from CGI script /var/www/php-bin-isp-php55/xxx/php [cgi:error] [pid xxx] [client xxx] Script timed out before returning headers: php а шелл и ssh просто висят и ничего не происходит. Как понять, в чем причина и почему не отрабатывает скрипт? Какие логи посмотреть, конфиги ковырять? Спасибо.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

Посмотри потребление ресурсов процессом пхп, который выполняет скрипт. Может быть он тупо уходит в бесконечный цикл.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

php.ini ковыряй на предмет таймаута выполнения.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

В php.ini стоит max_execution_time = 600; В любом случае, php процесс умирает раньше двух минут. Я правильно понимаю, что править его нужно в etc/php.ini? Если что, под веб в /var/www/php-bin-isp-php55 тоже исправлено.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

Я правильно понимаю, что править его нужно в etc/php.ini?

Это уже зависит от настроек твоего дистрибутива. Иногда делают разные конфиги для cli и mod_php.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

Твоя проблема не в том, что кто-то убивает пхп, а в том, что ты для этой задачи вообще его используешь.
Не используй пхп для парсинга xls(х), у меня от этого брат умер. Поставь gnumeric и дергай его. Просто, быстро, безболезненно.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

Используй вместо xls что-то более подходящее, например csv

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

я бы начала с увеличения уровня ошибок в php.ini 🙂

также можно использовать очереди. напримере, gearman. запустить гирмана, создать воркера, запустить через systemd, а клиента-консюмера через ваш скрипт. теперь вся тяжесть работы ляжет на воркера и не будет зависит от php-скрипта.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

самое разумное, а там и до man-ов рукой подать

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

К сожалению не я решаю, с какими форматами работать. Что юзер грузит, то и парсю.

Если вы о error_reporting, то, естественно, параметр E_ALL. Все равно тишина.

Спасибо, никогда не слышал о таком. Пошел читать мануалы и пробовать. По факту отпишусь.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

плавали-знаем

там ещё куча их: log_errors, display_errors, display_startup_errors

всё надо проверить.

Источник

continue processing php after sending http response

One of solution is to save message to database and make some cron which will be running each minute, but I need to generate response message immediately.

Is there some solution how to send to server http response 200 and than continue executing php script?

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

12 Answers 12

Yes. You can do this:

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

I’ve seen a lot of responses on here that suggest using ignore_user_abort(true); but this code is not necessary. All this does is ensure your script continues executing before a response is sent in the event that the user aborts (by closing their browser or pressing escape to stop the request). But that’s not what you’re asking. You’re asking to continue execution AFTER a response is sent. All you need is the following:

If you’re concerned that your background work will take longer than PHP’s default script execution time limit, then stick set_time_limit(0); at the top.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

If you’re using FastCGI processing or PHP-FPM, you can:

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

I spent a few hours on this issue and I have come with this function which works on Apache and Nginx:

You can call this function before your long processing.

Modified the answer by @vcampitelli a bit. Don’t think you need the close header. I was seeing duplicate close headers in Chrome.

I use the php function register_shutdown_function for this.

Edit: The above is not working. It seems I was misled by some old documentation. The behaviour of register_shutdown_function has changed since PHP 4.1 link link

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

I asked this question to Rasmus Lerdorf in April 2012, citing these articles:

I suggested the development of a new PHP built-in function to notify the platform that no further output (on stdout?) will be generated (such a function might take care of closing the connection). Rasmus Lerdorf responded:

See Gearman. You really really don’t want your frontend Web servers doing backend processing like this.

I can see his point, and support his opinion for some applications/ loading scenarios! However, under some other scenarios, the solutions from vcampitelli et al, are good ones.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

I can’t install pthread and neither the previous solutions work for me. I found only the following solution to work (ref: https://stackoverflow.com/a/14469376/1315873):

I have something that can compressed and send the response and let other php code to execute.

php script timed out before returning headers php. Смотреть фото php script timed out before returning headers php. Смотреть картинку php script timed out before returning headers php. Картинка про php script timed out before returning headers php. Фото php script timed out before returning headers php

There is another approach and its worthwhile considering if you don’t want to tamper with the response headers. If you start a thread on another process the called function wont wait for its response and will return to the browser with a finalized http code. You will need to configure pthread.

Once we execute $continue_processing->start() PHP wont wait for the return result of this thread and therefore as far as rest_endpoint is considered. It is done.

Some links to help with pthreads

in case of php file_get_contents use, connection close is not enough. php still wait for eof witch send by server.

my solution is to read ‘Content-Length:’

Note the «\n» in response to close line, if not the fget read while wait eof.

As you can see this script dosent wait about eof if content length is reach.

I have an important addition to all the other great answers!
TL;DR:
add

In my use case I would like to mark the API Call as «Accepted» and don’t make the client wait for finished processing.

Actually it feels right: The client should stop waiting for answer when it receives the «Connection: close» header, but in fact at least MY php does not send those headers yet. (tested with two different PHP-Servers, and via Browser+Insomnia client each)

There is some special behaviour that flush() would not send the first content if not at least a special amount of bytes were echoed, yet (in my case 1024 bytes). (probably some hotfix in case there is some leading or trailing whitespace in php files which are actually treated like an echo statement or something like that which would prevent later header() statements to take effect.)

To solve the problem one can send 1024 leading whitespace characters which should be ignored by JSON/XML/HTML interpreters.

So the full code looks like this:

(Here is some backup for my arguments, cant find the correct source rn: How to flush output after each `echo` call?)

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *