开发者

PHP: Adding text to a file

I'm trying to set up authentication on my server, however, I know little about Php.

I have a php file filled with users and passwords:

 function getPassword( $user )
 {
    // the user/password database. For very small groups
    // of users, you may just get away with expanding this
    // array.
    $passwords= array (
        'user1' => 'password1',
        'user2' => 'password2',
        'user3' => 'password3',
        'user4' => 'password4'
         );
    $password = $passwords[ $user ];
    if ( NULL == $password )
        return NULL;

Without manually editing the array of passwords, I want a php file to read in user inputs for usernames and passwords and append it to the array.

I have a vague idea of how this could work by looking up documentation:

<?php
function fwr开发者_C百科ite_stream($fp, $string) {
    $fp = fopen('shit.php', 'w');
    for ($written = 0; $written < strlen($string); $written += $fwrite) {
        $fwrite = fwrite($fp, substr($string, $written));
        if ($fwrite === false) {
            return $written;
        }
    }
    return $written;
    fclose($fp);
}
?>

How do I tell this to write to the array?


I would not hardcode the list of usernames and passwords in your PHP script. I would instead do something like this for reading the array from disk:

// Web server must have read permission for the file,
// but it should be placed outside of public_html
// for security reasons.
$gPasswordFile = '/home/kevin/password.db';

// Read the password file's entire contents as a string.
$contents = file_get_contents($gPasswordFile);

// Unserialize the file's contents, assuming an empty array
// if the file does not exist.
$passwords = $contents ? unserialize($contents) : array();

For writing the array to disk:

file_put_contents($gPasswordFile, serialize($contents)) or die('Could not save password file!');

If you were to have thousands of users as on a public web site, it would be inefficient to load the entire user database for every attempted login. Then you would likely turn to a real DBMS such as MySQL to store the information.

(As a side note, you really should be hashing passwords with a per-user salt to limit the effect of a password file compromise. Save that for another question though.)


I'd strongly recommend against what you're trying to do now. Why not store the passwords in a separate file, and have the script read/write that? Manipulating PHP in this way is asking for trouble, as you'll need to keep in mind every kind of input your users may throw at it.

I think your best bet is file_put_contents('filename.txt', "\"$username\",\"$password\\n" FILE_APPEND); (of course, you'll have to apply escaping and/or validation on the username/password)

Then get the contents with $passwords = fgetcsv('filename.txt')

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜