PHP exec and shell_exec can be used to execute a shell command on server side. exec also populates shell exit return status in one of the argument. shell_exec can also be used to get exit status by redirecting stdout and strerr and then echoing $?.
Capture return status using php exec
Here exit status will be set in $ret_var.
<?php
exec("ls /etc/passwd", $out, $ret_var);
echo "successful command ret_var=$ret_var\n";
exec("ls /etc/passwd_non_existing", $out, $ret_var);
echo "failed command ret_var=$ret_var\n";
?>successful command ret_var=0 failed command ret_var=2
Env: PHP 8.2.29 (Linux)
Capture return status using php shell_exec
Here main command stderr and stdout will be ignored by redirected to /dev/null (we can use a file also here). After the main command, 2nd command will echo exit status using $? which will be printed on stdout and hence will be returned by shell_exec.
<?php
$cmd = "ls /etc/passwd > /dev/null 2>&1; echo $?";
$status = shell_exec("$cmd");
$status = rtrim($status);
echo "successful command shell status=$status\n";
$cmd = "ls /etc/passwd_non_existing > /dev/null 2>&1; echo $?";
$status = shell_exec("$cmd");
$status = rtrim($status);
echo "failed command shell status=$status\n";
?>successful command shell status=0 failed command shell status=2
Env: PHP 8.2.29 (Linux)