read and if not there write, if there dont write and echo

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
fresh
Forum Contributor
Posts: 259
Joined: Mon Jun 14, 2004 10:39 am
Location: Amerika

read and if not there write, if there dont write and echo

Post by fresh »

hey,

Code: Select all

<?php
$names = file("winners/win06.txt");
if(array_search($_SESSION['username'],$names) !== false) {
echo "<script>alert('Cheaters never win.');</script>";
include("http://blah.com/js02.php");
  return;

} else {
$dis = $_SESSION['username'];
$fp = fopen("winners/win06.txt","ab");
fputs($fp, $dis."\n");
fclose($fp);

}

?>
text file writing/listing format:
john
jason
suzi
jack
charles
ok, I'm trying to mark when a user has already completed a mission, my method is to write there name to a file, one per line, and then when the user tries to cheat by redoing the same mission, the script will find their name in the file and tell them they are cheating and will send them back to the beginning... however this above script is not doing that, it just keeps adding my user name, atleast now it forces line breaks, but it just isn't finding my username, I think it's because this script take the entire file and makes it's enitre contents one big var, I need to have it read each line one at a time, to find out if that users name exists in the list... ive been workin on a fix for a day and half now, and am stumped, any help is appreciated thanks :)
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Post by d3ad1ysp0rk »

file() reads the file into an array. Then you can use in_array to check whether they've done it already.

http://php.net/file
http://php.net/in_array
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

[php_man]file[/php_man] keeps linebreaks at the end of lines. Your usernames don't have linebreaks, thus array_search always fails.
add this line before if statement:

Code: Select all

foreach($names as $id => $line) $names[$id] = trim($line);
User avatar
fresh
Forum Contributor
Posts: 259
Joined: Mon Jun 14, 2004 10:39 am
Location: Amerika

hey

Post by fresh »

I added it but havent got to test it yet, thank you in advance :)
Post Reply