Redirect to www in php

Here is a simple way to redirect any hit to www using php .
and also keep the protocol ( http/https )

if($_SERVER[HTTPS])
{
	header('Location:' . "http://www.$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ,true, 301);
}
else
{
	header('Location:' . "https://www.$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" ,true, 301);
}