Computers Windows Internet

Php stop script execution. Background script execution in PHP without crontab. #one. Demonstration of use

Stops execution PHP script and outputs a formatted HTML message.

Analogue of the base PHP functions die(). The difference is that wp_die() outputs a formatted HTML page errors. It is recommended to use this function when you need to completely stop PHP job. It is not recommended to use this function often - try not to show errors to users.

returns

Returns nothing, but terminates PHP.

Usage

wp_die($message, $title, $args); $message (mixed) Error message or full WP_Error class object.
Default: ""$title (string/array/number/object/boolean) Error title. If you use the WP_Error object, then the title will be taken from $data["title"], this parameter can be changed in advance for yourself.
Default: ""$args (string/array)

Various arguments controlling behavior.
Default: no

    response (number)
    HTTP status code. 500 - internal server error. The whole list .
    Default: 500

    back_link (logical)
    Whether or not to display a backlink to the previous page.
    Default: false

  • text_direction (line)
    Text direction: ltr (left to right) or rtl (right to left).
    Default: "ltr"

Examples

#one. Demonstration of use

Using the wp_die() function, let's see what is currently in the $post global variable:

Add_filter("body_class", "add_body_class_cb"); function add_body_class_cb($classes) ( global $post; wp_die("

" var_export($post, true) . "
"); }

#2. Styling the wp_die block

If the site needs to change the design of this block, then you can use the wp_die_handler hook:

500); $r = wp_parse_args($args, $defaults); $have_gettext = function_exists("__"); if (function_exists("is_wp_error") && is_wp_error($message)) ( if (empty($title)) ( $error_data = $message->get_error_data(); if (is_array($error_data) && isset($error_data[" title"])) $title = $error_data["title"]; ) $errors = $message->get_error_messages(); switch (count($errors)) ( case 0: $message = ""; break; case 1 : $message = ""; break; default: $message = "

    \n\t\t
  • ".join("
  • \n\t\t
  • ", $errors). "
  • \n\t
"; break; ) ) elseif (is_string($message)) ( $message = ""; ) if (isset($r["back_link"]) && $r["back_link"]) ( $back_text = $have_gettext? __("" Back") : "" Back"; $message .= "\n

$back_text

"; ) if (! did_action("admin_head")) : if (!headers_sent()) ( status_header($r["response"]); nocache_headers(); header("Content-Type: text/html; charset= utf-8"); ) if (empty($title)) $title = $have_gettext ? __("WordPress › Error") : "WordPress › Error"; $text_direction = "ltr"; if (isset($r[ "text_direction"]) && "rtl" == $r["text_direction"]) $text_direction = "rtl"; elseif (function_exists("is_rtl") && is_rtl()) $text_direction = "rtl"; ?> > <?php echo $title ?>

The code wp die : wp-includes/functions.php WP 5.2.2

$args); ) elseif (is_int($title)) ( $args = array("response" => $title); $title = ""; ) if (wp_doing_ajax()) ( /** * Filters the callback for killing WordPress execution for Ajax requests.* * @since 3.4.0 * * @param callable $function Callback function name.*/ $function = apply_filters("wp_die_ajax_handler", "_ajax_wp_die_handler"); ) elseif (wp_is_json_request()) ( /** * Filters the callback for killing WordPress execution for JSON requests. * * @since 5.1.0 * * @param callable $function Callback function name. */ $function = apply_filters("wp_die_json_handler", "_json_wp_die_handler"); ) elseif (wp_is_jsonp_request() ) ( /** * Filters the callback for killing WordPress execution for JSONP requests. * * @since 5.2.0 * * @param callable $function Callback function name. */ $function = apply_filters("wp_die_jsonp_handler", "_jsonp_wp_die_handler") ; ) elseif (defined("XMLRPC_REQUEST") && XMLRPC_REQUEST) ( /** * Filters the callback for killing WordPress executio n for XML-RPC requests. * * @since 3.4.0 * * @param callable $function Callback function name. */ $function = apply_filters("wp_die_xmlrpc_handler", "_xmlrpc_wp_die_handler"); ) elseif (wp_is_xml_request() || isset($wp_query) && (function_exists("is_feed") && is_feed() || function_exists("is_comment_feed") && is_comment_feed() || function_exists("is_trackback") && is_trackback()) ) ( /** * Filters the callback for killing WordPress execution for XML requests. * * @since 5.2.0 * * @param callable $function Callback function name. */ $function = apply_filters("wp_die_xml_handler", "_xml_wp_die_handler") ; ) else ( /** * Filters the callback for killing WordPress execution for all non-Ajax, non-JSON, non-XML requests. * * @since 3.0.0 * * @param callable $function Callback function name. */ $function = apply_filters("wp_die_handler", "_default_wp_die_handler"); ) call_user_func($function, $message, $title, $args); )

8 years ago

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()

?>

10 years ago

Jbezorg at gmail proposed the following:


header("Location: /");

?>

After sending the `Location:" PHP header _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;
}

?>

10 years ago

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!");
}
?>

B.R.

4 years ago

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).

Here follows the POC:

echo "testing finally wit exit\n" ;

try(
echo "In try, exiting\n" ;

exit;
) catch(Exception $e ) (
echo "catch\n" ;
) finally (
echo "finally\n" ;
}

echo "In the end\n" ;
?>

This will print:

testing finally wit exit
In try, exiting

1 year ago

>> 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
{
{
echo "bye A\n" ;
}
}

class B
{
public function __destruct()
{
echo "bye B\n" ;
}
}

$a = new A ;
$b = new B ;
exit;

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

// Exit into destructor:
class A
{
public function __destruct()
{
echo "bye A\n" ;
}
}

class B
{
public function __destruct()
{
echo "bye B\n" ;
exit;
}
}

$a = new A ;
$b = new B ;

//Output:
// bye B
?>

17 years ago

If you are using templates with numerous includes then exit() will end you script and your template will not complete (no, , etc...). Rather than having complex nested conditional logic within your content, just create a "footer.php" file that closes all of your HTML and if you want to exit out of a script just include() the footer before you exit().

include("header.php");
blah blah blah
if (!$mysql_connect) (
echo "unable to connect";
include("footer.php");
exit;
}
blah blah blah
include("footer.php");

16 years ago

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.

3 years ago

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



Placing it at the beginning of a PHP file will prevent direct access to the script.

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.

7 years ago

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.";
?>

They puzzled me here to write a demon in PHP. Those. a script that will perform certain actions a specified number of times in a specified number of hours at a random time (always random), and all this without using cron "a.

Before that, I never bothered, but then after setting the task, I began to think that it was impossible, that the php script should be called by the browser ... well, the task was set, it must be performed.

First thought is to disable script execution time limit. Forbidden by the host.

The second thought is to repeat the Ajax request periodically (yes, at least once per second) using Javascript. - not possible (requirement of the customer).

It turned out, in fact, that the browser should not be open, and crons should not be used, and the script should work independently of the user, indefinitely. Naturally, it should load the system at least.

1. Pack of cigarettes, night, Google, docks, books, manuals….
goto 1…

At the output I get:
Task_1:
Implement a script execution time generator based on the given number of times and the number of hours. Store these times somewhere.

Task_2:
Work after closing the browser

Task_3:
Don't crash after script execution time limit expires

Task_4:
Take action at the right time.

So…
We write the initial data in the config:

session_start(); // Session start $num_starts = 120; // Number of script runs per time interval $hours = 1; // Number of hours to run the script $num_starts times. $time_sec = $hours*3600; // Number of seconds in the run cycle $time_to_start = array(); // Actually, an array with launch times ignore_user_abort(1); // Ignore browser disconnect

Next, we write a function that will help us generate start times.
In it, we generate a random number from 0 to the number of seconds in the original interval.
/****** * @desc Generate an interval between runs. */ function add_time2start() ( global $time_sec, $time_to_start; $new_time = time()+rand(0, $time_sec); if (!in_array($new_time, $time_to_start)) ( // If there is no such time in the array - add $time_to_start = $new_time; ) else ( add_time2start(); // If such time already exists, regenerate. ) )

$k = 1; if ($_SESSION["num_st"] == "" || $_SESSION["num_st"][$num_starts-1]< time()) { // проверка, что в сессию не записаны данные и что эти данные не устарели. do { add_time2start($k); $k++; } while ($k < = $num_starts); sort($time_to_start, SORT_NUMERIC); $_SESSION["num_st"] = $time_to_start; }

Now we need to make the script work, regardless of the maximum execution time set by the server.
The principle is:
1) Determine the start time of the script;
2) We determine the established restriction on the execution time.
3) We start the cycle, inside which we count the current time and calculate the total time the script is running, check the current time with the values ​​in the array of start times, and if there is a match, we perform the specified actions (I have them in the exec.php file). We use sockets to run files.
4) Repeat the cycle until the script's running time approaches the maximum allowed. I set - until the maximum time is 5 seconds.

So ... we consider the initial data in time:

$start_time = microtime(); // Find out the script start time $start_array = explode(" ",$start_time); // Separate seconds and milliseconds $start_time = $start_array; // get script start time $max_exec = ini_get("max_execution_time"); //Get the maximum possible script running time
Basically a cycle. Comments in code.

Do( $nowtime = time(); // Current time //// If the current time is in the array with script execution times...... if (in_array($nowtime, $_SESSION["num_st"])) ( // We cling to the file with the main content of the actions $http = fsockopen("test.ru",80); /// at the same time we pass the session data to it and the time when it should work fputs($http, "GET http://test .ru/exec.php?".session_name()."=".session_id()."&nowtime=$nowtime HTTP/1.0\r\n"); fputs($http, "Host: test.ru\r\ n"); fputs($http, "\r\n"); fclose($http); ) //// performed the specified action // Find out the current time to check whether to continue looping or restart $now_time = microtime( ); $now_array = explode(" ",$now_time); $now_time = $now_array; // subtract from the current time the initial initial $exec_time = $now_time - $start_time+$exec_time; /// slow down for a second usleep(1000000); // Stop a script running in the background, I can't think of any other way if (file_exists("stop.txt")) exit; Verify the running time, if less than 5 seconds are left before the end of the script's // operation, exit the loop. ) while($exec_time< ($max_exec - 5));

Well, if the allowed time is coming to an end, then we complete the cycle and safely run the same script by another process (we’ll definitely meet 5 seconds)

// Run the same script with a new process and exit the current one $http = fsockopen("test.ru",80); fputs($http, "GET http://test.ru/index.php?".session_name()."=".session_id()."&bu=$max_exec HTTP/1.0\r\n"); fputs($http, "Host: test.ru\r\n"); fputs($http, "\r\n"); fclose($http);

When I finished everything, I was puzzled by the useful application ... You can use it as a service. It can monitor something on the network and notify you, for example, by mail. And you don't need any cron's.

The script can still be optimized - it has not been finalized.
By the way, that's what I could not tear myself away from - the browser still has to be opened in order to initially run the script.