Ognj3n Ognj3n - 6 months ago 26
PHP Question

Unable to decode json array after sending it via exec in PHP

I have an

array
that looks like this:

Daemon.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

);


That I'm sending via
exec
like so:

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


And trying to use it like so on other script:

useArray.php

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


In order to see which data received on
useArray.php
I'm putting this
$logData
array into txt file on server like this:

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


But sent
json
just seem not to be decoded right. This is how this
$logData
looks inside
testiranje.txt
:

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


So this is some strange json-alike format that I got after doing
json_decode
. And of course I don't know how to use this format, because I can't do anything like:

$notificationId = $logData['notificationId'];

Answer

You're interpreting a string through the shell syntax, which has its own very large and complex set of special characters. For one, " quotes are interpreted by the shell and are consequently stripped out of the resulting value.

If you want to transport any arbitrary string through the shell (or in fact through any intermediary language which has its own syntax and special characters), you need to escape it appropriately:

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

See http://php.net/escapeshellarg.

Having said this, I'd avoid this kind of invocation to begin with and use other communication mechanisms, like a queue/worker setup using ØMQ, Gearman or the like. But that's out of scope for this topic.

Comments