Search code examples
phpget

Processing Form Data using GET Request in PHP


I'm new to php and I am writing code to get form data using get method. Following is my code in index.php file.

<!DOCTYPE html>
<html>
<body>
    <form method="GET" action="index.php">
        <p>Enter Name</p>
        <input type="text" name="fname" />
        <input type="submit" />
    </form>
    <?php
    if($_SERVER['REQUEST_METHOD'] === 'GET')
    {
        $name = $_GET['fname'];
        print $name;
    }
    ?>
</body>
</html>

when I run my code, it calls the php code before submitting form. How can I process the data using GET Method without creating a new php file.


Solution

  • it calls the php code before submitting form

    Because when you load a page, that's a GET request. And the code explicitly states to execute on a GET request.

    How can I process the data using GET Method without creating a new php file

    You'd need to determine the difference between when the page is loaded and when the form is submitted. If the form must use GET then the request method isn't that difference. One option could be to check for the existance of a submitted value. For example:

    if (isset($_GET['fname'])) {
        // your code
    }
    

    A common approach would be to use the name of the submit button being clicked as well, which can also be used to distinguish between different buttons in the same form. But any submitted value will do.