PHP: Enforce HTTPS into URL if not present or typed in
I just encrypted my website, and everything works well. Except that when you enter the domain as "domain.com" or "www.domain.com", the line will not be secure, until you actually click a link on the website that directs you to a secure page. This is annoying. So I decided that I wanted to use PHP to enforce HTTPS into the URL. I have tried two methods: Method 1: if (!isset($_SERVER['HTTPS']) || !$_SERVER['HTTPS']) { // if request is not secure, redirect to secure url $url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; header('Location: ' . $url); exit; } Method 2: if(empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] !== "on") { header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); } Both give the same error: Warning: Cannot modify header information - headers already sent by (output started at domain.com/connection.php:1) in domain.com/connection.php on line 5. The troublesome line would then be the header, which is the last line in both approaches. What can I do about it? When I type echo instead of header to print out the URL, the URL seems to be right, so I don't understand why the user isn't redirected. It also seems like that it works with all URLs, except the URL is only the domain. E.g.: www.domain.com/folder -> Redirects to HTTPS www.domain.com -> Gives error