Passing Variables to Cron-Job PHP Scripts
When you schedule a PHP script to run via cron, passing arguments directly in the file pathâlike php myfile.php?type=dailyâfails because the shell interprets the string after the .php extension as part of the filename, not as an argument. The error "Could not open input file: myfile.php?type=daily" confirms this; your server is looking for a physical file literally named that string and cannot find it. To actually pass data like type=daily, you must use shell syntax to separate the command from its arguments.
Shell Argument Handling
The most direct approach uses the standard shell operator to append an argument without spaces around the equals sign, or by using the assignment syntax if your script expects a global variable. However, the cleanest and most portable method is passing key-value pairs as distinct arguments. If your PHP file expects $_GET['type'] to be populated, you can simulate a URL query string:
php myfile.php type=daily
In this command, type=daily becomes a single argument in the argv array of your PHP script, accessible via $_SERVER['argv'][1] or by parsing it as if it were a GET request. Many developers prefer to treat CLI scripts like web endpoints for consistency. You can achieve this by manually populating the superglobals:
<?php
// myfile.php
$argv = array_merge($_SERVER['argv'], ['type' => 'daily']); // Example setup
$type = $_GET['type'] ?? $_SERVER['argv'][1] ?? null;
This pattern ensures your logic remains unchanged whether the script runs from a browser or cron. If you prefer to rely on $_GET, ensure you don't assume it is automatically populated for CLI requests unless you explicitly merge $argv into $_GET.
Environment Variables vs. Command Arguments
Another option is using environment variables, which can be set in the crontab entry itself:
TYPE=daily php myfile.php
This approach works well if your PHP script uses getenv('TYPE') instead of checking $_GET or $argv. Environment variables persist for the duration of the process and are useful for configuration, but they introduce a different mental model. If your codebase expects URL-style parameters, mixing environment variables and arguments can lead to confusion. Stick to one source of truth for argument passing unless there is a specific reason not to.
Parsing Arguments in PHP
When you pass type=daily, your PHP script receives it as a string. You must parse it to extract the key and value. A common mistake is assuming $_GET works out of the box. In CLI context, $_GET is empty unless you manually populate it:
<?php
$argv = $_SERVER['argv'];
$type = null;
foreach ($argv as $arg) {
if (strpos($arg, '=') !== false) {
list($key, $value) = explode('=', $arg, 2);
$_GET[$key] = $value;
}
}
echo $_GET['type'] ?? 'No type provided';
This loop ensures that any key-value pair passed on the command line is available in $_GET regardless of your original code structure. It also handles multiple arguments gracefully, allowing you to pass --config path/to/config.php alongside type=daily.
Security Considerations
Passing variables via the command line does not inherently sanitize input. If you extract values from $argv without validation, malicious cron entries or misconfigured jobs could inject harmful data. Always treat CLI arguments as untrusted input. Validate types and lengths before using them in logic or database queries. For example:
if (!in_array($_GET['type'] ?? '', ['daily', 'weekly', 'monthly'])) {
exit('Invalid type');
}
This check prevents unexpected values from slipping into your processing logic, especially important when cron jobs might be triggered by external automation tools.
Cron Configuration Example
When updating your crontab, remember to quote arguments containing spaces:
0 2 * * * php /path/to/myfile.php "type=daily" >> /var/log/myfile.log 2>&1
Quoting ensures the shell doesn't split type=daily into separate tokens. Redirecting output to a log file helps diagnose failures without cluttering system logs. If your script writes to stderr, capturing both streams with 2>&1 ensures you see all diagnostic messages.
