开发者

Error reading text file in php

开发者 https://www.devze.com 2023-04-13 05:06 出处:网络
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 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 开发者_JAVA技巧= "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?


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));


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号