Вопрос

I am building a basic registration and login system for an online store.

I am a complete php newbie and am struggling to get my head around the reading side of php. My registraion validates fine and is writing to the correct file. Each user is required to register with a unique email address but I am unsure how to do this check.

<?php
// form filled out correctly
// assign all POSTed variables
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$address = $_POST['address'];
$email = $_POST['email'];
$sex = $_POST ['sex'];
$age = $_POST ['age'];
$pwd = $_POST ['pwd'];

// form validation such as all fields are filed in and email correct format

$fp = fopen("user.txt", "r");
//Output a line of the file until the end is reached

//combine string for output
$output_string = "Firstname: " .$fname ."\t"
."Lastname: " .$lname ."\t"
."Address: " .$address ."\t"
."Email: " .$email ."\t"
."Sex: " .$sex ."\t"
."Age: " .$age ."\t"
."Password: " .$pwd ."\n";

//write user to user.txt
$fp = fopen ("user.txt", "a");
fwrite ($fp, $output_string);
fclose($fp); 
echo "<p> Your registration was successful! </p>";
echo "<h3> <a href=\"login.php\"> Login here </h3>";
?>
Это было полезно?

Решение

If I were you I wouldn't store data in txt. I would use database or XML file.

Example of xml structure:

<?xml version="1.0" encoding="UTF-8" ?>
<users>
   <user>
     <firstname>John</firstname>
     <lastname>Doe</lastname>
     <adress>aaa 23 street</adress>
     <email>aaa@gmail.com</email>
     <sex>male</sex>
     <age>1987</age> <!-- better to use year of birth -->
     <password>dkfzlkxcvzxkcv</age> <!-- password's hash -->
    </user>
</users>

With such structure of file you can use simple xml

function findEmail()
{

 if (file_exists('users.xml'))
 {
   $xml = simplexml_load_file('test.xml');
   foreach ($xml->users->user as $user)
   { 
      if($user->email == $_POST['email']) return true;
   }  
 }
 return false;
}

Read more about Simple XML -> http://www.php.net/manual/en/book.simplexml.php Using XML has a lot of advantages you should consider it in your project. However, if you don't want to use it. To read file to array where element of array is a line you should use function file()

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top