Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass json or class object to command line php script

I have

$client = new Google_Client();

And it's token in json.

Now I want to pass this client object as well as json token to another script via shell_exec().
Let's assume command as

php myscript.php var1 var2 $client $token

Now as command line takes all argument as string I am not able to pass the json and client object. For json I found serialize() and unserialize() functions that I can pass to command prompt but what about $client object how to pass it to command prompt? Please Help.

like image 364
Vivek Muthal Avatar asked Mar 10 '26 18:03

Vivek Muthal


2 Answers

Serialize will also "stringify" objects! You can also base64 encode/decode your arguments to prevent special chars troubles :

$aArgs = array($client, $token);
$sArgs = base64_encode(serialize($aArgs));
exec('php myscript.php '.$sArgs);
like image 155
Nassim Avatar answered Mar 13 '26 07:03

Nassim


I'd use json_encode():

Preferred method to store PHP arrays (json_encode vs serialize)

TLDR? There are some possible issues with json_encode():

  • By default, json_encode() converts UTF-8 characters to Unicode escape sequences while serialize() does not. Note: To leave UTF-8 characters untouched, you can use the option JSON_UNESCAPED_UNICODE as of PHP 5.4.
  • JSON will have no memory of what the object's original class was (they are always restored as instances of stdClass).
  • You can't leverage __sleep() and __wakeup() with JSON
  • Only public properties are serialized with JSON
  • JSON is more portable

But if none of these things are an issue for your use case. it's 100-150% faster than serialize(). (Your Google_Client() class will be converted to a standard class when you decode the string).

// Script that kicks off the background task
$aArgs = array($client, $token);
$sArgs = base64_encode(json_encode($aArgs));
exec('php myscript.php '.$sArgs . ' > /dev/null 2>/dev/null &');

// myscript.php
$sArgs = json_decode(base64_decode($argv[1]));
// do something with $sArgs here...
like image 26
Silas Palmer Avatar answered Mar 13 '26 07:03

Silas Palmer