1

How can I, from a text file, use explode() to take the 1st 2 items (using comma as the delimiter) in each line ?


Username check is working.
The email however isn't.
The countEmail doesn't change.

This is the output I get:
(Tried to add an existing email and the countEmail didn't change)

array(3) {    <--- Previous user
  [0]=>
  string(11) "blabla123"
  [1]=>
  string(28) " [email protected]"
  [2]=>
  string(11) " 123, 1990
"
}
array(1) {
  [0]=>
  string(1) "
"
}

Notice: Undefined offset: 1 in C:\xampp\htdocs\Brets\register.php on line 35

Notice: Undefined offset: 1 in C:\xampp\htdocs\Brets\register.php on line 36
00 (countUser and countEmail)

And this is the code I use:

<form action="register.php" method="POST">
    Username: <br> <input type="text" name="username"> <br>
    Password: <br> <input type="password" name="password"> <br>
    Email: <br> <input type="text" name="email"> <br>
    Year of Birth: <br> <select name="year">
                            <option value="1990">1990</option>
                            <option value="1991">1991</option>
                            <option value="1992">1992</option>
                            <option value="1993">1993</option>
                        </select> <br>
    <input type="submit" value="Submit">
</form>

<?php
$next = 'register.php';
$greet = 'Welcome! <p>Please register using the form above.</p>';

if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']) && isset($_POST['year'])) {
    $username = htmlentities($_POST['username']);
    $password = htmlentities($_POST['password']);
    $email = htmlentities($_POST['email']);
    $year = htmlentities($_POST['year']);

    if (!empty($username) && !empty($password) && !empty($email) && !empty($year)) {
        $countEmail = 0;
        $countUser = 0;
        $filename = 'user.txt';
        $handle = fopen($filename, "a+");
        if ($handle) {
            while (($line = fgets($handle, filesize($filename))) !== false) {
                $line=explode(',', $line, 3);
                echo '<pre>';
                var_dump($line);
                echo '</pre>';
                if (($line[0] == $email) || ($line[1] == $email)) { $countEmail++; }
                if (($line[0] == $username) || ($line[1] == $username)) { $countUser++; }
            }
            if (!feof($handle)) {
                echo "Error: unexpected fgets() fail\n";
            }
        }
        if ($countEmail == 0 && $countUser == 0) {
            fwrite($handle, "$username, $email, $password, $year\r\n");
            fclose($handle);
            $greet = 'Thank you!';
        }
        if ($countEmail != 0) {$greet = 'An account with that email aready exists.';}
        if ($countEmail != 0) {$greet = 'Username already taken.';}
    } else { $greet = 'Fill in all fields.';}
}
echo $greet;

?>

I apologize if I sound confusing.
Also, I know there are probably much better ways of doing this, but I just started learning php :)

7
  • I just noticed that you're storing user names and passwords in a flat file. If you're new to PHP then it would definitely be worth looking into a MySQL database. W3Schools has a pretty useful introduction to it: w3schools.com/php/php_mysql_intro.asp Commented Jul 4, 2012 at 15:48
  • Since I'm new I thought best to start without MySQL. Am i wrong in doing so? Commented Jul 4, 2012 at 17:27
  • Flat files are VERY hard to traverse.. even messier when you need to alter data that already exists in it or insert data in the middle. However they are usually faster. But for this I would suggest MySQL (DONT EVER USE W3SCHOOLS! They are full of false or biased information. php.net is the official site) or maybe a noSQL DB like Mongo or Couch (if you want to stay away from SQL... both of these iirc use JSON to store the data) Commented Jul 4, 2012 at 17:32
  • Also you need to look into not storing your users passwords AS IS IN A FLAT FILE! this is a HUGE security risk. Please Please look at how to hash + salt your passwords in an effective way. Otherwise you're just asking for your users names and passwords to be hacked. Commented Jul 4, 2012 at 17:35
  • Because you're new as a final note: ca3.php.net/manual/en/book.pdo.php This should be your method to facilitate your DB handling. Prepared statements are the way to go! mysql_* functions are not... php.net/manual/en/faq.passwords.php you will likely want to read this entire article. It explains why md5 and sha1 are weak hashes for passwords and you need a real crypt lib. Cheers! Good Luck! Commented Jul 4, 2012 at 17:37

4 Answers 4

2

The php function fgets will read in the file line by line, allowing you to then process and do explodes on a line by line basis.

From the manual:

<?php
$handle = @fopen($filename, "r");
if ($handle) {
    while (($line = fgets($handle, 4096)) !== false) {
        // do something with $line here
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}
?>
Sign up to request clarification or add additional context in comments.

2 Comments

How do I call each line after fgets? $dataIn = fgets($handle, filesize($filename)); foreach($dataIn as $line) like this ?
I've added that into my answer for you. It's worth noting that the PHP manual generally has lots of good examples of how to use each function.
1

Should be as simple as:

list($item1, $item2) = explode(',', $str);

Using fgets() to read line by line.

Btw, if the data is comma separated, you could look at fgetcsv() as well.

Comments

1
$dataLines = explode("\n", $dataIn);

...

foreach ($dataLines as $line) {
  $line=explode(',', $line,3);
  if (siezof($line)<2) continue;
  if (($line[0] == $email) || ($line[0] == $email)) { $countEmail++; }
  if (($line[0] == $username) || ($line[0] == $username)) { $countUser++; }
}

Comments

0

Using a limit in explode will leave the last element containing the rest of string.

http://php.net/manual/en/function.explode.php

So if you want just the first two elements,

e.g. from "a,b,c,d" you want ["a", "b"] use:

$result = explode(",", $array, 3) 
=> ["a", "b", "c,d"]

then pop to remove the last one:

array_pop($result);
print_r($result);
=> ["a", "b"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.