Mithu Mithu - 3 years ago 172
PHP Question

How to update and get session value in WordPress?

I am trying to update a dropdown box and two text box value in session and then get those session value in next page. For this I have written following code in my first page

<form action="/thanks" method="POST">

<select name="select_amount" id="select_amount" onchange="submit();">
<option>-----</option>
<option value="10">1st option</option>
<option value="15">2nd option</option>
<option value="20">3rd option</option>
<option value="25">4th option</option>
</select>

<input type="text" name="programname" /><br>
<input type="text" name="email" /><br>
<input type="submit" name="submit" class="button_add">

</form>

<?php
session_start();
if(isset($_POST['submit'])) {
$_SESSION['pro']=$_POST['programname'];
$_SESSION['e']=$_POST['email'];
$_SESSION['amount']=$_POST['select_amount'];
}?>


and in
thanks.php
file I am trying to get session value by following code

<?php
session_start();
if (isset($_SESSION['amount'])) {
echo $_SESSION['amount'];
}?>


I have also added following code in my theme
function
file but its not working.

if(!session_id()) {
session_start();
}

Answer Source

session_start() is called after output is send to the browser which should result in an error being thrown. session_start() should be the first thing in your PHP file (after the starting tag).

You are trying to set the session variables on the same page the form is on. PHP code is not executed in the browser but on the server, the $_POST variable is thus only available once you submit the form.

What you probably meant to do is the following:

<?php
      session_start(); // start session before output
?>
<form action="/thanks" method="POST">

<select name="select_amount" id="select_amount" onchange="submit();">
   <option>-----</option>
   <option value="10">1st option</option>
   <option value="15">2nd option</option>
   <option value="20">3rd option</option>
   <option value="25">4th option</option>
</select>

<input type="text" name="programname" /><br>
<input type="text" name="email" /><br>
<input type="submit" name="submit" class="button_add">

</form>

thanks.php

<?php
    session_start();

    // form is posted to this page
    if(isset($_POST['submit'])) {

        // form is posted to this page
        $_SESSION['amount'] = $_POST['select_amount'];
        $_SESSION['programname'] = $_POST['programname'];
        $_SESSION['email'] = $_POST['email'];

        echo $_SESSION['amount'];
    }
}?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download