Albert Tung
Albert Tung

Reputation: 55

How to save a HTML variable in a PHP page

I understand there's "POST" and "GET" to obtain data from a HTML page. Is there a way to obtain the variable from the HTML page, save it on the PHP page as another variable so the variable will still be there even though the PHP page is being refreshed.

Right now I can present the variable on the PHP page, but after I refresh the page it doesn't save it or if I open a separate tab using the same URL, the variable isn't there.

Thanks.

Upvotes: 0

Views: 376

Answers (1)

Yolo
Yolo

Reputation: 1579

You can store HTML form variables to PHP session variables. Here is a super basic example:

<?php
session_start(); // this needs to be called anytime your working with sessions (even before destoying them)

if(isset($_POST['your_form_variable'])) {
    $_SESSION['your_session_variable'] = $_POST['your_form_variable'];
}

// $_SESSION['your_session_variable'] will now persist through every page load 
// until you destroy it by using:
//
// unset($_SESSION['your_session_variable']);
// 
// and to destroy them all:
//
// session_start();
// session_destroy();
// $_SESSION = array();

if(isset($_SESSION['your_session_variable'])) {
    echo $_SESSION['your_session_variable'];
}
?>
<form method="post">
  <input name="your_form_variable" value="Some value" />
  <button>Sumbit form</button>
</form>

Upvotes: 1

Related Questions