When you use the include function and click submit, it goes to the included file (PHP)

Based on my observations, it appears that when you use the include function to try to use content from another file and then press the submit button, that file is displayed. Here’s an example:

I have a file called File1, whose contents are below…

<?php

$submitClicked = false;

if(isset($_POST['submit']))
{
    $submitClicked = true;
}

And now I want to use another file to make output appear on the screen if I click the submit button. I do this with a main file that has html in it:

<!Doctype html>
<title>
    Practice
</title>

<body>
    <form action = "File1.php" method = "POST">

        <?php
            include_once 'File1.php';
            if($submitClicked)
            {
                echo "<h1> <em>Submit Clicked!</em>";
            }

            else
            {
                echo "Nope";
            }
        ?>

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

Now, when I click the submit button the page literally goes blank. I notice that it’s going to the file in the include function. Why does it do that and how do I get it to do what I intend for it to (which is to display Submit Clicked) when the submit button is clicked? I’m using the WAMP server, by the way.

Just remove the file name “File1.php” from form’s action attribute. It should look like action = “”.

That worked, thanks.

I am confused, however. Don’t I need “File1.php” in the action attribute if I want to handle information in another that file? Isn’t that what action is for in a form?

You’re welcome!

Yes, that’s what action attribute is for. The thing is whenever submit button is clicked, the page you’re on is redirected to the one in action’s attribute.

The File1.php in your case is being included to the current page. The purpose of include function is to display the code present in another file. The included files are not complete and therefore should not be used as links or actions.

If you want to handle information in File1.php, you can do the following changes:

File1.php:

<?php

$submitClicked = false;

if(isset($_POST['submit']))
{
    $submitClicked = true;
}

if($submitClicked)
{
	echo "<h1> <em>Submit Clicked!</em>";
}

else
{
	echo "Nope";
}
?>

Main File:

<!Doctype html>
<title>
    Practice
</title>

<body>
    <form action = "File1.php" method = "POST">
    <input type = "submit" name = "submit">
    </form>
</body>

Thanks for the information

I’m glad I could help! :slightly_smiling_face: