Skip to content

Instantly share code, notes, and snippets.

@mbrowniebytes

mbrowniebytes/cli.php

Last active Dec 14, 2020
Embed
What would you like to do?
Slim PHP from the command line
<?php
// command line only
if (PHP_SAPI != 'cli') {
exit("CLI only");
}
// 1st arg is calling script, and then should pass in a uri which should map to a route
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) {
exit("CLI Route must start with /cli/");
}
// get any more arguments
if (!empty($argv)) {
$additional = '';
foreach ($argv as $arg) {
if (strpos($arg, '=') !== false) {
// cli.php r=1 d=10
$additional .= '&' . $arg;
} else {
// cli.php -r 10
// normal arguments, 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
// https://www.slimframework.com/docs/v4/objects/application.html
(require __DIR__ . '/your/bootstrap.php');
@mbrowniebytes

This comment has been minimized.

Copy link
Owner Author

@mbrowniebytes 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.

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