PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
157: ReactPHP for Event-Driven PHP
I want to show you something that almost everyone trips over when they first move from traditional synchronous PHP to ReactPHP. You've spent years writing PHP where the code executes line-by-line, and the server waits for the database or an API to respond before moving on. In the event-driven world, that habit will absolutely kill your application's performance.
<?php
require 'vendor/autoload.php';
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) {
// Imagine this is a slow external API call
$data = file_get_contents('https://api.example.com/slow-endpoint');
return React\Http\Message\Response::plaintext("The API said: " . $data);
});
$socket = new React\Socket\SocketServer('0.0.0.0:8080');
$http->listen($socket);
echo "Server running at http://127.0.0.1:8080\n";
The Silent Freeze
At first glance, this looks fine. It's a simple HTTP server that fetches some data and returns it. But here is the problem: if you open two browser tabs and hit that endpoint simultaneously, the second request won't even start until the first one is completely finished. Your "asynchronous" server is behaving exactly like a slow, single-threaded synchronous script.
The culprit is file_get_contents(). This is a blocking function. Because ReactPHP runs on a single-threaded event loop, when you call a blocking function, you aren't just pausing that one request—you are pausing the entire server. The event loop literally stops spinning, and no other events (like new TCP connections) can be processed until that network call returns.
Switching to Non-Blocking I/O
To fix this, we have to stop using PHP's built-in filesystem and network functions and instead use the ReactPHP ecosystem. We need a client that returns a Promise instead of the actual data. This tells the event loop: "Go ahead and handle other requests; just let me know when this specific data arrives."
<?php
require 'vendor/autoload.php';
$loop = React\EventLoop\Loop::get();
$browser = new React\Http\Browser(); // This is the non-blocking client
$http = new React\Http\HttpServer(function (Psr\Http\Message\ServerRequestInterface $request) use ($browser) {
// We return the promise itself, not the response
return $browser->get('https://api.example.com/slow-endpoint')
->then(function (Psr\Http\Message\ResponseInterface $response) {
return React\Http\Message\Response::plaintext("The API said: " . (string)$response->getBody());
}, function (Exception $e) {
return React\Http\Message\Response::plaintext("Error: " . $e->getMessage())->withStatus(500);
});
});
$socket = new React\Socket\SocketServer('0.0.0.0:8080');
$http->listen($socket);
echo "Server running at http://127.0.0.1:8080\n";
How the Event Loop Actually Handles This
Notice the difference in the logic flow. In the fixed version, $browser->get() initiates the request and immediately returns a Promise object. It doesn't wait for the bytes to come back from the wire.
- The server hands that Promise back to the ReactPHP HTTP handler.
- The event loop is now free to pick up the next incoming request from a different user.
- When the external API finally responds, the event loop triggers the
then()callback. - Only then is the final response sent back to the original client.
I can't stress this enough: if you use sleep(), PDO (without a wrapper), or curl_exec() inside a ReactPHP loop, you've effectively turned your high-performance server back into a standard PHP script, but with more overhead. Always look for the "async" version of the library you're using.
📋 Practical Task
Build a Concurrent Website Availability Checker
Your task is to create a CLI tool using ReactPHP that checks the status of multiple websites simultaneously. Instead of checking them one-by-one in a loop (which would be slow), you must initiate all requests concurrently.
Requirements:
- Create an array of at least 5 different URLs (e.g., google.com, github.com, etc.).
- Use
React\Http\Browserto send a GET request to each URL. - Use
React\Promise\all()to wait for all requests to complete. - When all requests are finished, print a summary list showing which sites returned a 200 OK status and which ones failed.
- The total execution time of the script should be roughly equal to the slowest single request, not the sum of all requests.
There are no comments for now.