【问题标题】:How to use PHP variable in shell-scripts? [duplicate]如何在 shell 脚本中使用 PHP 变量? [复制]
【发布时间】:2018-04-05 16:11:10
【问题描述】:

我想用 PHP 向远程服务器发送一个文件。当我对文件名进行硬编码时,以下代码可以正常工作:

$output = shell_exec('curl -XPOST -F "file=@myfile.txt" http://135.195.42.168:6007');
echo "<pre>$output</pre>";

现在我需要动态决定 "file=@myfile.txt"。我尝试了以下方法:

$filePath = $_SERVER['DOCUMENT_ROOT'].'package/myzip_'.$owner_id.'.zip';
$name = basename($filePath);
$content = "file=@{$name}";
$output = shell_exec('curl -XPOST -F $content http://135.195.42.168:6007');
echo "<pre>$output</pre>";

很遗憾,上面的代码不起作用。请问有更好的建议吗?

【问题讨论】:

  • 单引号将打印出$content,而不是变量的内容。将其更改为双引号。
  • 完美运行!非常感谢,@aynber。

标签: php shell curl


【解决方案1】:
$filePath = $_SERVER['DOCUMENT_ROOT'].'package/myzip_'.$owner_id.'.zip';
$name = basename($filePath);
$content = "file=@{$name}";
$output = shell_exec('curl -XPOST -F ' . $content . ' http://135.195.42.168:6007');
echo "<pre>$output</pre>";

应该没问题

还有

$output = shell_exec("curl -XPOST -F $content 135.195.42.168:6007"); 

注意:

' in php 告诉 php 不解释 ' 之间的任何内容

$x = 'HELLO';


echo "what you say when you are nice? $x"; //outputs: what you say when you are nice? HELLO

这不适用于''

回显 '\n'; //输出\n

回显 "\n"; //输出换行符(不是
换行符,而是回车符)

一般来说,我觉得尽可能使用 '' 会更安全。它不仅更安全,而且通常也更实用,因为你可以这样做

$output = shell_exec('curl -XPOST -F ' . str_replace('a', 'b', $content) . ' http://135.195.42.168:6007');

您不必重新阅读代码来扫描所有字符串以查找隐藏的 $

【讨论】:

猜你喜欢
  • 2020-11-01
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 2022-01-18
相关资源
最近更新 更多