Skip to content
Advertisement

Run PHP submit code prior to HTML form action to set SESSION variables

Is there a way when a user submits an HTML form to run the PHP code necessary to save the form data as session variables prior to executing the HTML form’s action and leaving the page? When I set the form action to go to the next page (session2.php) it does so without running the PHP associated with the submit button. If I remove the form action then I need JavaScript in the PHP submit script to bring the user to the next page.

Is there a way to run the PHP and then the run the form action, or is it best to leave as-is? I do have session_start(); as line 1 in both files.

session1.php

<?php

if (isset($_POST['submit'])) {  

    // Set Global Session Variables from Form's POST Values
    $_SESSION["favcolor"] = $_POST['favcolor'];
    $_SESSION["favanimal"] = $_POST['favanimal'];
    
    // Go To Next Page
    $URL="session2.php";
    echo "<script type='text/javascript'>document.location.href='{$URL}';</script>";
    echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">';

}       
?>


<form action="" method="post">
Enter Color: <input type="text" name="favcolor" /><br />
Enter Animal: <input type="text" name="favanimal" /><br />
<input type="submit" value="submit" name="submit" />
</form>

session2.php

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

Advertisement

Answer

There are a few ways you can do this:

  1. Use PHP’s header('Location: /page-url');

  2. Render different content if $_POST is set

<?php

if (isset($_POST['submit'])) {  

    // Set Global Session Variables from Form's POST Values
    $_SESSION["favcolor"] = $_POST['favcolor'];
    $_SESSION["favanimal"] = $_POST['favanimal'];
    
    // Render other page content
    include "session2.php";
    
    // end the script to prevent loading this page contents
    die;
}       
?>


<form action="" method="post">
Enter Color: <input type="text" name="favcolor" /><br />
Enter Animal: <input type="text" name="favanimal" /><br />
<input type="submit" value="submit" name="submit" />
</form>
  1. Submit form via an AJAX request and redirect depending on the response
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement