There is actually a way of changing http to https by using a .htaccess file.
It looked better to me then trying to get a php script to detect all that, but I wasn't able to get the .htaccess method to work for me (wasn't able to spend much time on it).
You may also want to put SERVER variables into other variables. I found that $foo['bar'] will make header() not work correctly. So maybe something like $path1=$SERVER['HTTP_HOST'].
Anyway, there is my 2 cents. Sorry I couldn't help more.
Good luck!