PHP

PHP Post Processing by disconnecting HTTP connection and continuing the remaining logics

CK CK 3788 
Created at  
1,807 0 0

To disconnect an HTTP connection and continue executing tasks in PHP, you can utilize the following approach. The idea is to send a response to the client, terminate the HTTP connection, and then continue executing any background tasks.

Here's an example of how to do this in PHP:

Step-by-Step Process:

  1. Send a response to the client and close the connection:
    • Flush the output buffer.
    • Close the connection to the client.
    • Continue script execution after the connection is closed.
  2. Keep the script running in the background:
    • Ignore user abort so the script continues to run even after the client has disconnected.

Example Code:

<?php
// Turn off output buffering
ob_end_clean();

// Tell the browser that the connection is close (HTTP 1.1)
header("Connection: close");
// Ensure that the script doesn't time out
ignore_user_abort(true);
set_time_limit(0); // Disable time limits

// Send the response to the client
echo "HTTP response has been sent!";
ob_flush();
flush();

// Close the connection with the client
if (function_exists('fastcgi_finish_request')) {
    fastcgi_finish_request(); // For Nginx with FastCGI
}

// Client is disconnected here, but the script continues to run

// Do your background tasks here
sleep(5); // Simulate a time-consuming task
file_put_contents("background_task_log.txt", "Task completed at: " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);

// Additional background processing
?>

Explanation:

  1. ob_end_clean(): Disables output buffering so that any buffered content is flushed.
  2. header("Connection: close"): Informs the client that the server has closed the connection.
  3. ignore_user_abort(true): Ensures the script continues running even if the user has disconnected.
  4. set_time_limit(0): Disables the execution time limit so the script can run indefinitely.
  5. echo, ob_flush(), and flush(): Send the output to the client before closing the connection.
  6. fastcgi_finish_request(): If you're using Nginx with FastCGI, this function will flush the response and close the connection, allowing the script to continue in the background.
  7. Background task: After closing the connection, the script can continue executing any task such as logging or performing other long-running operations.

This approach ensures that the user gets a response quickly while the server continues to process the remaining tasks in the background.

Tags Background Process Disconnect an HTTP connection HTTP Connection Post Processing fastcgi_finish_request ob_end_clean Facebook X
Comments 0
  1. When you Postgresql Module is not able to open connection : Doubt your libpq version
    474
  2. How to Get a YouTube Channel ID from a URL in PHP
    1,024
  3. Building a MCP server in PHP
    631
  4. PHP 7 vs PHP 8
    1,243
  5. Upgrading PHP 7.4 to PHP 8.1 in CentOS 7
    647
  6. gRPC Server with PHP
    504
  7. PHP Code to Fetch current Coinbase Assets (Balances)
    440
  8. PHP Code to Fetch PEPE coin pricing based in USD from Coinbase
    363
  9. Google Single Sign-On implementation with PHP
    1,373
  10. PHP Superglobal Variables do not require additional syntax to access it
    2,633
  11. Run Python Code with Virtual Environment in PHP
    673
  12. PHP Simplified Operators
    317
  13. PHP Heredoc (aka Nowdoc)
    437
  14. WordPress Remote Posting with PHP
    1,682
  15. Google BigQuery Example to converted Nested FIelds in JSON
    459
  16. Verifying Apple In-App Purchase validation receipt with PHP
    1,785
  17. Useful code for file-based Unit Test in PHP
    500
  18. Function Overloading Implementation in PHP with Magic Mathods
    1,755
  19. PHP Magic - the Null Coalescing Operator (??) - return the value if the give variable is NULL
    1,670
  20. How do I find php.ini on Mac?
    492
  21. Mastering Excel Data Importation in PHP
    554
  22. Create Blob Image in HTML based on the given Text, Width and Height in the Center of the Image without saving file
    972
  23. How do I determine the client IP type (IPv4/IPv6) in PHP
    833
  24. What is 302 Found Redirection in HTTP 1.1?
    490
  25. Implementing a Versatile DNS Server in PHP: Handling A, AAAA, CNAME, and TXT Records
    618
  26. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  27. CentOS 7 PHP Apache Kafka: Installation, Examples, and System Diagram
    306
  28. Apache Kafka Explained: Powering Netflix, Building with PHP
    491
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    39
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,611
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    243
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    582
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    338
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    216
  30. Understanding Data Lineage
    260