Best practise to execute long running PHP scripts

Best practise to execute long running PHP scripts

July 17, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Best practise to execute long running PHP scripts

Executing Long-Running PHP Scripts: Best Practices for 2017

Long-running PHP scripts are a common requirement in modern web applications. They can be used to perform heavy processing tasks, update databases, or run periodic jobs like backups and reports. However, running such scripts within the traditional HTTP request-response cycle is inefficient and resource-intensive.

In this article, we will explore best practices for executing long-running PHP scripts that meet your specific requirements: invoking them via an HTTP request without waiting for a response, and running them periodically every night by default without manual intervention on clients’ servers. We will focus on plain PHP solutions rather than using frameworks or libraries.

The Challenge of Long-Running Scripts in PHP

By default, when you execute a long-running script directly from your web server (e.g., via an HTTP request), it blocks the entire process until completion. This means that no other requests can be processed during this time, leading to poor performance and potential timeout errors.

Moreover, if you want the script to run every night by default on clients’ servers without manual intervention, adding a cron job is not feasible since you won’t have access to their systems. This adds an extra layer of complexity to the solution.

Solution: Background Processing with PHP

To overcome these challenges, we can utilize background processing techniques in PHP. The key idea is to start the long-running script asynchronously, allowing it to execute independently while the main HTTP request continues promptly.

Approach 1: Forking and Ignoring Parent Process

One approach is to use PHP’s built-in pcntl_fork() function to create a child process that will handle the long-running task. Here’s an example:

<?php

// Check if this script was called directly (not included)
if (!defined('PHPUNIT_RUN')) {
    // Fork and start the background process
    $pid = pcntl_fork();

    switch ($pid) {
        case -1:
            die("Unable to fork");
        case 0: // Child process
            // Your long-running code here
            break;
        default: // Parent process
            exit; // Immediately terminate the parent process
    }
}

// If included (not called directly), return a response
if (!defined('PHPUNIT_RUN')) {
    echo "Processing started";
}

In this example, when you call the script directly via an HTTP request, it forks the child process to handle the long-running task. The parent process immediately terminates, freeing up system resources and allowing other requests to be processed.

Approach 2: Using a Job Queue

Another approach is to use a job queue that supports background processing. This allows you to add jobs to the queue when an HTTP request arrives, and then have worker processes pick them up and execute them asynchronously.

There are several PHP libraries available for implementing job queues, such as Resque or Beanstalkd. These libraries provide a robust infrastructure for managing background jobs efficiently.

Periodic Execution with Cron in PHP

To run the script every night by default without manual intervention, you can utilize PHP itself to trigger the job periodically. The cron function in PHP allows you to schedule tasks at specific intervals or dates.

Here’s an example of how to use it:

<?php

// Check if this is a cron execution (not an HTTP request)
if (!isset($_SERVER['REQUEST_TIME_FLOAT'])) {
    // This script was called by the cron job, so execute the long-running task here
    // Your long-running code here
} else {
    // If not a cron execution, it's an HTTP request - return a response
    echo "Script is running in background";
}

In this example, you can configure your server to run this script periodically using the cron daemon. The script will check if the current request was triggered by an actual PHP script (REQUEST_TIME_FLOAT is not set) or via an HTTP request (which sets REQUEST_TIME_FLOAT).

Conclusion

Executing long-running scripts in PHP requires careful consideration and proper handling to ensure optimal performance, resource utilization, and user experience. By using background processing techniques like forking and job queues, you can efficiently handle these tasks without blocking the main web server process.

Additionally, utilizing PHP’s built-in cron function allows you to schedule periodic execution of your long-running scripts, making it easy to automate recurring tasks on clients’ servers without manual intervention.

Remember that proper error handling, logging, and monitoring are essential when dealing with background processes. Regularly review the logs for any failed or incomplete jobs to ensure the system’s reliability.

At Laravel Company, we specialize in delivering high-quality PHP solutions tailored to your specific business needs. If you require assistance in implementing long-running scripts, optimizing performance, or setting up background processing systems, don’t hesitate to reach out to our team of experienced developers.

Database Performance Cron Errors

Our network