What are the potential pitfalls of not setting a timeout in a PHP script that communicates with a server?

Without setting a timeout in a PHP script that communicates with a server, the script may hang indefinitely if the server does not respond or if there are network issues. This can lead to performance issues and potential resource exhaustion on the server. To prevent this, it's important to set a timeout for the server connection in order to handle these situations gracefully.

// Set a timeout for the server connection
$timeout = 10; // 10 seconds

$context = stream_context_create([
    'http' => [
        'timeout' => $timeout
    ]
]);

$response = file_get_contents('http://example.com/api/data', false, $context);

if ($response === false) {
    // Handle timeout or connection error
    die('Error: Server connection timed out');
}

// Process the response data
echo $response;