In web development, forms are a crucial way for users to interact with the server. With PHP, you can easily collect and process form data. This tutorial will show you how to create a simple PHP form and handle the submitted data.
First, you need to create an HTML form to collect user input. Below is a basic example:
<form action="submit.php" method="post"> <label for="name">Name:</label> <input type="text" name="name" id="name"> <br> <label for="email">Email:</label> <input type="email" name="email" id="email"> <br> <input type="submit" value="Submit"> </form>
In this form, the action attribute specifies where the data will be sent after submission, the method attribute defines how the data will be transmitted (POST), and the name and id attributes identify each input field.
Next, create a file named submit.php to receive and process the form submission.
<?php if (isset($_POST['name']) && isset($_POST['email'])) { // Get form inputs $name = $_POST['name']; $email = $_POST['email']; // Save data to a database or file // ... // Return a success message echo "Thank you for your submission!"; } else { // Missing input fields echo "Please fill in all required fields."; } ?>
This PHP script checks whether the form inputs exist using isset() and retrieves the submitted values via the $_POST array. You can then store the data in a database, send an email, or perform other actions as needed.
When building a form, it's important to understand the key HTML attributes:
Once the user fills out and submits the form, the PHP script receives and processes the input. Common steps include:
By following these steps, you can easily build a fully functional PHP form to securely collect and process user input.