繁体   English   中英

使用多行 PHP 变量作为执行 bash 脚本的参数

[英]Use multiline PHP variable as argument for executing bash script

在 PHP 中,我有一个返回多行文本的变量,类似于下面显示的内容。

*
*clefF4
*k[f#c#g#d#a#]
*d:
*M6/4

然后我想在 PHP 中使用这个变量作为执行 bash 脚本的参数。 我这样做的 PHP 代码如下(其中$filechosen是上面的文本字符串):

$output = shell_exec("/path/to/bash/script.sh $filechosen");
echo "<pre>$output</pre>";

下面是使用变量“ $filechosen ”作为参数的极其简单的 bash 脚本:

#!/bin/bash

returnExpression=$(echo "$1" | grep 'k\[')
echo $returnExpression

但是,当我运行它时,我没有得到任何输出。 为什么是这样?

您应该始终对要替换到命令行中的变量进行转义,PHP 提供了一个函数escapeshellarg()来执行此操作。

$output = shell_exec("/path/to/bash/script.sh " . escapeshellarg($filechosen));

或者

$escaped = escapeshellarg($filechosen);
$output = shell_exec("/path/to/bash/script.sh $escaped");

在 GNU/Linux 中,常用的命令方式是处理流。 grep也是如此。 只要有可能,您就不应该打破这种模式。 在您的特定示例中,将其包装到位置参数中是没有意义的。

您可以使用popen将流写入执行的命令:

<pre>
<?php

$filechosen = <<<_EOS_
*
*clefF4
*k[f#c#g#d#a#]
*d:
*M6/4
_EOS_;


if($handle = popen("grep 'k\\['", "w"))
{
  fwrite($handle, $filechosen);
  pclose($handle);
}

?>
<pre>

当您想将输出流读入变量时,请改用proc_open函数。

if($handle = proc_open("grep 'k\\['", [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $streams))
{
  [$stdin, $stdout, $stderr] = $streams;

  fwrite($stdin, $filechosen);
  fclose($stdin);

  $output = stream_get_contents($stdout);
  fclose($stdout);

  $error  = stream_get_contents($stderr);
  fclose($stderr);

  proc_close($handle);
  echo $output;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM