Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Slim PHP from the command line
<?php
if (PHP_SAPI != 'cli') {
exit("CLI only");
}
if (empty($argv) || count($argv) < 2) {
exit("Missing route for CLI");
}
// remove calling script
array_shift($argv);
// get route + params from 1st argument
$uri = array_shift($argv);
// group routes by /cli/
if (strpos($uri, '/cli/') !== 0) {
// handle os shell quirks
// windows git bash
if (strpos($uri, 'C:/Program Files/Git/cli/') === 0) {
$uri = str_replace('C:/Program Files/Git/cli/', '/cli/', $uri);
} else {
echo "uri: " . $uri . PHP_EOL;
exit("CLI Route must start with /cli/");
}
}
// get any more arguments
if (!empty($argv)) {
$additional = '';
foreach ($argv as $arg) {
if (strpos($arg, '=') !== false) {
// r=1 d=10
$additional .= '&' . $arg;
} else {
// normal args -r 10, store as argv
$additional .= '&argv[]=' . $arg;
}
}
if (strpos($uri, '?') === false) {
$uri .= '?';
}
$uri .= $additional;
}
// set uri based on cli arguments
$_SERVER['REQUEST_URI'] = $uri;
// normal Slim app, routes_cli_*, ActionCli
(require __DIR__ . '/cfg/bootstrap.php');
@mbrowniebytes
Copy link
Author

mbrowniebytes commented Dec 14, 2020

Command line entry script for Slim PHP.
Create cli.php below public, in the project root, at the same level as public, src, vendor, etc.

@mbrowniebytes
Copy link
Author

mbrowniebytes commented Sep 30, 2021

updated to handle os shell quirks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment