how to store variable values over multiple page loads

前端 未结 7 523
南笙
南笙 2020-12-18 07:34

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.

<
7条回答
  •  忘掉有多难
    2020-12-18 08:11

    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:

    $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 "

    "; $x++; } ?>

    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.

提交回复
热议问题