What is the problem with my code? I've fot two files in the same folder: index.php and pass.txt:
This is pass.txt:
qwerty
And this is index.php:
<?php
$password=file_get_contents('pass.txt');
session_start();
if (isset($_SESSION['timeout'])) {
if ($_SESSION['timeout'] + 10 < time()) {
session_destroy(); } }
else {
$_SESSION['pass']="" ; $_SESSION['timeout']=time(); }
if (isset($_POST["pass"])) {
$_SESSION['pass']=$_POST['pass'] ;
}
if($_SESSION['pass'] == $password) {
echo 'you are logged in';
} else {
echo'<form method="POST" action="">
<input type="password" name="pass">
</form>';
}
?>
PROBLEM: When I write 'qwerty' in the input field and submit, it doesn't display "your ale logged in"
It is a mere syntax question for further development, not intended to protect anything.
Other answered questions did not solve my problem.
I think the issue may have been the call to file_get_contents
- I tried the following and it appears to function correctly. ( oops, forgot the session_start()
for this example )
<?php
session_start();
if( isset( $_SESSION['timeout'] ) && $_SESSION['timeout'] + 10 < time() ) session_destroy();
else {
$_SESSION['pass']="" ;
$_SESSION['timeout']=time();
}
$password=file_get_contents( realpath( __DIR__.'/pass.txt' ), FILE_TEXT | FILE_SKIP_EMPTY_LINES );
echo 'The password from the text file: '. $password;
if( isset( $_POST["pass"] ) ) $_SESSION['pass']=$_POST['pass'] ;
if( strlen( $password ) > 0 && trim( $_SESSION['pass'] ) === trim( $password ) ) {
echo 'you are logged in';
} else {
/* for dev I use a local file, aliased as /stackoverflow/ */
echo'<form method="POST" action="">
<input type="password" name="pass">
<input type="submit" value="login">
</form>';
}
?>