In this series you'll learn all about forms, form submissions, how this translates in the HTTP Request/Response world, and saving files to the disk. This is a huge step forward, and all in under 30 minutes!
In this second part of PHP for Beginners, you'll learn all about forms, form submissions, how this translates in the HTTP Request/Response world, and saving files to the disk. This series continues from PHP for Beginners Part 1, and we'll be expanding on that same project in this series.
In this tutorial we'll get things set up and ready to go by setting up our sample code, doing a quick review of the HTTP request, and creating a new page for the site with some navigation.
In this tutorial we're going to leave PHP alone for a second and put together some good old HTML to create a form with name, breed, weight, and bio text fields. Once we create our form, we'll explain how forms get submitted over HTTP, and the difference between POST and GET requests.
In this tutorial we will work with the PHP
$_POST variable, along with the
$_SERVER variable to capture the information from our form. We'll need to make sure our code is specifically looking for POST data, instead of GET, by using some logic.
We can now read the POST data from our form, but we can't really do much with it long term. We aren't saving the information anywhere. In this tutorial you are going to learn how to update our pets.json file with new information every time the form gets submitted. Since this is an important file for us to be able to use and read, we'll also quickly look at how to keep the human-readable formatting in place as we make our updates.
As you use your form, you'll notice that after you submit the form, you just keep seeing the form again. If you keep submitting it, you'll end up with a bunch of duplicate records. That's no good. In this tutorial you will implement a redirect on the form submission to take the submitter to the home page, instead of back to the form, using the
header() function. We'll explain what exactly a header is and how that relates to our HTTP requests.
Our form is working well now, and to finish up, in this tutorial we're going to clean up and reorganize our code a little bit by moving things into a new custom function, called
save_pets(). This won't change how the form works, but moving logic into functions gives us two advantages, re-usable code, and making it clearer what the code we've written does, and is intended for.