Storing form data in a json file with php
Updated: 15-Jan-2022 / Tags: PHP and JSON / Views: 3861 - Author: George
Introduction
Hello everyone,
in this post we are going to see how PHP and JSON are
working together. We are going to take the data from a contact form, and we will encode them and store them in a JSON file.
Lets start
We need three files for our little app.
- We are going to create an index.php file where we are going to write our html,
- an script.php file, for our php code,
- and a messages.json file, where we are going to store the messages.
The HTML code
index.php ... In the first line we are going to include the script.php file that we are gonna create in the next chapter. We are going to use the require() function for that.
<?php require("script.php") ?>
<!DOCTYPE html>
Inside the body tags we are going to have our contact form. The form has two input fields and a textarea. In the first input field we ask for the users email. In the second field we ask for a subject, and in the textarea for the message.
<body>
<form action="" method="post">
<h3>Contact us</h3>
<label>Enter your email</label>
<input type="email" name="email" value="">
<label>Enter a subject</label>
<input type="text" name="subject" value="">
<label>Enter your message</label>
<textarea name="message"> </textarea>
<input type="submit" name="submit" value="Send message">
<p class="error"><?php echo @$error; ?></p>
<p class="success"><?php echo @$success; ?></p>
</form>
Lets break down the form element.
<form action="" method="post">
- The action="" attribute is left empty, that means that the form will be submitted in the same page.
- The method="post" attribute is set to post. The form will send the data to the server with the HTTP POST REQUEST. That means that the data are hidden from the user and safer during the transfer.
<input type="email" name="email" value="">
- In line 14 we have the email input field with the name attribute set to "email".
<input type="text" name="subject" value="">
- In line 17 we have the subject input field with the name attribute set to "subject".
<textarea name="message"> </textarea>
- In line 20 we have the message textarea with the name attribute set to "message". We are gonna need those name attributes in our php file to grab the values.
<input type="submit" name="submit" value="Send message">
- In line 22 we have the submit button, we will use the name attribute to check for the post request in the php file.
<p class="error"><?php echo @$error; ?></p>
<p class="success"><?php echo @$success; ?></p>
- In line 24 we have an error placeholder where will output any error from the php file trough the $error variable. The same thing applies to the success placeholder in line 25.
- The @ sign in front of the variables tells the server not to throw a warning if the variables are not declared (created).
The php code
Now this is the code we are going to write in our script.php file.
if(isset($_POST['submit'])){
$new_message = array(
"email" => $_POST['email'],
"subject" => $_POST['subject'],
"message" => $_POST['message']
);
if(filesize("messages.json") == 0){
$first_record = array($new_message);
$data_to_save = $first_record;
}else{
$old_records = json_decode(file_get_contents("messages.json"));
array_push($old_records, $new_message);
$data_to_save = $old_records;
}
$encoded_data = json_encode($data_to_save, JSON_PRETTY_PRINT);
if(!file_put_contents("messages.json", $encoded_data, LOCK_EX)){
$error = "Error storing message, please try again";
}else{
$success = "Message is stored successfully";
}
}
Lets break down the php code.
First of all we have to check if the user has pressed the submit button. The ['submit'] array key is the submit buttons name="submit" attribute value.
if(isset($_POST['submit'])){
Next in line 3, and if there is a post request we are creating an array and give it a name of $new_message and assigning to variables the incoming email, subject, and message.
$new_message = array(
"email" => $_POST['email'],
"subject" => $_POST['subject'],
"message" => $_POST['message']
);
In the next code block from line 9 - 16 we have an if statement and we are checking if the messages.json file is empty or has stored messages in it.
if(filesize("messages.json") == 0){
$first_record = array($new_message);
$data_to_save = $first_record;
}else{
$old_records = json_decode(file_get_contents("messages.json"));
array_push($old_records, $new_message);
$data_to_save = $old_records;
}
- With the condition filesize("messages.json") == 0, we are checking the size of the messages.json file. If the condition is true the file is empty. == 0 means zero bytes.
-
In line 10 we know that the file is empty so we have to create an array to store our $new_message. It is important to store the first message
in an array, because we need an array to store multiple messages, and we assign the array ta a variable called $first_record.
Next in line 11 i 'll assign the record to a generic variable for later use. - In line 12 we have the else clause. That means, if the file contains records, then in line 13 we get all the records and store then in the $old_records variable. You see that we have to decode the data in order to use them json_decode(file_get_contents("messages.json")).
- Next in line 14 we add the $new_message to the $old_records which is an array. Remember that we creating with the first message an array to hold all messages. Line 10.
- And in line 15 we assign the data to the generic variable.
$encoded_data = json_encode($data_to_save, JSON_PRETTY_PRINT);
- In line 18 we use the json_encode function to encode the the data so we can store them back to the file. The JSON_PRETTY_PRINT flag will structure the data in the file and make them more readable.
if(!file_put_contents("messages.json", $encoded_data, LOCK_EX)){
$error = "Error storing message, please try again";
}else{
$success = "Message is stored successfully";
}
} // end of script.
-
In the last code block we write the data back to the file using the
file_put_contents() function wrapped in an if statement to check
if the function is successful. If something went wrong we store an error message in the $error variable. And if everything went ok, we store a
success message in the $success variable.
Remember we have the $error and $success variables in the html form inside placeholders. -
file_put_contents() ... writes the data to a file, takes as the first argument the filepath, and the second argument is the data we want to write.
The LOCK_EX flag is for security reasons. The file can not be opened by another application until the writing process is done.
Summary
And that's it. That is how we can store form data in a JSON file.
I hope you like it, and thanks for reading.
Source code
You can download the source code and use it in any way you like.
Times downloaded: 549
Comment section
You can leave a comment, it will help me a lot.
Or you can just say hi. 😉