Wednesday, November 14, 2018

PHP: Passing Variables on the Command Line

In my work I need to generate documentation, and sadly I work in an all Windows environment and have no Apache server available to me. Using PHP to generate content is pretty natural to, but not using a web server creates some challenges.

If you have PHP installed*, it is easy enough to turn a document into an html document via redirection:

php .\mypage.php > mypage.html

However, one of the great things about PHP is passing $_GET data. I use JSON config files which contain data my documentation needs. If I want to point to a particular json file, I do not need to code it into my script, if I pass the file location as an argument.

<?php
    parse_str(implode('&', array_slice($argv, 1)), $_GET);
    $json = $_GET['json'];
    include($json);
?>

So, my command line would be:

php .\mypage.php json=mypage.json > mypage.html

* PHP can be drop-installed on Windows, meaning that if the executable is present you can run php. I set up an alias in my Powershell $PROFILE to make it available easily:

    Set-Alias -Name php -Value C:\mybin\php\php.exe

No comments: