开发者

PHP exec() command: how to specify working directory?

开发者 https://www.devze.com 2022-12-11 02:23 出处:网络
My script, let\'s call it execute.php, needs to start a shell script which is in Scripts subfolder. Script has to be executed so, that its working directory is Scripts. How开发者_如何转开发 to accompl

My script, let's call it execute.php, needs to start a shell script which is in Scripts subfolder. Script has to be executed so, that its working directory is Scripts. How开发者_如何转开发 to accomplish this simple task in PHP?

Directory structure looks like this:

execute.php
Scripts/
    script.sh


Either you change to that directory within the exec command (exec("cd Scripts && ./script.sh")) or you change the working directory of the PHP process using chdir().


The current working directory is the same as the PHP script's current working directory.

Simply use chdir() to change the working directory before you exec().


For greater control over how the child process will be executed, you can use the proc_open() function:

$cmd  = 'Scripts/script.sh';
$cwd  = 'Scripts';

$spec = array(
    // can something more portable be passed here instead of /dev/null?
    0 => array('file', '/dev/null', 'r'),
    1 => array('file', '/dev/null', 'w'),
    2 => array('file', '/dev/null', 'w'),
);

$ph = proc_open($cmd, $spec, $pipes, $cwd);
if ($ph === FALSE) {
    // open error
}

// If we are not passing /dev/null like above, we should close
// our ends of any pipes to signal that we're done. Otherwise
// the call to proc_close below may block indefinitely.
foreach ($pipes as $pipe) {
    @fclose($pipe);
}

// will wait for the process to terminate
$exit_code = proc_close($ph);
if ($exit_code !== 0) {
    // child error
}


If you really need your working directory to be scripts, try:

exec('cd /path/to/scripts; ./script.sh');

Otherwise,

exec('/path/to/scripts/script.sh'); 

should suffice.


This is NOT the best way :

exec('cd /patto/scripts; ./script.sh');

Passing this to the exec function will always execute ./scripts.sh, which could lead to the script not being executed with the right working directory if the cd command fails.

Do this instead :

exec('cd /patto/scripts && ./script.sh');

&& is the AND logical operator. With this operator the script will only be executed if the cd command is successful.

This is a trick that uses the way shells optimize expression evaluation : since this is an AND operation, if the left part does not evaluate to TRUE then there is not way the whole expression can evaluate to TRUE, so the shells won't event process the right part of the expression.

0

精彩评论

暂无评论...
验证码 换一张
取 消