Guillermo P
Guillermo P

Reputation: 73

Send $_POST data between php files

I have an HTML form, whose action element refers to the php itself. After clicking the submit button, the php is reloaded and I verify that the input "search" is not empty (if its empty, nothing happens, and if its not, the pag1.php is loaded).

The problem is that if I load the pag1.php file with the header() function, I can´t send it the $_POST data.

Here is my code:

<?php
    if($_SERVER['REQUEST_METHOD'] == 'POST' ){
        $uncomplete;

        foreach($_POST as $val){
            if(empty($val)){
                $uncomplete = true;
                break;
            }
        }

        if(!$uncomplete){
            header("Location: pag1.php");
        }
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <title>Form</title>     
        <meta charset = "UTF-8">
    </head>
    <body>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

            <input type="text" name="search"><br><br>

            <input type="submit" name="submit" value="Send">
   
        </form>
    </body>
</html>

Here is the pag1.php file:

<?php
    echo $_POST['search'];
?>

I've seen similar ways to do it, but I don´t want to load pag1.php on a iframe, I want to load it on my actual window.

Edit: I know that I can change the action element in the form tag to pag1.php, but this is a basic example in case I needed to validate the $_POST array in the same file before sending its data to the pag1.php file.

Upvotes: 0

Views: 68

Answers (1)

ffx14
ffx14

Reputation: 2104

You can include pag1.php and set flag for showing form

<?php
    $showForm = true;
    if($_SERVER['REQUEST_METHOD'] == 'POST' ){
        $uncomplete;
        foreach($_POST as $val){
            if(empty($val)){
                $uncomplete = true;
                break;
            }
        }
        if(!$uncomplete){         
            include("pag1.php");
            $showForm = false;
        }
    }
?>

<?php if($showForm): ?>
<!DOCTYPE html>
<html>
    <head>
        <title>Form</title>     
        <meta charset = "UTF-8">
    </head>
    <body>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

            <input type="text" name="search"><br><br>

            <input type="submit" name="submit" value="Send">
   
        </form>
    </body>
</html>
<?php endif; ?>

Upvotes: 2

Related Questions