Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP if ($_POST) annoyance

Tags:

post

php

I find myself working through a lot of other peoples' code nowadays. I noticed if (isset($_POST)) in some of the code and made sure to fix that. (It will always evaluate true). Then I start seeing this:

if ($_POST)

After thinking through this, it annoys me, but still seems to work. Does anyone see any issues with using this to check if a form has been submitted? If the $_POST array is empty, then it evaluates as false. Any special cases where this might not work?

like image 731
teynon Avatar asked Mar 04 '26 13:03

teynon


1 Answers

It's an unreliable test - it assumes that at least one form element will be submitted. It's entirely possible to perform a POST where no data is submitted, which would make if ($_POST) evaluate to false, but be meta-false as a POST was actually performed.

The proper 100% reliable test is

if ($_SERVER['REQUEST_METHOD'] == 'POST') { ... }
like image 86
Marc B Avatar answered Mar 06 '26 04:03

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!