【问题标题】:PHP: Adding text to a filePHP:将文本添加到文件中
【发布时间】:2011-01-16 07:47:55
【问题描述】:

我正在尝试在我的服务器上设置身份验证,但是我对 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);
}
?>

如何告诉它写入数组?

【问题讨论】:

标签: php arrays file


【解决方案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 来存储信息。

(顺便说一句,您确实应该使用每个用户的 salt 对密码进行哈希处理,以限制密码文件泄露的影响。不过,将其留作另一个问题。)

【讨论】:

    【解决方案2】:

    我强烈建议您不要现在尝试做的事情。为什么不将密码存储在单独的文件中,并让脚本读/写呢?以这种方式操作 PHP 是自找麻烦,因为您需要牢记用户可能向它提出的各种输入。

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

    然后用$passwords = fgetcsv('filename.txt')获取内容

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 1970-01-01
      • 2013-11-25
      • 1970-01-01
      • 2013-01-04
      • 2016-08-29
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      相关资源
      最近更新 更多