从帖子中读取php中的文本文件

时间:2015-09-15 12:28:57

标签: php file post text flat-file

我的代码有什么问题?我在同一个文件夹中输入了两个文件: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&#39;在输入字段中提交,它不显示&#34;您的啤酒登录&#34;

这仅仅是进一步开发的语法问题,并非旨在保护任何内容。

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

3 个答案:

答案 0 :(得分:1)

在index.php开始会话myFactory的创建中 要比较php中的字符串,请使用http://php.net/manual/en/function.strcmp.php session_start();

strcmp();

答案 1 :(得分:1)

我认为问题可能是对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 /stackoverflow/ */
            echo'<form method="POST" action="">
                    <input type="password" name="pass">
                    <input type="submit" value="login">
                </form>';
        }
?>

答案 2 :(得分:0)

使用此代码 -

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

?>