0

I try to determine if a checkbox is checked or not, but i get an error.

test.php

<html>
    <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

            Use Proxy : <input type="checkbox" name="use_proxy"><br><br>

            <input type="submit">
        </form>

        <?php 
            $use_proxy  = $_POST['use_proxy'];

            if ($use_proxy != "on")
            {
                $use_proxy = "off";
            }

            echo "<p> use_proxy = " . $use_proxy . "</p><br>"; 
        ?>
    </body>
</html>

I get this error: Notice: Undefined index: use_proxy in C:\xampp\htdocs\mbcl\checkbox_test.php on line 11 How can i solve it?

1
  • your code seems correct. Commented Sep 21, 2015 at 11:11

1 Answer 1

3

This is the behaviour of checkbox until they are checked , they can not be fetched at backend(PHP) . You can try as below-

<html>
    <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

            Use Proxy : <input type="checkbox" name="use_proxy" value="off"><br><br>

            <input type="submit">
        </form>

        <?php 
            $use_proxy  = isset($_POST['use_proxy'])?"on":"off";
            echo "<p> use_proxy = " . $use_proxy . "</p><br>"; 
        ?>
    </body>
</html>
Sign up to request clarification or add additional context in comments.

6 Comments

Obviously because you weren't using ISSET
@CodeGodie And why is it necessary to use isset? The logik looks totaly ok.
Because ISSET will check if POST actually exists. Initially before you submit your form, There are no POST requests, thus giving you those errors
@EdwardBlack ,one more thing , what you are getting that is not "error" , they are "warning" in real . You would be overcome this by using "error_reporting(0) " too.
You should not turn off error reporting. These warning/errors will help you make better code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.