【问题标题】:PHP executing second php from the folder where the second php exist using main phpPHP使用主php从第二个php存在的文件夹中执行第二个php
【发布时间】:2015-11-17 16:26:18
【问题描述】:

嗨,我需要从另一个名为 parent.php 的 php 中执行文件夹 child 上的 php child.php,并在 parent.php 处获取 child.php 的输出。我有下面的代码,但不能工作,因为 child.php 应该从文件夹 child 本身执行。

如何解决这个问题,比如将目录更改为child 并在那里执行 php 并获取输出。

function execute($filename){
    ob_start();
    include $filename;
    $output = ob_get_contents();
    ob_end_clean();
    return $output;
}

【问题讨论】:

标签: php


【解决方案1】:

Michael Berkowski 的评论应该足以让您继续前进,但这是您要求的解决方案。错误处理留给读者练习。

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

【讨论】:

    【解决方案2】:

    我不确定,但您可以使用exec 执行它并将结果存储在一个变量中。我假设您正在使用类似 unix 的系统运行并调用

    php

    在命令行上执行 php 二进制文件。

    $file = 'child/child.php';
    $fullPath = __DIR__ . '/child/child.php';
    $command = 'php ' . $fullPath;
    $result = '';
    $resultCode = 0;
    exec($command, $result, $resultCode);
    var_dump($result);
    

    【讨论】:

      【解决方案3】:

      你应该使用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() 将执行命令并输出所有内容,但是当与输出缓冲区一起使用时,您可以返回包含输出的字符串。

      【讨论】:

      • 它只返回完整输出的最后一行;)
      • 哇!我不敢相信我只需要运行多行输出的脚本。谢谢@Paladin76
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多