Problem with simple PHP login Script

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • carmstrong@cbamedia.com

    Problem with simple PHP login Script

    I'm new to PHP and I'm trying to write up a simple PHP login page
    script to authenticate users from a flat file. I've managed to make
    most of it work, except that it only accepts the last user on the
    user/password file, and I'm not sure why. (I.e. the user.txt file is:

    user1:pass1
    user2:pass2
    user3:pass3

    and it only works for user3:pass3)

    Here is my code:

    <?php

    $auth = false; // Assume user is not authenticated

    if (isset( $_POST['txtUsername'] ) && isset( $_POST['txtPassword'] )) {

    // Read the entire file into the variable $file_contents

    $filename = 'user.txt';
    $fp = fopen( $filename, 'r' );
    $file_contents = fread( $fp, filesize( $filename ) );
    fclose( $fp );

    // Place the individual lines from the file contents into an array.

    $lines = explode ( "\n", $file_contents );

    // Split each of the lines into a username and a password pair
    // and attempt to match them to $PHP_AUTH_USER and $PHP_AUTH_PW.

    foreach ( $lines as $line ) {

    list( $username, $password ) = explode( ':', $line );

    if ( ( $username == $_POST['txtUsername'] ) &&
    ( $password == $_POST['txtPassword'] ) ) {

    // A match is found, meaning the user is authenticated.
    // Stop the search.

    $auth = true;
    break;

    }
    }

    }

    if (! $auth ) {

    ?>

    <h1>Login</h1>

    <form name="form" method="post" action="<?php echo
    $_SERVER['PHP_SELF'];?>">
    <p><label for="txtUsernam e">Username: </label>
    <br /><input type="text" title="Enter your Username" name="txtUserna me"
    /></p>

    <p><label for="txtpasswor d">Password: </label>
    <br /><input type="password" title="Enter your password"
    name="txtPasswo rd" /></p>

    <p><input type="submit" name="Submit" value="Login" /></p>

    </form>

    <?php

    } else {

    echo '<P>You are authorized!</P>';
    }

    ?>

  • Chung Leong

    #2
    Re: Problem with simple PHP login Script

    carmstrong@cbam edia.com wrote:[color=blue]
    > I'm new to PHP and I'm trying to write up a simple PHP login page
    > script to authenticate users from a flat file. I've managed to make
    > most of it work, except that it only accepts the last user on the
    > user/password file, and I'm not sure why. (I.e. the user.txt file is:[/color]

    It's probably because the text file was created in Windows, where the
    line separator is \r\n. When you do the explode on \n, all the elements
    except the last will have a \r attached at the end, thus not matching
    what was entered.

    Use trim() on $username should fix the problem.

    Comment

    Working...