Some people might find it useful to run other program using the same process as a different user. This is very usefull if the script is running under root. Here is a simple code to achieve that under *nix PHP CLI:
#!/usr/bin/php -q
<?php
//Enter run-as user below (argument needed to be passed when the script is called), otherwise it will run as the caller user process.
$username = $_SERVER['argv'][1];
$user = posix_getpwnam($username);
posix_setuid($user['uid']);
posix_setgid($user['gid']);
pcntl_exec('/path/to/cmd');
?>
I use this as a part of socket program so that a program can be run under different user from remote location.pcntl_exec
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
pcntl_exec
Референца за `function.pcntl-exec.php` со подобрена типографија и навигација.
pcntl_exec
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
pcntl_exec — Ја извршува наведената програма во тековниот простор на процесот
= NULL
Ја извршува програмата со дадените аргументи.
Параметри
path-
pathмора да биде патека до бинарна извршна датотека или скрипта со валидна патека што укажува на извршна датотека во шебанг (#!/usr/local/bin/perl на пример) како прв ред. Погледнете ја страницата man execve(2) на вашиот систем за дополнителни информации. args-
argsе низа од низи со аргументи што се предаваат на програмата. env_vars-
env_varsе низа од низи што се предаваат како околина на програмата. Низата е во формат име => вредност, каде што клучот е името на променливата на околината, а вредноста е вредноста на таа променлива.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. false on failure. On success the function does not return, because the current process image is replaced by the executed program.
Белешки од корисници 3 белешки
The pcntl_exec() function works exactly like the standard (unix-style) exec() function. It differs from the regular PHP exec() function in that the process calling the pcntl_exec() is replaced with the process that gets called. This is the ideal method for creating children. In a simple example (that does no error checking):
switch (pcntl_fork()) {
case 0:
$cmd = "/path/to/command";
$args = array("arg1", "arg2");
pcntl_exec($cmd, $args);
// the child will only reach this point on exec failure,
// because execution shifts to the pcntl_exec()ed command
exit(0);
default:
break;
}
// parent continues
echo "I am the parent";
--
since this is not being executed through a shell, you must provide the exact path from the filesystem root. Look at the execve() man page for more information.As a side note, if I'm reading the comments below correctly, you should not run this if you're using a PHP webserver module, as it will replace the webserver's process with whatever process you're telling it to run.