How can I run a PHP script in the background after a form is submitted?
You are facing a classic synchronous vs. asynchronous processing dilemma. Your form submission triggers two distinct operations: inserting data into a database and sending 150+ individual emails. The database write is fast; the email queue processing takes over a minute due to server-side restrictions on mass emailing. This creates a user experience where the submitter waits indefinitely, leading to duplicate submissions or browser hangs if they navigate away prematurely.
The goal is to decouple the immediate response from the long-running task without relying on cron (which has frequency limits) or forcing the user to wait for synchronous completion. The solution involves queuing the background job and responding immediately to the client.
Immediate Database Commit
The first step in this architecture is ensuring the primary database operation completes before any background work begins. Your main request handler should insert the record into the notifications table and return success as soon as that transaction commits.
At this point, you have two architectural paths for the email sending logic: a dedicated queue job or a direct file call. Since your environment restricts cron frequency but allows instant triggers, a message queue is the standard approach for reliability. If you are using Laravel, the built-in task scheduler and queue system handles this elegantly. You would dispatch a SendNotificationJob immediately after the form save:
// In your FormController or Route
$notification = Notification::create($data);
// Commit the transaction first
$db->commit();
// Dispatch the email task to the queue
dispatch(new SendEmailJob($notification->id));
return redirect()->route('notifications.success', $notification->id);
The redirect() call ensures the browser receives a 200 OK status immediately. The user sees the success page instantly, eliminating the "server lag" perception and preventing duplicate form submissions. If JavaScript is disabled, this HTTP-level response still works, solving one of your specific constraints.
Handling Direct File Execution
If you are not using a framework queue system or prefer to run a separate script directly, you can invoke that script via a synchronous exec() or shell_exec() call within the main request cycle. However, you must distinguish between "fire-and-forget" and "synchronous blocking."
To achieve true fire-and-forget behavior without waiting for the emails to send, you must detach the process so the web server does not wait for the background script to finish before sending the HTTP response. In PHP, this is often done by piping output to /dev/null or running the child process asynchronously:
$output = shell_exec('php /path/to/send_emails.php ' . $notificationId . ' 2>/dev/null');
return redirect()->route('notifications.success', $notificationId);
The 2>/dev/null redirects error output to prevent the main script from halting on stderr, and the lack of a wait() ensures the function returns immediately. The caveat here is that if the background script crashes or hits a fatal error before finishing, it might not be logged in your standard web log unless you explicitly capture and write its exit code or logs to a separate file.
Addressing the "Cannot Fail" Constraint
Your source material mentions a critical requirement: "This script cannot fail." This is a tricky constraint in distributed systems. If the background email script crashes, the user never knows, yet the promise of notification was broken.
With a message queue (like Laravel's Redis or database-based queues), you can configure the job to retry on failure. The system administrator's restriction on cron frequency does not apply here because the trigger is event-driven, not time-based. The queue worker runs independently, polling for new jobs. If the email server rejects a batch due to policy limits, the job retries until the list is exhausted or hits a hard limit.
If you must use direct file execution without a queue driver, you need a robust logging mechanism inside send_emails.php. It should append its progress and any errors to a dedicated log file rather than relying on echo or print_r, which would clutter your main web server logs or cause output buffering issues if the main script tries to read them.
User Experience and Browser Hanging
The second problem you identifiedâusers closing tabs and causing subsequent browser hangsâis resolved by the asynchronous pattern itself. When the main PHP script finishes and returns a successful HTTP response (200 OK) immediately after dispatching the job, the connection between the browser and server is closed. The background process runs on the server independently.
If the user closes the tab or navigates to another page while the background job is still sending emails, there is no lingering PHP process holding a socket open for that specific request. The web server (Nginx/Apache) will have already handed off the response and released the connection pool. Consequently, subsequent requests to your domain will load normally without hanging, regardless of whether the background email task is still in progress or has finished.
By shifting the heavy lifting to a decoupled processâwhether via a queue worker or an asynchronous shell commandâyou satisfy the requirement for instant feedback while adhering to email server policies and infrastructure limitations.
