/

How to Use Forms in PHP: A Step-by-Step Guide

How to Use Forms in PHP: A Step-by-Step Guide

Forms play a crucial role in allowing users to interact with web pages and send data to servers. In this tutorial, we will walk you through the process of using forms in PHP.

First, let’s start with a simple HTML form:

1
2
3
4
<form>
<input type="text" name="name" />
<input type="submit" />
</form>

To integrate this form into your PHP application, you can place it in your index.php file as if it were an HTML file. Keep in mind that PHP files allow for HTML code with PHP snippets enclosed within <?php ?> tags.

Next, let’s take a look at how this form works using a basic example:

PHP Form

When the user clicks the Submit button, the form triggers a GET request to the same URL and sends the data through the query string. You can notice the URL changing to something like: http://localhost:8888/?name=test.

To check if the submitted parameter is set, we can use the isset() function. Here’s an example:

1
2
3
4
5
6
7
8
9
10
<form>
<input type="text" name="name" />
<input type="submit" />
</form>

<?php
if (isset($_GET['name'])) {
echo '<p>The name is ' . $_GET['name'];
}
?>

Here’s how it looks:

GET Request Example

As you can see, we can retrieve the information from the GET request query string using the $_GET variable.

Typically, forms are used to perform POST requests. To demonstrate this, we need to modify the form to use the POST method:

1
2
3
4
5
6
7
8
9
10
<form method="POST">
<input type="text" name="name" />
<input type="submit" />
</form>

<?php
if (isset($_POST['name'])) {
echo '<p>The name is ' . $_POST['name'];
}
?>

Now, we are performing a POST request. The form data is sent to the server without appending it to the URL. Here’s how it looks:

POST Request Example

With the POST request, PHP still serves the index.php file, but the form data is sent differently - through URL-encoded data.

To organize the code better, we can separate the form request handler from the form generation code. Here’s how it can be done:

In index.php:

1
2
3
4
<form method="POST" action="/post.php">
<input type="text" name="name" />
<input type="submit" />
</form>

In post.php:

1
2
3
4
5
<?php
if (isset($_POST['name'])) {
echo '<p>The name is ' . $_POST['name'];
}
?>

By setting the action attribute in the form, we specify that the form data should be submitted to the post.php file. You can perform various actions with the received data in the separate file, such as saving it to a database or a file.

Congratulations! You now have a better understanding of how to use forms in PHP. Feel free to explore more advanced form handling techniques and unleash the power of PHP in your web applications!

tags: [“PHP”, “forms”, “web development”, “GET request”, “POST request”]