how to store variable values over multiple page loads

I’m making a php script that stores 3 arrays: $images, $urls, $titles based on the input data of the form within the php file.

I want to print the values of these arrays in the first part of the page and then to pre-fill the form’s input fields with the value of the arrays. Also when a user modifies an input field and clicks on “Save” the page should reload with the modfied version.

My problem is that on each call of the php file in a browser the value of the variables gets deleted. Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?

<?php
//save the arrays with the form data
$images = array($_POST["i0"],$_POST["i1"],$_POST["i2"],$_POST["i3"]);
$urls = array($_POST["u0"],$_POST["u1"],$_POST["u2"],$_POST["u3"]);
$titles = array($_POST["t0"],$_POST["t1"],$_POST["t2"],$_POST["t3"]);
//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
   echo"<div>
            <input name='i".$x."' type='text' value='".$images[$x]."'>
            <input name='u".$x."' type='text' value='".$urls[$x]."'>
            <input name='t".$x."' type='text' value='".$titles[$x]."'>";
       $x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Store the variables in a PHP session.

session_start();
$_SESSION['images'] = $images;

Then on next (or any other) page, you can retrieve the values as:

session_start();
$images = $_SESSION['images'];

Solution 2

Changing the scope of the variables to a larger scope, might do the trick. Also, check if you have a post request before updating the values.

<?php
    if(sizeof($_POST) >0)
    {
      //UPDATE VALUES
    }
?>

Solution 3

If you want a permanent storage of state, between different pages, you should use sessions, by putting session_start(); in the start of your script. After this, every variable $_SESSION[$x] will be persisted, and will be available to your scripts.

However, in this particular case, answering your question: “Is there a way to store the values of the array so that the form always gets pre-filled with the last saved values?”, it is easier to just use the $_POST variable if it exists already:

<?php
if(!$_POST){
    $_POST = array();
    foreach(array("i0","i1","i2","i3") as $i) $_POST[$i]="";
    foreach(array("u0","u1","u2","u3") as $i) $_POST[$i]="";
    foreach(array("t0","t1","t2","t3") as $i) $_POST[$i]="";
}
foreach($_POST as $k=>$v)  filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);

//save the arrays with the form data
$images = array($_POST["i0"], $_POST["i1"], $_POST["i2"], $_POST["i3"]);
$urls   = array($_POST["u0"], $_POST["u1"], $_POST["u2"], $_POST["u3"]);
$titles = array($_POST["t0"], $_POST["t1"], $_POST["t2"], $_POST["t3"]);


//print the arrays
print_r($images);
print_r($urls);
print_r($titles);
//create the form and populate it
echo "<p><form method='post' action='".$_SERVER['PHP_SELF']."';";
$x = 0;
while ($x <= 3) {
   echo"<div>
            <input name='i".$x."' type='text' value='".$images[$x]."'>
            <input name='u".$x."' type='text' value='".$urls[$x]."'>
            <input name='t".$x."' type='text' value='".$titles[$x]."'>";
       $x++;
}
?>
<br>
<input type="submit" name="sumbit" value="Save"><br>
</form>

Note: this line foreach($_POST as $k=>$v) filter_input(INPUT_POST,$k,FILTER_SANITIZE_SPECIAL_CHARS);
should be enough to protect you from basic XSS attacks.
Note also that in general, it is best to follow the pattern of reloading pages with GET after POST, which makes you less susceptible to form resubmitions, in which case using sessions for storage is the better solution.

Solution 4

What brought me here was somewhat different kind of beast. I had problem with subsequent post request from AXIS IP camera and needed to preserve last file name across requests. In case that someone stumble here looking for some way to cache variables and SESSION is not an option maybe should look at Alternative PHP Cache:

Note: Unlike many other mechanisms in PHP, variables stored using
apc_store() will persist between requests (until the value is removed
from the cache).

http://php.net/manual/en/book.apc.php

Solution 5

Use sessions: http://php.net/manual/en/function.session-start.php

Solution 6

You can use sessions to store values and write rules to refill form fields after validations on data submit. Also function isset() is very helpful to avoid “not defined” errors.

Solution 7

The solution you are looking for is the session. Use $_SESSION to store value of Your variables. For example, at the end of script:

$_SESSION['images'] = $images;

and in form’s input:

<input name='i".$x."' type='text' value='".(isset($_SESSION['images']) ? 
$_SESSION['images'] : '')."'>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply