在 PHP 中创建 2 个文件的关联数组
Creating associative array of 2 files in PHP
我正在 php 本地主机上制作登录系统。
当新用户注册时,
-用户名存储在/registration/usernames.txt,
-密码存储在/registration/passwords.txt
当我将这些写入文件 usernames.txt
和 passwords.txt
时,我是这样做的:
fwrite( $file_usernames, $usernameR.', ' );
fwrite( $file_passwords, $passwordR.', ' );
所以当:
Username: John
Password: blablabla
被输入,它存储在文件usernames.txt中为:
John,
在passwords.txt中存储为:
blablabla,
现在,当我想登录任何注册用户时,首先我想创建一个关联数组,其中 "key" 是用户名,"value" 是密码,然后在数组中循环并查看用户名和密码是否正确。
我试过这样做:
// create array of: "username" => "password"
$file_usernames_read = fread( fopen( "./registration/usernames.txt", "r" ), filesize( "./registration/usernames.txt" ) );
$file_passwords_read = fread( fopen( "./registration/passwords.txt", "r" ), filesize( "./registration/passwords.txt" ) );
$usernames = array( $file_usernames_read );
$passwords = array( $file_passwords_read );
$together = array_combine( $usernames, $passwords );
但这种方法行不通,我也不知道还有什么其他方法可以尝试。
感谢您的帮助。
应该这样做:
$usernames = explode(", ", file_get_contents("./registration/usernames.txt"));
$passwords = explode(", ", file_get_contents("./registration/passwords.txt"));
$map = array_combine($usernames, $passwords);
但通常您应该在将密码存储到文本文件之前加密它们(使用 password_hash)。
并且您还应该考虑使用数据库系统来存储用户数据,而不是纯文本文件。
我正在 php 本地主机上制作登录系统。
当新用户注册时,
-用户名存储在/registration/usernames.txt,
-密码存储在/registration/passwords.txt
当我将这些写入文件 usernames.txt
和 passwords.txt
时,我是这样做的:
fwrite( $file_usernames, $usernameR.', ' );
fwrite( $file_passwords, $passwordR.', ' );
所以当:
Username: John
Password: blablabla
被输入,它存储在文件usernames.txt中为:
John,
在passwords.txt中存储为:
blablabla,
现在,当我想登录任何注册用户时,首先我想创建一个关联数组,其中 "key" 是用户名,"value" 是密码,然后在数组中循环并查看用户名和密码是否正确。
我试过这样做:
// create array of: "username" => "password"
$file_usernames_read = fread( fopen( "./registration/usernames.txt", "r" ), filesize( "./registration/usernames.txt" ) );
$file_passwords_read = fread( fopen( "./registration/passwords.txt", "r" ), filesize( "./registration/passwords.txt" ) );
$usernames = array( $file_usernames_read );
$passwords = array( $file_passwords_read );
$together = array_combine( $usernames, $passwords );
但这种方法行不通,我也不知道还有什么其他方法可以尝试。
感谢您的帮助。
应该这样做:
$usernames = explode(", ", file_get_contents("./registration/usernames.txt"));
$passwords = explode(", ", file_get_contents("./registration/passwords.txt"));
$map = array_combine($usernames, $passwords);
但通常您应该在将密码存储到文本文件之前加密它们(使用 password_hash)。
并且您还应该考虑使用数据库系统来存储用户数据,而不是纯文本文件。