How to test if a form is submitted in PHP?

We live in a very busy world, and sometimes we try to get things done quick-and-dirty. One of the most popular examples is to create a PHP script that renders a view and also handles form submission (action). So, what is the best way to test if a form has been submitted?

For example, let's look at the HTML form snippet below:

<form name="example" action="example.php" method="post">
   <input type="text" name="name" />
   <input type="submit" name="submit" value="Submit">
</form>

Most PHP programmers tend to use the isset() method to test a form submission. You may use isset($_POST['submit']), which works perfectly fine but what happens if you use the image button to submit a form? For example,

<form name="example" action="example.php" method="post">
   <input type="text" name="name" />
   <input type="image" name="submit" src="submit.png" id="submit" value="submit" />
</form>

If you use isset($_POST['btnSubmit']) to test form submission, the test will FAIL in the above example. The best way to test form submission is to use the REQUEST method.

if ($_SERVER['REQUEST_METHOD'] == "POST") 

Conclusion

In PHP, you can test if a form is submitted by checking if the relevant form data is present in the request. Typically, this involves checking the $_POST or $_GET superglobal arrays, depending on the form's submission method (POST or GET).

Additionally, you might want to include CSRF (Cross-Site Request Forgery) protection in your form handling to enhance security. This involves generating and validating CSRF tokens to prevent unauthorized form submissions.

Keep in mind that relying solely on client-side validation is not secure, so always perform server-side validation and sanitation of the submitted data for security purposes.

Share this post

Comments (0)

    No comment

Leave a comment

All comments are moderated. Spammy and bot submitted comments are deleted. Please submit the comments that are helpful to others, and we'll approve your comments. A comment that includes outbound link will only be approved if the content is relevant to the topic, and has some value to our readers.


Login To Post Comment