I had created a simple password protection page for a PHP webpage by searching online. below is the code.
protect.php:
<?php
namespace Protect;
function with($form, $password, $scope=null) {
if( !$scope ) $scope = current_url();
$session_key = 'password_protect_'.preg_replace('/\W+/', '_', $scope);
session_start();
if( $_POST['password'] == $password ) {
$_SESSION[$session_key] = true;
redirect(current_url());
}
if( $_SESSION[$session_key] ) return;
require $form;
exit;
}
function current_url($script_only=false) {
$protocol = 'http';
$port = ':'.$_SERVER["SERVER_PORT"];
if($_SERVER["HTTPS"] === 'on') $protocol .= 's';
if($protocol === 'http' && $port === ':80') $port = '';
if($protocol === 'https' && $port === ':443') $port = '';
$path = $script_only ? $_SERVER['SCRIPT_NAME'] : $_SERVER['REQUEST_URI'];
return $protocol."://".$_SERVER[SERVER_NAME].$port.$path;
}
function redirect($url) {
header("Location: ".$url);
exit;
}
Form.php:
<html>
<body>
<form method="POST">
<?php
if( $_SERVER['REQUEST_METHOD'] === 'POST' ) {
?>
Invalid password
<?php
}
?>
<p>Enter password for access:</p>
<input type="password" name="password">
<button type="submit">Submit</button>
</form>
</body>
</html>
At the top of the php webpage which is to be protected with security password:
<?php
require_once('protect.php');
Protect\with('form.php', 'demo'); // demo is the password
?>
It's working fine but I am getting an error as
Undefined index: password in C:\xampp\htdocs\iv\admin\protect.php on line 9 and session start() is already defined.
(On top of the php page which is to be protected).
When I tried to make any changes its completely not working.
Anybody, please help and guide me where exactly the error.