php - 使用 file_put_contents 表单的白名单用户
问题描述
<?php
$filename = 'whitelist.txt';
if (isset($_POST['uname'])) {
$uname = $_POST['uname'];
file_put_contents($filename, '{"'.$uname.'"}');
if (empty($uname)) {
header("Location: generator.php?error=No Empty Username");
exit();
}
}else{
header("Location: generator.php");
exit();
}
预期的输出应该是:
{“用户 1”,“用户 2”}
但它是:
{“用户 1”}
我只是想通过使用表单来创建一个白名单用户,这样他就可以被列入白名单,希望有人能提供帮助!谢谢!
解决方案
要创建用户黑名单,您需要使用一些数据库和身份验证,否则在 user1 和 user2 具有相同数据的情况下,您最终会遇到问题
但是对于你的问题。一种方法是每次都替换最后一个字符
是如何...file_put_con...
用这个替换行
$existing = file_get_contents($filename);
if(strpos($existing,"}")){ //check if at least one username exists
$newcontent = str_replace('}',',"'.$uname.'"}',$existing); //replace old data with new
file_put_contents($filename,$newcontent);
} else { // incase there is no username at all
$newcontent = '{"'.$uname.'"}';
file_put_contents($filename,$newcontent);
}
如果您在 uname 中输入 },您显然会损坏数据
所以通过使用实体来防止这种情况或防止 } 字符被接受