douke3335 2014-01-28 14:48
浏览 60
已采纳

字符串未通过shell_exec正确传递给bash脚本

Input text in page1:

...
<form name="myform" action="page2.php" method="post">
<input type="text" size="92" name="my_text" />
...

page2.php:

...
$our_text = ($_POST['my_text']);

Until now we're ok, and echo $our_text still gives me the right string. but then, when passing $subject to a bash script:

...
shell_exec("./myscript.sh '$our_text'");

in myscript.sh:

...
still_our_text=$1
echo $still_our_text > log.txt

in log.txt, I have my complete string if it has only standard letters and spaces. But if there is an apostrophe or a letter with an accent (French é or è or ê), then I only get strange things "I will do it now" is kept intact in log.txt "I'll do it now" just doesn't work, log.txt is not created "L'éléphant va bien" (which means the elephant feels well...), actually puts "Léléphant" in log.txt, and if we pass additional arguments through shell exec, the other words are passed in the other arguments For example If I pass 4 arguments to shell exec:

1: "L'éléphant va bien"
2: "go"
3: 4
4: "stop"

Then in scrip.sh, if I echo $1 to $4 in log.txt, I have:

1: Léléphant
2: va
3: bien
4: 

But sometimes it just doesn't work and nothing get written in log.txt.

Any idea on how to fix this and correctly pass a string through shell_exec, so I recover my full string in the bash script ? Thanks in advance

  • 写回答

2条回答 默认 最新

  • dousaoxiancy199896 2014-01-29 07:40
    关注

    escapeshellarg should work. Take the following example:

    ourtext.php

    <?php
    setlocale(LC_CTYPE, 'en_US.UTF-8');
    $our_text = "L'éléphant va bien";
    shell_exec('./myscript.sh ' . escapeshellarg($our_text));
    

    myscript.sh

    still_our_text=$1
    printf '%s
    ' "$still_our_text" >log.txt
    

    (Made a few changes to be make it more robust)

    Then run it like so from the command line:

    $ php ourtext.php; cat log.txt
    L'éléphant va bien
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办