Pass KM Variables to PHP in Command Line

One way to pass KM variables to PHP variables is to use the $_ENV variable. See the example in my post:
Please Consider Adding "Get KM Variable in PHP" to the Wiki Scripting Page - Forum Admin - Keyboard Maestro Discourse

If we run php from command line, we can pass KM variables in such way:

Make a php file, named test.php. I save it to '~/Dropbox/Scripting/php/'.

<?php
$var = getopt("p:q:");
echo var_dump($var);
?>

Make a KM macro as such:

The value of LocalVar1 in KM will become the value of $p.
The value of LocalVar2 in KM will become the value of $q.

Result of the macro:
image

I'm completely new to php and I was wondering if you could help me understand something. I have a php script for Logic Pro project files that works from terminal like this:

php <path to script> -f <path to file> -s <search term>

-f tells the script to search in the file and -s tells it to search for that term.

My question is, how do I do all this when the script code is in a Keyboard Maestro shell script action?

I've tried this, but it doesn't work, so I must be making some basic errors:

I've removed the actual code to make it easier to see in a screenshot.

Your Terminal command is "Unix shell -- tell php to run this script using these arguments". So you just need to do the same in KM:


...will probably do it. You could hard-code the script's path as above, or pass it in as a variable too. Using the full path to php means you don't have to worry about shell search paths.

1 Like

How many :beers: do I owe you now? I've lost count!

Thanks man!

The other way to do it would be the way you tried, "writing" the script in the KM action, and passing in KM variables. Your current php script probably uses getopt("f:s:") to collect the parameters, so you'd be looking to strip out the collection code block and replace it with assignments from your KM variables using $_ENV[KMVAR_Local__FilePath] and $_ENV[KMVAR_Local_SearchTerm].

My php is very rusty (thank Google for us getting this far!) but post the code if you want to go this route.

1 Like

It's working the way you first suggested, so I'm tempted not to look a gift horse in the mouth!

I suppose if it didn't reference an external script, it would simplify installation for other users, but I wouldn't know how to "strip out the collection code block", so I think I'll leave it as-is for now. Thanks again!