Php остановить все скрипты

Как остановить скрипт PHP, работающий на фоне

но теперь я хочу остановить это. Он отправляет сотни писем в мой Gmail a / c. Это на веб-сервере, где я не могу перезапустить его, чтобы убить процесс.

Есть ли способ выполнить другой файл, чтобы убить процесс или как мне это сделать?

Solutions Collecting From Web of «Как остановить скрипт PHP, работающий на фоне»

Если у вас нет доступа к оболочке, то единственный способ – попросить администратора сервера убить процесс.

При этом существует простой способ настроить сценарий и разрешить его отмену из любого другого скрипта на том же сервере, как показано ниже:

 // optional cleanup/remove file after the completion of the loop unlink(sys_get_temp_dir().'/myscriptcancelfile'); // To cancel/exit the loop from any other script on the same server file_put_contents(sys_get_temp_dir().'/myscriptcancelfile','stop'); ?> 

Я предполагаю, что у вас нет доступа к оболочке. Я подозреваю, что самый простой способ – связаться с администратором и перезапустить Apache. Они не хотят, чтобы этот бег больше, чем вы.

Один из вариантов мог бы попытаться убить все процессы Apache с помощью PHP. Он отправит сигнал об удалении всем процессам Apache, за исключением того, на котором он работает. Это может работать, если процесс Apache работает под общим процессом без setuid (). Попытайтесь на свой страх и риск.

Следующее остановит фоновый процесс (PHP):

sudo service apache2 stop 

Чтобы снова запустить apache:

sudo service apache2 start 

Чтобы просто перезапустить apache:

sudo service apache2 start 

Если вы начали использовать его в фоновом режиме, используйте ps aux | grep time.php ps aux | grep time.php чтобы получить PID. Тогда просто kill PID . Если процесс запущен на переднем плане, используйте его, чтобы прервать его.

Если процесс начался в Apache, перезапустите Apache (перезапуск /etc/init.d/apache2 для Debian). Если процесс начался с CGI-подобного сервера, перезапустите сервер.

Чтобы остановить выполнение скриптов php, вы можете просто ввести следующую команду в своем терминале. Это запустит службу Apache. (окончательный перезапуск службы php).

sudo service apache2 restart 

Возможно, вы захотите включить таймаут в свои скрипты в будущем.

Вы можете убить процесс apache. Попробуйте запустить что-то вроде apachectl stop а затем apachectl start начнет его восстановление. Это убьет ваш сервер в течение определенного периода времени, но также будет следить за тем, чтобы все процессы, зависящие от этого скрипта, исчезли.

  • Установка pThreads в Windows
  • Горизонтальное масштабирование: маршрутизация пользовательских поддоменов между серверами
  • Перенаправить HTTPS на HTTP, если параметр querystring отсутствует через htaccess
  • Оптимизация сайтов, основанных на коханах, для скорости и масштабируемости
  • SQL не создает ничего в базе данных
  • PDO :: query vs. PDOStatement :: execute (PHP и MySQL)
  • Аутентификация против ldap с использованием PHP, активного каталога при использовании IE / Firefox
  • Magento Admin> Система> Конфигурация> Дополнительно> Система – Неустранимая ошибка
  • Отправка сообщений с php на java
  • PHP и MySQL Выберите одно значение
  • как пройти поездку на php.ini
  • PHP, jQuery, Ajax, отправлять поля ввода HTML с кодом поля вложения не работает
  • Использование imagejpeg для сохранения и отображения файла изображения
  • Ошибка субдомена 500 Laravel
  • Обратный preg_replace
Читайте также:  Python import module as dict

Источник

exit

Прекращает выполнение скрипта. Функции отключения и деструкторы объекта будут запущены, даже если была вызвана конструкция exit .

exit — это конструкция языка, и она может быть вызвана без круглых скобок, если не передаётся параметр status .

Список параметров

Если status задан в виде строки, то эта конструкция выведет содержимое status перед выходом.

Если status задан в виде целого числа ( int ), то это значение будет использовано как статус выхода и не будет выведено. Статусы выхода должны быть в диапазоне от 0 до 254, статус выхода 255 зарезервирован PHP и не должен использоваться. Статус выхода 0 используется для успешного завершения программы.

Возвращаемые значения

Функция не возвращает значения после выполнения.

Примеры

Пример #1 Пример использования exit

$filename = ‘/path/to/data-file’ ;
$file = fopen ( $filename , ‘r’ )
or exit( «Невозможно открыть файл ( $filename )» );

Пример #2 Пример использования exit со статусом выхода

//обычный выход из программы
exit;
exit();
exit( 0 );

//выход с кодом ошибки
exit( 1 );
exit( 0376 ); //восьмеричный

Пример #3 Функции выключения и деструкторы выполняются независимо

class Foo
public function __destruct ()
echo ‘Деинициализировать: ‘ . __METHOD__ . ‘()’ . PHP_EOL ;
>
>

function shutdown ()
echo ‘Завершить: ‘ . __FUNCTION__ . ‘()’ . PHP_EOL ;
>

$foo = new Foo ();
register_shutdown_function ( ‘shutdown’ );

exit();
echo ‘Эта строка не будет выведена.’ ;
?>

Результат выполнения данного примера:

Завершить: shutdown() Деинициализировать: Foo::__destruct()

Примечания

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.

Замечание:

Эта языковая конструкция эквивалентна конструкции die() .

Смотрите также

User Contributed Notes 21 notes

If you want to avoid calling exit() in FastCGI as per the comments below, but really, positively want to exit cleanly from nested function call or include, consider doing it the Python way:

define an exception named `SystemExit’, throw it instead of calling exit() and catch it in index.php with an empty handler to finish script execution cleanly.

// file: index.php
class SystemExit extends Exception <>
try /* code code */
>
catch ( SystemExit $e ) < /* do nothing */ >
// end of file: index.php

// some deeply nested function or .php file

if ( SOME_EXIT_CONDITION )
throw new SystemExit (); // instead of exit()

jbezorg at gmail proposed the following:

if( $_SERVER [ ‘SCRIPT_FILENAME’ ] == __FILE__ )
header ( ‘Location: /’ );

?>

After sending the `Location:’ header PHP _will_ continue parsing, and all code below the header() call will still be executed. So instead use:

if( $_SERVER [ ‘SCRIPT_FILENAME’ ] == __FILE__ )
header ( ‘Location: /’ );
exit;
>

A side-note for the use of exit with finally: if you exit somewhere in a try block, the finally won’t be executed. Could not sound obvious: for instance in Java you never issue an exit, at least a return in your controller; in PHP instead you could find yourself exiting from a controller method (e.g. in case you issue a redirect).

Читайте также:  Python pyodbc windows authentication

echo «testing finally wit exit\n» ;

exit;
> catch( Exception $e ) echo «catched\n» ;
> finally echo «in finally\n» ;
>

echo «In the end\n» ;
?>

This will print:

testing finally wit exit
In try, exiting

Don’t use the exit() function in the auto prepend file with fastcgi (linux/bsd os).
It has the effect of leaving opened files with for result at least a nice «Too many open files . » error.

Beware if you enabled uopz extension, it disables exit / die() by default. They are just «skipped».

Be noticed about uopz (User Operations for Zend) extension of PHP. It disables (prevents) halting of PHP scripts (both FPM and CLI) on calling `exit()` and `die()` by default just after enabling the extension. Therefore your script will continue to execute.

To rich dot lovely at klikzltd dot co dot uk:

Using a «@» before header() to suppress its error, and relying on the «headers already sent» error seems to me a very bad idea while building any serious website.

This is *not* a clean way to prevent a file from being called directly. At least this is not a secure method, as you rely on the presence of an exception sent by the parser at runtime.

I recommend using a more common way as defining a constant or assigning a variable with any value, and checking for its presence in the included script, like:

in index.php:
define ( ‘INDEX’ , true );
?>

in your included file:
if (! defined ( ‘INDEX’ )) die( ‘You cannot call this script directly !’ );
>
?>

BR.

Note, that using exit() will explicitly cause Roxen webserver to die, if PHP is used as Roxen SAPI module. There is no known workaround for that, except not to use exit(). CGI versions of PHP are not affected.

When using php-fpm, fastcgi_finish_request() should be used instead of register_shutdown_function() and exit()

For example, under nginx and php-fpm 5.3+, this will make browsers wait 10 seconds to show output:

echo «You have to wait 10 seconds to see this.
» ;
register_shutdown_function ( ‘shutdown’ );
exit;
function shutdown () sleep ( 10 );
echo «Because exit() doesn’t terminate php-fpm calls immediately.
» ;
>
?>

This doesn’t:

echo «You can see this from the browser immediately.
» ;
fastcgi_finish_request ();
sleep ( 10 );
echo «You can’t see this form the browser.» ;
?>

In addition to «void a t informance d o t info», here’s a one-liner that requires no constant:

To redirect to / instead of dying:

if ( basename ( $_SERVER [ ‘PHP_SELF’ ]) == basename ( __FILE__ )) if ( ob_get_contents ()) ob_clean (); // ob_get_contents() even works without active output buffering
header ( ‘Location: /’ );
die;
>
?>

Doing the same in a one-liner:

A note to security: Even though $_SERVER[‘PHP_SELF’] comes from the user, it’s safe to assume its validity, as the «manipulation» takes place _before_ the actual file execution, meaning that the string _must_ have been valid enough to execute the file. Also, basename() is binary safe, so you can safely rely on this function.

include (‘header.php’);
blah blah blah
if (!$mysql_connect) echo «unable to connect»;
include (‘footer.php’);
exit;
>
blah blah blah
include (‘footer.php’);

Читайте также:  How to Create Dynamic Chart in PHP using Chart.js

These are the standard error codes in Linux or UNIX.

1 — Catchall for general errors
2 — Misuse of shell builtins (according to Bash documentation)
126 — Command invoked cannot execute
127 — “command not found”
128 — Invalid argument to exit
128+n — Fatal error signal “n”
130 — Script terminated by Control-C
255\* — Exit status out of range

When a object is passed as $status and it consists of a __toString() magic method the string value of this method will be used as $status. If the object does not contain a __toString method, exit will throw a catchable fatal error.

>> Shutdown functions and object destructors will always be executed even if exit is called.

It is false if you call exit into desctructor.

Normal exit:
class A
public function __destruct ()
echo «bye A\n» ;
>
>

class B
public function __destruct ()
echo «bye B\n» ;
>
>

// Output:
// bye B
// bye A
?>

// Exit into desctructor:
class A
public function __destruct ()
echo «bye A\n» ;
>
>

class B
public function __destruct ()
echo «bye B\n» ;
exit;
>
>

Calling ‘exit’ will bypass the auto_append_file option.
On some free hosting this risks you getting removed, as they may be using for ads and analytics.

So be a bit careful if using this on the most common output branch.

return may be preferable to exit in certain situations, especially when dealing with the PHP binary and the shell.

I have a script which is the recipient of a mail alias, i.e. mail sent to that alias is piped to the script instead of being delivered to a mailbox. Using exit in this script resulted in the sender of the email getting a delivery failure notice. This was not the desired behavior, I wanted to silently discard messages which did not satisfy the script’s requirements.

After several hours of trying to figure out what integer value I should pass to exit() to satisfy sendmail, I tried using return instead of exit. Worked like a charm. Sendmail didn’t like exit but it was perfectly happy with return. So, if you’re running into trouble with exit and other system binaries, try using return instead.

It should be noted that if building a site that runs on FastCGI, calling exit will generate an error in the server’s log file. This can quickly fill up.

Also, using exit will diminish the performance benefit gained on FastCGI setups. Instead, consider using code like this:

if( /* error case */ )
echo «Invalid request» ;
else /* The rest of your application */
>
?>

I’ve also seen developers get around this issue with FastCGI by wrapping their code in a switch statement and using breaks:

switch( true ) case true :
require( ‘application.php’ );
>

if( $x > $y ) echo «Sorry, that didn’t work.» ;
break;
>

?>

It does carry some overhead, but compared to the alternative, it does the job well.

Источник

Оцените статью