You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP的shell_exec中正确传递查询参数?

问题原因

你遇到的问题是因为shell环境会把URL中的&当成特殊字符解析——在bash等shell里,&的作用是将前面的命令放到后台执行,所以你的原命令会被shell拆成多部分:

  1. curl https://$domain/$url.php?importid=$importid(后台运行)
  2. org=$org(被当成独立命令执行)
  3. t=xxx >> /var/log/bgrd_call.log 2>&1(被当成独立命令执行)
    最终curl只收到第一个查询参数,后面的都被shell剥离了。
正确实现方式

推荐以下几种靠谱的解决方法:

方法1:转义URL中的&

在每个&前面加上反斜杠\,让shell把它当作普通字符处理:

shell_exec("curl https://$domain/$url.php?importid=$importid\&org=$org\&t=".urlencode($t)." >> /var/log/bgrd_call.log 2>&1 ");

方法2:用双引号包裹整个URL

把完整的URL用双引号括起来,shell会将引号内的内容当作整体,不会解析里面的特殊字符:

shell_exec("curl \"https://$domain/$url.php?importid=$importid&org=$org&t=".urlencode($t)."\" >> /var/log/bgrd_call.log 2>&1 ");

方法3:用escapeshellarg做安全处理(推荐)

这个函数会自动处理所有shell特殊字符,既能解决当前问题,还能避免潜在的shell注入风险:

$fullUrl = "https://$domain/$url.php?importid=$importid&org=$org&t=".urlencode($t);
shell_exec("curl ".escapeshellarg($fullUrl)." >> /var/log/bgrd_call.log 2>&1 ");

内容的提问来源于stack exchange,提问作者user1729972

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:35:19