tags:

views:

236

answers:

4

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
+1  A: 

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

thephpdeveloper
Oh yeah, good ole chdir()!
timdev
A: 
timdev
+2  A: 

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

soulmerge
A: 

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
}
Inshallah