load .profile with proc_open()

I don’t have a ksh, but I’ve managed to do it with bash.

/home/galymzhan/.bash_profile:

export VAR_FROM_PROFILE="foobar"

/home/galymzhan/test.php:

#!/usr/bin/php -n
<?php
if (!isset($_SERVER['VAR_FROM_PROFILE'])) {
  $descriptors = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'));
  $process = proc_open('bash', $descriptors, $pipes);
  fwrite($pipes[0], escapeshellcmd('source /home/galymzhan/.bash_profile') . "\n");
  fwrite($pipes[0], escapeshellcmd('/home/galymzhan/test.php') . "\n");
  fclose($pipes[0]);
  echo "Output:\n";
  echo stream_get_contents($pipes[1]);
  echo "\n";
  fclose($pipes[1]);
  proc_close($process);
  exit;
}
print "Got env var {$_SERVER['VAR_FROM_PROFILE']}\n";
// Useful part of the script begins

Output I’ve got:

[galymzhan@dinohost ~]$ ./test.php 
Output:
Got env var foobar

Leave a Comment