[英]Why is strpos() not working when searching this .txt file?
因此,我正在嘗試將電子郵件地址收集和存儲在文本文件中,並且除了無法識別地址是否已提交之外,它還在工作。 即使已經存在,也會在文本文件中添加一個地址。 感謝您的見解。
<?php
function showForm() {
echo '
<form method="post" action="">
Email Address: <input type="email" name="email"> <br />
<input type="submit" value="Submit" name="submit">
</form>
';
}
if(empty($_POST['submit']) === false) {
$email = htmlentities(strip_tags($_POST['email']));
$logname = 'email.txt';
$logcontents = file_get_contents($logname);
$pos = strpos($logcontents, $email);
if ($pos === true) {
die('You are already subscribed.');
} else {
$filecontents = $email.',';
$fileopen = fopen($logname,'a+');
$filewrite = fwrite($fileopen,$filecontents);
$fileclose = fclose($fileopen);
if(!$fileopen or !$filewrite or !$fileclose) {
die('Error occured');
} else {
echo 'Your email has been added.';
}
}
} else {
showForm();
}
?>
strpos()
返回找到字符串的位置,或者返回false
。
檢查$pos === true
永遠不會成功,因為strpos()
的返回值不能為true
。
嘗試if ($pos !== false) { ...
代替。
您的這一行:
$pos = strpos($logcontents, $email);
返回找到的字符串的位置,而不是布爾值。
和
if ($pos === true) {
可能包含0
作為位置。
您應該將其更改為:
if ($pos != false) {
strpos永遠不會返回true。 它可以返回零位,除非您使用嚴格的比較,否則PHP會將其解釋為false。
if ($pos !== false)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.