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 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂