Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error reading text file in php

Tags:

I have a file I need to import into a database. (My database is good, I can connect and I can add). Now my problem is for some reason nothing gets inserted.

I have a file schooldatabase.txt of users/password I need to add to a database. The file has 200 lines.

Here's a sample:

test|098f6bcd4621d373cade4e832627b4f6 test2|ad0234829205b9033196ba818f7a872b 

Now for each of these line (student username and password) I have to insert them in a database.

Here's my code:

function addUser($user,$pass) { // this code is good }  function processUser($user,$pass) {   $pass=md5($pass);   $myFile = "schooldatabase.txt";   $fh = fopen($myFile, 'r');   $theData = fread($fh, 5);   $login = "$user|$pass";   if(stristr($theData,$login) !== false){       $result = "rejected";   }   elseif(stristr($theData,$login) !== true){       addUser($user,$pass); // this work I manuall tested       $result = "accepted";    }    fclose($fh);    return $result; } var_dump(processUser('invaliduser','test2')); 

Why it return "accepted" if that user is not in the file?

like image 375
Pat R Ellery Avatar asked Oct 17 '11 01:10

Pat R Ellery


2 Answers

I think here you should re-think about your process. I assume you "processUser" more than one time therefore you will open/read/close the same file over and over without altering that file.

Because the file is not huge (and I assume it's a one-time-script), Just open the file in memory when you start your script then you can compare all the value you are testing with that file.

You can use the function file to do so. Then you can check if the user exists using in_array.

Here's the script:

function addUser($user,$pass) { // this code is good }  $file = file("schooldatabase.txt", FILE_IGNORE_NEW_LINES ^ FILE_SKIP_EMPTY_LINES);  function processUser($user,$pass, array &$file) {   $pass = md5($pass);   if(in_array("$user|$pass", $file)) {     addUser($user,$pass); // do you check if the query is good?     return 'accepted';   }    return "rejected"; }  var_dump(processUser('invaliduser','test2', $file)); 
like image 155
Book Of Zeus Avatar answered Sep 25 '22 07:09

Book Of Zeus


I think you're overcomplicating the if a bit -- it's either true or false, so no need to check that stristr twice! Also, you might have your true/false mixed up.

Edit: Also, it should probably be stripos, which will return the position or false.

Try...

if(stripos($theData,$login) === false){     $result = "rejected"; } else {     addUser($user,$pass); // this work I manuall tested     $result = "accepted"; } 

...does that work?

like image 38
JoLoCo Avatar answered Sep 22 '22 07:09

JoLoCo