How to stop PHP when using a terminal command using system () or passthru ()?

I am trying to make an application that checks that it can go outside, but it never stops. How can I apply the command to the terminal and stop the action? An example in the following case:

$ php -r "echo system('ping 127.0.0.1');"
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.073 ms
64 bytes from 127.0.0.1: icmp_req=2 ttl=64 time=0.073 ms
64 bytes from 127.0.0.1: icmp_req=3 ttl=64 time=0.072 ms
64 bytes from 127.0.0.1: icmp_req=4 ttl=64 time=0.074 ms
64 bytes from 127.0.0.1: icmp_req=5 ttl=64 time=0.071 ms
64 bytes from 127.0.0.1: icmp_req=6 ttl=64 time=0.073 ms
64 bytes from 127.0.0.1: icmp_req=7 ttl=64 time=0.074 ms
64 bytes from 127.0.0.1: icmp_req=8 ttl=64 time=0.073 ms
64 bytes from 127.0.0.1: icmp_req=9 ttl=64 time=0.074 ms
64 bytes from 127.0.0.1: icmp_req=10 ttl=64 time=0.081 ms
64 bytes from 127.0.0.1: icmp_req=11 ttl=64 time=0.072 ms
64 bytes from 127.0.0.1: icmp_req=12 ttl=64 time=0.075 ms

Note: ctrl + c is used to stop, but this will be done through a web browser.

+5
source share
4 answers

This can be done with proc_open. For example, this program allows you to run ping6within 5 seconds:

<?php
$descriptorspec = array(
   1 => array("pipe", "w"),
);

$process = proc_open('ping6 ::1', $descriptorspec, $pipes);

$emptyarr = array();
$start = microtime(true);
if (is_resource($process)) {
    stream_set_blocking($pipes[1], 0);
    while (microtime(true) - $start < 5) {
        $pipesdup = $pipes;
        if (stream_select($pipesdup, $emptyarr, $emptyarr, 0, 100000))
            echo fread($pipes[1], 100);
    }

    fclose($pipes[1]);
    proc_terminate($process);
}

In your case, you can check connection_aborted(). But note that you must continue to send (and flush) data to interrupt the user that will be detected.

+1

. -c ping.

+4

system() , . , .

ping -c 4 127.0.0.1 ping.

+1
source

The correct course of action is not to stop the process, but to bring the command line arguments to ping so that it ends by itself. The argument you are looking for -c countsends only a fixed number of requests. See more details man ping.

+1
source

All Articles