PHP exec () komutu: çalışma dizini belirtmek için nasıl?

4 Cevap

Benim komut, o da execute.php diyelim, Script alt klasör içinde bir kabuk komut dosyasını başlatmak gerekiyor. Senaryo onun çalışma dizini Script olduğunu, bu nedenle idam edilmelidir. PHP bu basit görevi gerçekleştirmek için nasıl?

Dizin yapısı bu gibi görünüyor:

execute.php
Scripts/
    script.sh

4 Cevap

Eğer (exec("cd Scripts && ./script.sh")) exec komutu içinde bu dizine değiştirin veya chdir() kullanarak PHP sürecinin çalışma dizinini değiştirmek ya.

Geçerli çalışma dizini PHP betiğin geçerli çalışma dizini olarak aynıdır.

Basitçe chdir() önce çalışma dizinini değiştirmek için kullanabileceğiniz exec().

Eğer gerçekten komut olmak için çalışma dizini gerekiyorsa, deneyin:

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

Aksi takdirde,

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

yeterli olacaktır.

Çocuk süreç idam edilecek kadar üzerinde daha fazla kontrol için, proc_open() işlevini kullanabilirsiniz:

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