在 PHP 中通过 exec 发送 json 数组后无法解码它



我有一个看起来像这样的array

守护进程.php

$data = array(
   'notificationId' => $notificationId,
   'userId' => $userId,
   'appId' => $appId,
   'message' => $message,
   'destinationUrl' => $destinationUrl,
   'method' => $method,
   'notificationTime' => $notificationTime,
   'timeReceived' => $timeReceived,
   'impressions' => $impressions,
   'clicks' => $clicks,
   'numberOfUsers' => $numberOfUsers,
   'campaignId' => $campaignId,
   'targetGroups' => $targetGroups,
   'notificationType' => $notificationType,
   'status' => $status,
   'appGroup' => $appGroup
);

我通过exec发送的,如下所示:

$data=json_encode($data);
exec("php path/where/script/is/useArray.php ".$data." &");

并尝试在其他脚本上像这样使用它:

使用数组.php

$logData=$argv[1];
json_decode($logData);

为了查看useArray.php上接收了哪些数据,我将这个$logData数组放入服务器上的txt文件中,如下所示:

file_put_contents(__DIR__ .'/log/testiranje.txt', print_r($logData,true)."n", FILE_APPEND);

但是发送json似乎没有被正确解码。这是这个$logDatatestiranje.txt里面的样子:

{notificationId:478,userId:92,appId:1512823699024883,message:joj,destinationUrl:https://www.servis-racunara.net/pages/,method:2}

所以这是我在做json_decode后得到的一些奇怪的类似 json 的格式。当然,我不知道如何使用这种格式,因为我不能做以下任何事情:

$notificationId   = $logData['notificationId'];

您正在通过 shell 语法解释字符串,该语法具有自己非常庞大且复杂的特殊字符集。首先,"报价由外壳解释,因此从结果值中删除。

如果你想通过 shell(或者实际上通过任何具有自己的语法和特殊字符的中间语言)传输任意字符串,你需要适当地转它:

exec("php path/where/script/is/useArray.php " . escapeshellarg($data) . " &");

请参阅 http://php.net/escapeshellarg。

话虽如此,我会避免这种调用,而是使用其他通信机制,例如使用 ØMQ、Gearman 等的队列/工作线程设置。但这超出了本主题的范围。

您通常不能在 shell 中键入随机字符并让它们作为常规文本传递,这就是 escapeshellarg() 存在的原因(尽管根据我的经验,它只能在 Unix shell 上正常工作,并且在 Windows 上经常失败)。

在任何情况下,命令行参数仅适用于小参数。如果您需要传输复杂数据,最好使用其他机制:

  • 标准输入
  • 临时文件

对于前者,您必须转储exec()并使用例如 proc_open() —您可以在手册页中找到使用示例。

对于后者,只需在文件系统函数中选择您最喜欢的功能即可。对于小文件,file_put_contents()/file_get_contents()组合可能很好。

最新更新