如何从文本文件中使用 explode() 在每行中获取第 2 项(使用逗号作为分隔符)?
用户名检查正在工作。
然而,电子邮件不是。
countEmail 没有改变。
这是我得到的输出:(
试图添加一个现有的电子邮件并且 countEmail 没有改变)
array(3) { <--- Previous user
[0]=>
string(11) "blabla123"
[1]=>
string(28) " blahblah@blah.com"
[2]=>
string(11) " 123, 1990
"
}
array(1) {
[0]=>
string(1) "
"
}
Notice: Undefined offset: 1 in C:\xampp\htdocs\Brets\register.php on line 35
Notice: Undefined offset: 1 in C:\xampp\htdocs\Brets\register.php on line 36
00 (countUser and countEmail)
这是我使用的代码:
<form action="register.php" method="POST">
Username: <br> <input type="text" name="username"> <br>
Password: <br> <input type="password" name="password"> <br>
Email: <br> <input type="text" name="email"> <br>
Year of Birth: <br> <select name="year">
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
</select> <br>
<input type="submit" value="Submit">
</form>
<?php
$next = 'register.php';
$greet = 'Welcome! <p>Please register using the form above.</p>';
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']) && isset($_POST['year'])) {
$username = htmlentities($_POST['username']);
$password = htmlentities($_POST['password']);
$email = htmlentities($_POST['email']);
$year = htmlentities($_POST['year']);
if (!empty($username) && !empty($password) && !empty($email) && !empty($year)) {
$countEmail = 0;
$countUser = 0;
$filename = 'user.txt';
$handle = fopen($filename, "a+");
if ($handle) {
while (($line = fgets($handle, filesize($filename))) !== false) {
$line=explode(',', $line, 3);
echo '<pre>';
var_dump($line);
echo '</pre>';
if (($line[0] == $email) || ($line[1] == $email)) { $countEmail++; }
if (($line[0] == $username) || ($line[1] == $username)) { $countUser++; }
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
}
if ($countEmail == 0 && $countUser == 0) {
fwrite($handle, "$username, $email, $password, $year\r\n");
fclose($handle);
$greet = 'Thank you!';
}
if ($countEmail != 0) {$greet = 'An account with that email aready exists.';}
if ($countEmail != 0) {$greet = 'Username already taken.';}
} else { $greet = 'Fill in all fields.';}
}
echo $greet;
?>
如果我听起来令人困惑,我深表歉意。
另外,我知道可能有更好的方法可以做到这一点,但我刚刚开始学习 php :)