所以这是我非常简单和基本的帐户系统(只是一个学校项目),我希望用户能够更改他们的密码.但我不确定如何在一行中替换密码值,保持所有其他值相同.
CSV文件:
ID,Username,Email,DateJoined,Password,UserScore,profilePics
1,Test,Test@Test.com,03/12/2014,Test,10,uploads/profilePics/Test.jpg
2,Alfie,Alfie@test.com,05/12/2014,1234,136,uploads/profilePics/Alfie.png
PHP:
(“cNewPassword”=确认新密码)
session_start();
if(empty($_POST['oldPassword']) || empty($_POST['newPassword']) || empty($_POST['cNewPassword'])) {
die("ERROR|Please fill out all of the fields.");
} else {
if($_POST['newPassword'] == $_POST['cNewPassword']) {
if ($_POST['oldPassword'] == $_SESSION['password']) {
$file = "Database/Users.csv";
$fh = fopen($file, "w");
while(! feof($file)) {
$rows = fgetcsv($file);
if ($rows[4] == $_POST['oldPassword'] && $rows[1] == $_SESSION['username']) {
//Replace line here
echo("SUCCESS|Password changed!");
}
}
fclose($file);
}
die("ERROR|Your current password is not correct!");
}
die("ERROR|New passwords do not match!");
}
?>
解决方法:
您必须以读取模式打开文件,在写入模式下打开文件,写入修改后的数据,然后删除/重命名文件.我建议尝试建立一个真正的数据库并使用它,但如果你要使用csv,代码看起来应该或多或少像这样:
$input = fopen('Database/Users.csv', 'r'); //open for reading
$output = fopen('Database/temporary.csv', 'w'); //open for writing
while( false !== ( $data = fgetcsv($input) ) ){ //read each line as an array
//modify data here
if ($data[4] == $_POST['oldPassword'] && $data[1] == $_SESSION['username']) {
//Replace line here
$data[4] = $_POST['newPassword'];
echo("SUCCESS|Password changed!");
}
//write modified data to new file
fputcsv( $output, $data);
}
//close both files
fclose( $input );
fclose( $output );
//clean up
unlink('Database/Users.csv');// Delete obsolete BD
rename('Database/temporary.csv', 'Database/Users.csv'); //Rename temporary to new
希望能帮助到你.
标签:php,csv
来源: https://codeday.me/bug/20190716/1476675.html