How can PHP be used to handle authentication for external resources on a different server or port?

When handling authentication for external resources on a different server or port in PHP, you can use cURL to make HTTP requests to the external server and pass authentication credentials in the request headers. This allows you to securely access resources on a different server or port while ensuring proper authentication.

<?php
// Set the external server URL and authentication credentials
$external_url = 'https://external-server.com/resource';
$username = 'username';
$password = 'password';

// Initialize cURL session
$ch = curl_init();

// Set cURL options to make a GET request with authentication headers
curl_setopt($ch, CURLOPT_URL, $external_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Basic ' . base64_encode($username . ':' . $password)
));

// Execute the cURL session and store the response
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Output the response from the external server
echo $response;
?>