【问题标题】:PHP exec() runs the code but doesn't work completelyPHP exec() 运行代码但不能完全工作
【发布时间】:2023-04-03 01:20:02
【问题描述】:

在我的代码的某些部分,我比较了 2 个文件并使用 exec() 函数将差异输出到另一个文件。

exec 函数中我使用comm -13 <(sort file_a) <(sort file_b) > output

当我运行我的 php 代码时,它会创建输出文件,但文件本身是空的。当我直接将命令复制并粘贴到终端时,它也会填充具有差异的文件,但不会在 php 上填充我的输出文件。

部分代码;

exec('bash -c \'comm -13 <(sort "' . $path_d_raw.$least_recent_raw_file . '") <(sort "' . $path_d_raw.$most_recent_raw_file . '") > test.txt 2>&1\'', $output, $return);

$path_d_raw.$least_recent_raw_file and $path_d_raw.$most_recent_raw_file 路径正确,/file 测试了一百次。

我也尝试使用shell_exec,但无法以任何方式完成。

【问题讨论】:

    标签: php bash exec


    【解决方案1】:

    您可以使用filesize()函数直接比较文件大小,也可以回显该值。

        <?php
    
    // outputs e.g.  somefile.txt: 1024 bytes
    
    $filename = 'somefile.txt';
    echo $filename . ': ' . filesize($filename) . ' bytes';
    
    ?>
    

    https://www.php.net/manual/ro/function.filesize.php

    【讨论】:

    • 这与文件大小无关 :) 这是关于比较 2 个文件并打印差异
    【解决方案2】:

    我的猜测是逃避问题。您应该使用proper functions 来转义参数和(在这种情况下)命令。试试这个:

    <?php
    $command = sprintf(
        "comm -13 <(sort %s) <(sort %s) > test.txt 2>&1",
        escapeshellarg($path_d_raw . $least_recent_raw_file),
        escapeshellarg($path_d_raw . $most_recent_raw_file)
    );
    $escaped_command = escapeshellarg($command);
    exec("bash -c $escaped_command", $output, $return);
    

    我们转义了两次,因为您将命令本身传递给另一个 shell 执行。

    我还建议写入一个位于绝对路径的文件,在一个单独的目录中。您的 Web 服务器可以写入存储可执行 PHP 脚本的目录这一​​事实应该引起您的关注。

    【讨论】:

    • 感谢@miken32,代码仍然可以毫无问题地执行,但它仍然不会填充新文件的差异。我检查了几次权限问题,但它只创建test.txt 文件但不填充它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    相关资源
    最近更新 更多