Execing Processes in PHP
Our example demonstrates how to replace the current PHP process with another executable using the exec() function. This is similar to the classic exec function in Unix-like operating systems.
<?php
// For our example we'll exec `ls`. PHP doesn't require an
// absolute path to the binary we want to execute, but it's
// a good practice to use one.
$binary = '/bin/ls';
// exec() in PHP doesn't require arguments in slice form.
// We can pass them as a string.
$args = '-a -l -h';
// In PHP, we don't need to explicitly pass the environment
// variables. The child process inherits the environment
// of the parent process by default.
// Here's the actual exec() call. If this call is successful,
// the execution of our PHP process will end here and be
// replaced by the `/bin/ls -a -l -h` process.
exec("$binary $args");
// If exec() fails, the script will continue here.
echo "This line will only be printed if exec() fails.\n";When we run our program, it is replaced by ls.
$ php exec-processes.php
total 16
drwxr-xr-x 4 user 136B Oct 3 16:29 .
drwxr-xr-x 91 user 3.0K Oct 3 12:50 ..
-rw-r--r-- 1 user 1.3K Oct 3 16:28 exec-processes.phpNote that PHP’s exec() function behaves differently from the syscall in Unix-like systems. It doesn’t completely replace the current process, but rather creates a new process and waits for it to finish. The output of the command is not automatically displayed; you would need to capture and echo it explicitly if you want to see it.
For a closer equivalent to the Unix exec() syscall in PHP, you can use the pcntl_exec() function, which is available when PHP is compiled with process control support:
<?php
$binary = '/bin/ls';
$args = ['-a', '-l', '-h'];
pcntl_exec($binary, $args);
// If pcntl_exec() fails, the script will continue here.
echo "This line will only be printed if pcntl_exec() fails.\n";This version will completely replace the PHP process with the new process, just like the Unix exec() syscall.
PHP doesn’t offer a classic Unix fork function in its core, but the pcntl extension provides pcntl_fork() for creating child processes. However, for most use cases, PHP’s built-in functions for running external commands (like exec(), system(), or shell_exec()) are sufficient.
Comments powered by Disqus