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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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
Answers:

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().

Questions:
Answers:

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().

Questions:
Answers:

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
}

Questions:
Answers:

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.

Questions:
Answers:

That’s not the best way.

Passing the following to the exec function will also execute ./scripts.sh, which could now delete the whole UNIX system – when running into path issues:

exec(‘cd /patto/scripts; ./script.sh’);

Use && (To only execute the second command after successful termination of the first) instead of the ; (semi colon) – which is only like pressing the enter key.