Jump to content

Only add if not found...


Recommended Posts

Good day to you all,

            My code is looking for user name in a file, if match found, do nothing, if no match found, add to list.

 

Right now, it add anyway !

 



$activeadmlist = "user_list.txt";
$pos = strpos($activeadmlist, $_SESSION['username']);

if ($pos === false) {

$output= $_SESSION['username']."\n";
$newfile="user_list.txt";
$file = fopen ($newfile, "a");
fwrite($file, $output);
fclose ($file); 


} else {


} 

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/164438-only-add-if-not-found/
Share on other sites

strpos is treating $activeadmlist as a string, not a file. You never specified that you were opening a file or getting it's contents.

 

So it's checking in "user_list.txt" for the username, that's why it's adding anyway.

 

//grabs contents of the actual file
$file = file_get_contents("user_list.txt");
$user = $_SESSION['username'];

if(!strpos($file, $user)) {
$output= $user."\n";
$newfile="user_list.txt";
$file = fopen ($newfile, "a");
fwrite($file, $output);
fclose ($file);
}
else
{}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.