Why file_get_contents Blocks and How to Avoid It
When you need to fetch data from an external endpoint in PHP, the default approach often involves file_get_contents(). While convenient for synchronous tasks where you must wait for the full response before proceeding, this method blocks execution. In your specific use case, the first requirement is to trigger a request without waiting for the server to respond. This pattern is common when initiating background jobs or fire-and-forget actions.
To achieve non-blocking behavior in vanilla PHP, fsockopen is indeed a viable alternative to cURL, though it requires careful handling of streams and timeouts. The core mechanism involves opening a socket connection, sending the HTTP GET request headers manually, and then immediately closing the stream before the response body arrives. This prevents the script from hanging while waiting for the remote server.
Here is how you can implement make_request to handle the fire-and-forget scenario:
function make_request_non_blocking(string $url): void {
$parsedUrl = parse_url($url);
$host = $parsedUrl['host'];
$path = $parsedUrl['path'] ?? '';
// Create a socket connection
if (!fsockopen($host, 80, $errno, $errstr, 5)) {
throw new Exception("Connection failed: $errstr");
}
// Construct the raw HTTP request
$request = "GET $path HTTP/1.1\r\n";
$request .= "Host: $host\r\n";
$request .= "User-Agent: PHP-Script\r\n";
$request .= "Connection: close\r\n\r\n";
// Send the request immediately
fwrite($stream, $request);
// Close the stream immediately to avoid blocking on the response
fclose($stream);
}
In this implementation, we explicitly set Connection: close in the headers. This instructs the remote server to terminate the connection as soon as it processes the request headers, rather than waiting for a full HTTP response or keeping the socket open. By closing the local stream with fclose() right after writing, the script returns control instantly without reading the response body.
For your second requirementâretrieving the actual text outputâyou must abandon the non-blocking approach. Fetching content inherently requires reading the response stream until EOF (End Of File) or a specific length is reached. Using file_get_contents() here is perfectly fine and often preferred for simplicity unless you need fine-grained control over headers or error handling.
If you require more robust capabilities, such as setting custom headers, handling redirects automatically, or managing SSL certificates, the built-in HTTP client in PHP 7.0+ offers a cleaner solution without needing cURL:
$ch = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "User-Agent: MyApp/1.0\r\nAccept: application/json\r\n",
'timeout' => 5, // Prevents hanging indefinitely
]
]);
$output = file_get_contents('http://www.externalsite.com/script2.php?variable=45', false, $ch);
This approach maintains synchronization (waiting for the response) but removes the dependency on cURL or PECL extensions. It is important to note that if the external server takes longer than your timeout threshold, file_get_contents will throw a ErrorException. In production environments, always wrap these calls in try-catch blocks or set appropriate timeouts to prevent your application from freezing indefinitely.
While the LaravelCompany platform often encourages using their specific HTTP helpers for API interactions, understanding these underlying mechanisms ensures you can troubleshoot issues when external dependencies fail or when working within frameworks that don't provide built-in abstractions. The choice between fsockopen for fire-and-forget tasks and file_get_contents or cURL for data retrieval depends entirely on whether the response payload is required during the current execution cycle.