searching a text file

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
sulen
Forum Commoner
Posts: 79
Joined: Wed Jul 09, 2003 4:55 pm
Location: los angeles
Contact:

searching a text file

Post by sulen »

Hi ,
I need to search a text file .htpasswd for the existence of user names entered by users on a form so that I can prompt them that their username already exists.

The script needs to search this file and return true if the user name.

Please help.
User avatar
JAM
DevNet Resident
Posts: 2101
Joined: Fri Aug 08, 2003 6:53 pm
Location: Sweden
Contact:

Post by JAM »

Use file() to read the file into an array, then you can compare each row's content agains the given username.

Code: Select all

function userexists($formuser) {
  // read the file into array
 $data = file('.htpasswd');
  // loop...
  for ($i=0;$i<count($data);$i++) {
    // break it up in pieces (interesting uses)
    list($user,$pass,$uid,$gid,$gecos,$home,$shell) = explode(":",$data[$i]);
    // note === for exakt match...
    if ($user === $formuser) { return 1; }
  }
  return 0;
}
// Usage:
if (userexists('name')) { echo 'Allready in the file'; }
else { echo 'Not filed...'; }
It might need some modification (for example $_POST and such) but I'm tired and need coffee...
Post Reply