从PHP执行adb shell并转义字符串 [英] Executing adb shell from PHP and escaping strings

查看:570
本文介绍了从PHP执行adb shell并转义字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将有效的bash脚本转换为PHP代码。

I am trying to convert a working bash script into PHP code.

#!/bin/bash
phonenumber="$1"
message="$2"

# check the args...
# double quotes inside $message must be escaped. Also prevents code injection.
message=${message//\"/\\\"}

adb shell "am startservice --user 0 -n com.android.shellms/.sendSMS -e \"contact\" $phonenumber -e msg \"$message\""

上面的代码有效。
在PHP中,当消息中包含新行时,下一个代码将不起作用:

The code above works. In PHP, next code doesn't work when the messages includes a new line:

function sendsms ($m, $to, $n) {
    echo "About to sent an sms to $to [$n]\n";

    // escape some chars in $m
    $m = addslashes($m);

    adb_shell_exec ("am startservice --user 0 -n com.android.shellms/.sendSMS -e contact \"$to\" -e msg \"$m\"");

}

function adb_shell_exec ($s) {
    shell_exec("adb shell " . addslashes ($s));
}

我收到消息错误:


       $ php -r "require 'sim-android-v8.php'; sendsms('Message with one double \" quote final solution
       and new line','+32*******31','Pierre François');"
       About to sent an sms to +32*******31 [Pierre François]
       /system/bin/sh: no closing quote
       sh: 2: and: not found

我不明白为什么会这样

推荐答案

感谢FAEWZX,我发现函数 escapeshellarg()的正确使用。他在上面给出的答案在大多数情况下都有效,但并不防水。IMO,下面的代码更好,因为到目前为止,使用 escapeshellarg()可以覆盖100%的情况。 strong>两次并递归。

Thanks to FAEWZX, I discovered the proper use of the function escapeshellarg(). The answer he gave above is working in most of the cases, but is not waterproof. IMO, the code below is better because it covers 100% of the cases so far, using escapeshellarg() twice and recursively.

function sendsms ($m, $to, $n) {
    echo "About to sent an sms to $to [$n]\n";

    $subshell = 'am startservice --user 0' .
      ' -n com.android.shellms/.sendSMS' .
      ' -e contact ' . escapeshellarg($to) . 
      ' -e msg ' . escapeshellarg($m);

    $shell = 'adb shell ' . escapeshellarg($subshell);

    shell_exec($shell);
}

这篇关于从PHP执行adb shell并转义字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆