Read text file with php with message

What is the problem with my code? I have two files in one 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 does not display "your el registered"

This is a simple syntactical question for further development, not intended to be protected.

Other answers to the questions did not help solve my problem.

+4
source share
3 answers

I think the problem could be in the call file_get_contents- I tried the following and it seems to work correctly. (oops, forgot 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>';
        }
?>
+1
source

index.php session_start(); php, http://php.net/manual/en/function.strcmp.php strcmp();

if (strcmp($_SESSION['pass'], $password))  {
    echo 'you are logged in';
} else {
    echo'<form method="POST" action="">
    <input type="password" name="pass">
    </form>';
}
+1

-

<?php 

$password=file_get_contents(realpath( __DIR__.'/pass.txt' ),FILE_TEXT | FILE_SKIP_EMPTY_LINES);

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>';
}

?>
0

Source: https://habr.com/ru/post/1607460/


All Articles