PHP exec()运行代码,但不能完全正常工作

问题描述 投票:0回答: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具有正确的路径,/文件对其进行了百次测试。

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

php bash exec
2个回答
0
投票

您可以使用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


0
投票

我的猜测将是一个不可避免的问题。您应该使用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脚本的目录这一​​事实应引起您的关注。

© www.soinside.com 2019 - 2024. All rights reserved.