PHP:向文件添加文本

时间:2011-01-16 07:47:55

标签: php arrays file

我正在尝试在我的服务器上设置身份验证,但是,我对Php知之甚少。

我有一个填充了用户和密码的php文件:

 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;

如果不手动编辑密码数组,我想要一个php文件读取用户输入的用户名和密码,并将其附加到数组中。

通过查找文档我对这是如何工作有一个模糊的概念:

<?php
function fwrite_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);
}
?>

如何告诉它写入数组?

2 个答案:

答案 0 :(得分:1)

我强烈建议你反对你现在要做的事情。为什么不将密码存储在单独的文件中,并将脚本读/写?以这种方式操作PHP会引发麻烦,因为您需要记住用户可能会输入的每种输入。

我认为你最好的选择是file_put_contents('filename.txt', "\"$username\",\"$password\\n" FILE_APPEND);(当然,你必须对用户名/密码进行转义和/或验证)

然后使用$passwords = fgetcsv('filename.txt')

获取内容

答案 1 :(得分:1)

我不会硬编码PHP脚本中的用户名和密码列表。我宁愿做这样的事情从磁盘读取数组:

// 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();

将数组写入磁盘:

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

如果您在公共网站上拥有数千名用户,那么为每次尝试登录加载整个用户数据库效率都很低。然后你可能会转向一个真正的DBMS,比如MySQL来存储信息。

(作为旁注,你真的应该使用每用户盐来哈希密码以限制密码文件泄露的影响。但是将其保存为另一个问题。)