Skip to content

Instantly share code, notes, and snippets.

@mbrowniebytes
Last active September 30, 2021 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbrowniebytes/71720f437c4051dfebe043770360ad79 to your computer and use it in GitHub Desktop.
Save mbrowniebytes/71720f437c4051dfebe043770360ad79 to your computer and use it in GitHub Desktop.
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

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

updated to handle os shell quirks

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