Execute a PHP script from another PHP script
When you need to trigger logic that normally runs via a cron job but requires manual activation, you are essentially asking your application to handle an event without HTTP input. The goal is to run code on the server sideâbypassing web request handling while still utilizing the full PHP runtime environment. This approach is distinct from calling an external script; it involves invoking internal logic within the same application stack.
To achieve this, you must explicitly detach the execution context from the standard HTTP request lifecycle. A simple include or require statement will not suffice if your script relies on specific initialization hooks, such as Service Providers in a Laravel application, or if you need to ensure the output buffer is handled correctly for background tasks. The primary mechanism for this is using the command-line interface (CLI) execution mode directly from within a PHP file.
Using exec and system for CLI Invocation
If your architecture separates web-facing scripts from background workers, the most direct method is to invoke the PHP interpreter as an external process. You can do this using functions like exec(), system(), or passthru(). These functions allow a running PHP script to spawn another instance of the PHP CLI engine.
Consider a scenario where you have a file named cron_job.php that contains heavy processing logic intended to run every two hours. You can create a separate trigger script, say manual_run.php, which executes this file via the system binary:
#!/usr/bin/env php
<?php
// Ensure we are not interfering with the current request output
ob_start();
// Execute the target script as a CLI process
$output = exec('php /path/to/cron_job.php 2>&1');
if (false !== $output) {
// Log the output to a file or handle errors here
error_log($output);
} else {
throw new RuntimeException('Script execution failed.');
}
This approach effectively runs cron_job.php in a clean CLI environment, ignoring the web server's request handler. The key here is ensuring that the path provided to the php binary matches your system's CLI installation and that file permissions allow the current user to execute it. However, this method introduces a process fork overhead and makes passing complex data structures between the scripts cumbersome unless you rely on temporary files or environment variables.
Leveraging Application Frameworks
If your application is built on a framework like Laravel, relying on external CLI execution might bypass essential service containers or middleware that initialize the application state. In these cases, it is often better to design the manual trigger as a dedicated command.
Laravel provides an artisan CLI interface designed specifically for this purpose. You can register a custom command in your ConsoleKernel that performs the exact same logic as your cron job. Once registered, you can invoke this command directly from within another PHP script using the Artisan facade or by calling the underlying class methods.
use Illuminate\Support\Facades\Artisan;
Artisan::call('your:custom:command');
This method keeps the logic encapsulated within your application's service container, ensuring that all necessary bindings and configurations are loaded correctly. It avoids the pitfalls of spawning a new process, which can be resource-intensive if called frequently from web requests.
Critical Considerations and Pitfalls
Regardless of the method chosen, you must address the implications of running background logic during an active HTTP request. If your manual trigger script runs synchronously in a web context (e.g., inside a controller or route), it will block the response until the task completes. This can lead to timeouts or poor user experience if the cron job logic is computationally expensive.
To mitigate this, consider using Laravel's Queue system even for manual triggers. You can push a job onto the queue from your manual script and let the worker process handle the heavy lifting asynchronously. This decouples the triggering event from the execution time, maintaining responsiveness in your web interface.
Additionally, be cautious with error handling. If the target script throws an exception that isn't caught in its CLI context, you might see a generic PHP fatal error displayed depending on your php.ini settings. Ensure that display_errors is set to Off and log_errors is set to On for production environments to keep logs clean and secure.
Finally, if you are moving away from file-based cron jobs entirely, integrating with a dedicated task scheduler like Laravel Scheduler allows you to define these manual triggers as events that can be dispatched both automatically and manually via the queue or CLI command system.
