-1

Hi I need to execute a php child.php which is on the folder child, from another php named parent.php, and get the out put of child.php at parent.php. I have the below code but not works as the child.php should executed from the folder child itself.

How can resolve the issue, like change the directory to child and execute the php there and get the output.

function execute($filename){
    ob_start();
    include $filename;
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}
Haris
  • 13,645
  • 12
  • 90
  • 121
  • 4
    You can `chdir()` into `child/` before running this `execute()` function then change back (if necessary). http://php.net/manual/en/function.chdir.php Without more details of what is actually in `child.php`, there's not much more to speculate on. – Michael Berkowski Nov 17 '15 at 16:29
  • W.T.F ? û_O could you be a more detailed about `should executed from the folder` – Blag Nov 17 '15 at 16:29
  • @Blag `should executed from the folder` because in `child php` I am using relative path to get some file content, and at the moment I cannot access to change the `child.php`, I can only edit `parent.php` – Haris Nov 17 '15 at 16:32
  • Possible duplicate of [PHP: How to set current working directory to be same as directory executing the script](http://stackoverflow.com/questions/5254000/php-how-to-set-current-working-directory-to-be-same-as-directory-executing-the) – Mark Amery Nov 17 '15 at 19:05

3 Answers3

1

I am not sure, but you could execute it with exec and store the result in a variable. I assume that you are running with an unix-like system and calling

php

on a command line executes the php binary.

$file = 'child/child.php';
$fullPath = __DIR__ . '/child/child.php';
$command = 'php ' . $fullPath;
$result = '';
$resultCode = 0;
exec($command, $result, $resultCode);
var_dump($result);
Paladin
  • 1,637
  • 13
  • 28
1

You should use system()

function execute($filename){
    ob_start();

    // you may want to get the full path to $filename
    system("php {$filename}");

    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

system() will execute the command and just output everything, but when used with an output buffer, you can return a string containing the output.

jay
  • 177
  • 1
  • 12
1

Michael Berkowski's comment should be enough to get you going but here is the solution you asked for. Error handling is left as an exercise for the reader.

function execute($filename) {
    // store current directory
    $cur_dir = getcwd();
    // change directory to the folder containing $filename
    chdir(dirname($filename));
    ob_start();
    include $filename;
    $output = ob_get_contents();
    ob_end_clean();
    // change back to the original working directory
    chdir($cur_dir);
    return $output;
}
Community
  • 1
  • 1
Josh J
  • 6,813
  • 3
  • 25
  • 47