PHP-protection for a HTML-file
To PHP-protect a HTML-document 'somefile.html' without changing its extension or configuring the server to interpret HTML as PHP, we can do the following:
1.
In somefile.html, put the following script at the very top of the head section:
<script>
/* Remove if you don't want password-protection for the HTML-file */
if(!document.getElementById('php_protection')){window.location.replace('somefile.php')}
</script>
2.
That script references a file named 'somefile.php'. So we create it. It must look like this:
<!DOCTYPE html>
<html>
<head>
<script>
function loadDoc(url) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
top.document.write('<div id="php_protection" style="position: absolute; width:0; height:0"><\/div>' + request.responseText)
}
};
request.open("GET", url, false);
request.send();
}
</script>
</head>
<body>
<?php
$pass = $_POST['pass'];
//change password to your liking;
if(!($pass == "secretpassword"))
{
echo '<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Login</title></head><body ><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
<div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-family: arial; font-size: 20px; line-height: 40px">
<div style="display: inline-block; width: 150px">Password:</div> <input type="password" name="pass" style="border: 1px solid black; width: 200px; height: 30px; font-family: arial; font-size: 16px; padding-left: 10px" required></input>
<div style="height: 20px"> </div>
<input type="submit" name="submit" value="Login" style="font-family: arial; font-size: 16px;" ></input></div>
</form>
</body></html>';
exit();
}
//change password to your liking;
if($pass == "secretpassword")
{
echo '<script>loadDoc("somefile.html")</script>';
}
?>
</body>
</html>
Put both files in the same same folder.