Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect unchecked checkbox php

Tags:

php

Is there a way to check of a checkbox is unchecked with php? I know you can do a hidden field type in html but what about with just php when the form is submitted? I tried below no luck.

if(!isset($_POST['server'])||$_POST['server']!="yes"){
        $_POST['server']     == "No";
}
like image 927
acctman Avatar asked Dec 01 '22 23:12

acctman


2 Answers

This is an old question, but for people looking for this....

Better approach to Matt's answer is to use $_SERVER['REQUEST_METHOD'] to check if form was submitted:

if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
    //form was submitted...let's DO this.

    if (!isset($_POST['checkboxname'])) {
        // checkbox was not checked...do something
    } else {
        // checkbox was checked. Rock on!
    }
}
like image 27
Rizwan Avatar answered Dec 04 '22 02:12

Rizwan


If a checkbox is not checked it will not be posted. if(!isset($_POST['checkboxname'])) will do the trick.

Be aware, though, you should at least submit something so that you know the form was submitted in the first place.

if (isset($_POST['formWasSubmitted'])) {
    //form was submitted...let's DO this.

    if (!isset($_POST['checkboxname'])) {
        // checkbox was not checked...do something
    } else {
        // checkbox was checked. Rock on!
    }
}
like image 83
Matt Avatar answered Dec 04 '22 04:12

Matt