使用 post 从 php 读取文本文件

read text file from php with post

我的代码有什么问题?我在同一个文件夹中有两个文件:index.php 和 pass.txt:

这是pass.txt:

qwerty

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

?>

问题:当我在输入字段中输入 'qwerty' 并提交时,它不显示 "your ale logged in"

纯语法问题有待进一步开发,无意保护任何东西。

其他回答的问题没有解决我的问题。

在您的 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>';
}

使用此代码-

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

?>

我认为问题可能出在对 file_get_contents 的调用上 - 我尝试了以下方法,它似乎运行正常。 (哎呀,忘记了这个例子的 session_start()

<?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 /Whosebug/ */
            echo'<form method="POST" action="">
                    <input type="password" name="pass">
                    <input type="submit" value="login">
                </form>';
        }
?>