PHP: Enforce HTTPS into URL if not present or typed in | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

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

14th Mar 2018, 2:38 AM
Spise Pause
Spise Pause - avatar
2 Answers
+ 2
Okay, I solved this using javascript: <script type="text/javascript"> if (location.protocol != 'https:') { location.href = 'https:' + window.location.href.substring(window.location.protocol.length); } </script>
14th Mar 2018, 2:45 AM
Spise Pause
Spise Pause - avatar
+ 1
Apparently, this can also be done from the .htaccess file: RewriteCond %{HTTPS} off RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
14th Mar 2018, 4:41 PM
Spise Pause
Spise Pause - avatar