What are the potential pitfalls of using $_SERVER['SERVER_NAME'] or $_SERVER['HTTP_HOST'] to retrieve the Internet address in PHP?

Potential pitfalls of using $_SERVER['SERVER_NAME'] or $_SERVER['HTTP_HOST'] include susceptibility to header injection attacks and unreliable results due to the possibility of the values being manipulated by the client. To mitigate these risks, it is recommended to use a combination of SERVER_NAME and SERVER_PORT to construct a secure URL.

$serverName = $_SERVER['SERVER_NAME'];
$serverPort = $_SERVER['SERVER_PORT'];
$isSecure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
$protocol = $isSecure ? 'https://' : 'http://';

$fullUrl = $protocol . $serverName . ($serverPort == 80 || $serverPort == 443 ? '' : ':' . $serverPort);
echo $fullUrl;