0

I have a simple issue in my PHP project I made a small application that gives you the possibility to fill the form fields and stored all the data inside a .txt file at the same time the data show up below the form with some specific information such as (first name, last name, city, message).

What is the problem I am facing?

I'm trying to bring the stored data from the .txt file into the bootstrap card like the image below.

The .txt file lock like this:

.txt file

Here is my code:

<!DOCTYPE html>
<!--[if lt IE 7]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en">
    <!--<![endif]-->
    <head>
        <!-- Required meta tags -->
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="description" content="Project Description" />
        <meta name="author" content="Project Author" />
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
        <title>TP2 - Forum de discussion</title>
        <!-- CSS Libraries -->
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/bootstrap.min.css" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" />
        <!-- Google Fonts -->
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&display=swap" />
    </head>
    <body class="bg-light">
        <div class="container col-md-6 my-3">
            <form class="mb-4" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" autocomplete="off">
                <div class="row mb-3">
                    <label for="firstname" class="col-sm-4 col-form-label"><i class="fas fa-user-circle me-1"></i> Nom <sup class="fw-bold text-danger">*</sup></label>
                    <div class="col-sm-8">
                        <input type="text" id="firstname" class="form-control" name="firstname" value="" autofocus />
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="lastname" class="col-sm-4 col-form-label"><i class="fas fa-user me-1"></i> Prenom <sup class="fw-bold text-danger">*</sup></label>
                    <div class="col-sm-8">
                        <input type="text" id="lastname" class="form-control" name="lastname" value=""  />
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="email" class="col-sm-4 col-form-label"><i class="fas fa-at me-1"></i> Email <sup class="fw-bold text-danger">*</sup></label>
                    <div class="col-sm-8">
                        <input type="email" id="email" class="form-control" name="email" value=""  />
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="city" class="col-sm-4 col-form-label"><i class="fas fa-building me-1"></i> Ville <sup class="fw-bold text-danger">*</sup></label>
                    <div class="col-sm-8">
                        <input type="text" id="city" class="form-control" name="city" value=""  />
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="country" class="col-sm-4 col-form-label"><i class="fas fa-flag me-1"></i> Pays <sup class="fw-bold text-danger">*</sup></label>
                    <div class="col-sm-8">
                        <input type="text" id="country" class="form-control" name="country" value=""  />
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="message" class="col-sm-4 col-form-label"><i class="fas fa-envelope me-1"></i> Message <sup class="fw-bold text-danger">*</sup></label>
                    <div class="col-sm-8">
                        <textarea id="message" class="form-control" name="message" rows="3" ></textarea>
                    </div>
                </div>
                <div class="row mb-3">
                    <label for="file" class="col-sm-4 col-form-label"><i class="fas fa-file me-1"></i> joindre un fichier</label>
                    <div class="col-sm-8">
                        <input type="file" id="file" class="form-control" name="file"  />
                    </div>
                </div>
                <hr />
                <div class="d-grid gap-2">
                    <button type="submit" class="btn btn-lg btn-primary" name="submit">Envoyer <i class="fas fa-arrow-alt-circle-right ms-1"></i></button>
                </div>
            </form>
            
<?php
$filename = "data_form.txt";
$time = date("Y-d-m H:m:s");

if (isset($_POST["submit"])) {
    $firstname = "First Name: " . $_POST["firstname"] . "\r\n";
    $lastname = "Last Name: " . $_POST["lastname"] . "\r\n";
    $email = "Email: " . $_POST["email"] . "\r\n";
    $city = "City: " . $_POST["city"] . "\r\n";
    $country = "Country: " . $_POST["city"] . "\r\n";
    $message = "Message: " . $_POST["message"] . "\r\n";
    $file = "Uploaded File: " . $_POST["file"] . "\r\n";
    $fp = fopen($filename, "a");
    fwrite($fp, $firstname . $lastname . $email . $city . $country . $message . $file . "\n");
    fclose($fp);
}

$fp2 = fopen($filename, "r");
while (!feof($fp2)) {
    $content = fgets($fp2);
    // echo $content . "<br>";
    echo "
            <ul class='list-group'>
                <li class='row row-cols-1 row-cols-md-2 p-4 bg-white shadow'>
                    <div class='col mb-lg-0 mb-md-4'>
                        <ul class='list-group list-group-flush'>
                            <li class='list-group-item bg-transparent px-0'><i class='fas fa-user-circle me-1'></i> <strong>Nom &amp; Prénom:</strong> <span class='text-primary'>Oliver Queen</span></li>
                            <li class='list-group-item bg-transparent px-0'>
                                <i class='fas fa-envelope me-1'></i>
                                <strong>Message:</strong>
                                <span><i class='fas fa-clock'></i> (25/04/2022 19:40)</span>
                                <br />
                                <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
                            </li>
                        </ul>
                    </div>
                    <div class='col'>
                        <ul class='list-group list-group-flush'>
                            <li class='list-group-item bg-transparent px-0'><i class='fas fa-building me-1'></i> <strong>Ville:</strong> <span class='text-primary'>new york / usa</span></li>
                        </ul>
                    </div>
                </li>
            </ul>
            
            ";
    echo "<br>";
}
fclose($fp2);
?>  
            
        </div>
        <!-- JS Libraries -->
        <script src="js/bootstrap.bundle.min.js"></script>
    </body>
</html>

Expected results

Expected results

maxwiber
  • 13
  • 2
  • So where exactly are you stuck? I don't see any actual attempt to parse the contents of the file or output it. P.S. Your life would be a lot easier if you store the data in a recognised format such as JSON, for which easy encoding and decoding functions exist in PHP. Then you wouldn't have to work out how to extract the data from the abitrary format in which you've stored it currently. – ADyson May 06 '22 at 12:21
  • How I can bring the data separately from .txt file example : `

    First Name is : $firstname

    `
    – maxwiber May 06 '22 at 12:43
  • I just explained a way - store the data in a recognised format such as JSON. That way you can then easily decode it and get the property you want from it. – ADyson May 06 '22 at 13:11
  • [How to extract and access data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-to-extract-and-access-data-from-json-with-php) – ADyson May 06 '22 at 13:12
  • I'm not locking for JSON read my question – maxwiber May 06 '22 at 13:21
  • I know. But it will save you a lot of effort if you use JSON instead of inventing your own data format. – ADyson May 06 '22 at 13:22

1 Answers1

0

It seems you're stuck on how to parse the data you've stored in your text file and retrieve specific pieces of information such as the first name.

To solve this easily we need to take a step back. Instead of the arbitrary format which you've stored the data in, I would recommend using a recognised format such as JSON, for which PHP has ready-made encoding and decoding functions. This will make your life a lot easier and save a whole step of programming work writing your own parser.

For example:

Firstly, saving the data:

if (isset($_POST["submit"])) {
    $data = array(
      "firstname" => $_POST["firstname"],
      "lastname" => $_POST["lastname"],
      "email" => $_POST["email"],
      "city" => $_POST["city"],
      "country" => $_POST["country"],
      "message" => $_POST["message"]
    );
    
    //now append to the existing JSON, if any
    $existingJSON = file_get_contents($filename);
    $list = array();
    
    if ($existingJSON !== false) $list = json_decode(existingJSON, true);
    $list[] = $data; //append to the list
    $json = json_encode($list);
    file_put_contents($filename, $json);
}

And then, retrieving it:

$fileJSON = file_get_contents($filename);
$fileList = json_decode($fileJSON, true); //The "true" tells it to decode into an associative array

foreach ($fileList as $item)
{
  echo "
            <ul class='list-group'>
                <li class='row row-cols-1 row-cols-md-2 p-4 bg-white shadow'>
                    <div class='col mb-lg-0 mb-md-4'>
                        <ul class='list-group list-group-flush'>
                            <li class='list-group-item bg-transparent px-0'><i class='fas fa-user-circle me-1'></i> <strong>Nom &amp; Prénom:</strong> <span class='text-primary'>".$item["firstname"]." ".$item["lastname"]."</span></li>
                            <li class='list-group-item bg-transparent px-0'>
                                <i class='fas fa-envelope me-1'></i>
                                <strong>Message:</strong>
                                <span><i class='fas fa-clock'></i> (25/04/2022 19:40)</span>
                                <br />
                                <p>".$item["message"]."</p>
                            </li>
                        </ul>
                    </div>
                    <div class='col'>
                        <ul class='list-group list-group-flush'>
                            <li class='list-group-item bg-transparent px-0'><i class='fas fa-building me-1'></i> <strong>Ville:</strong> <span class='text-primary'>".$item["city"]." ".$item["country"]."</span></li>
                        </ul>
                    </div>
                </li>
            </ul>
            ";
}

N.B. If you're going to work with multiple records, in the longer term it will be a lot simpler and more efficient to use a small database (e.g. MySQL or SQLite).

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • one question how I can display all stored data one by one ? – maxwiber May 06 '22 at 13:33
  • You mean show each different field about a person? – ADyson May 06 '22 at 13:34
  • Or you mean show data about lots of different people? – ADyson May 06 '22 at 13:34
  • I don't want to remove first stored data after filling the form again – maxwiber May 06 '22 at 13:34
  • show data about lots of different people – maxwiber May 06 '22 at 13:34
  • show data about lots of different people with the time of storage – maxwiber May 06 '22 at 13:36
  • Ok. Read the N.B. section of my answer - I've explained the limitations of this example, it's just to show you how the JSON storage works in general. To store many different records in a text file (in any format) becomes inefficient (because you have to recreate the whole file each time, and it's slow to search for things etc), so at that point it's sensible to use a database instead of a file. – ADyson May 06 '22 at 13:36
  • I can show you what to do with the file, if you want, but it's not a good design really – ADyson May 06 '22 at 13:37
  • my professor need to use .txt file as database store many records by using the form after that displaying all data belowe the form. – maxwiber May 06 '22 at 13:37
  • Why did your professor give you this task? It's a silly task, no-one would store multiple records in this way in real life, you would always use a database. I don't know why they think you would learn anything very useful from this. But ok I will show you a way. – ADyson May 06 '22 at 13:38
  • yes I need help – maxwiber May 06 '22 at 13:38
  • I know but he is opinion to use .txt file – maxwiber May 06 '22 at 13:39
  • ok I made an updated version which should help you. Basically you just have to append the new data to the existing data (if there is any) each time you save it. And then to display it, you need to loop through the list. Nothing complicated. – ADyson May 06 '22 at 13:43
  • one simple question how I can get the exact time of stored data – maxwiber May 06 '22 at 14:12
  • You mean you want to save an extra property into each record saying when it was stored? Well, first google how to get the current time with PHP, and then you can hopefully see how to set an extra property to the $data array before you save it. – ADyson May 06 '22 at 14:26