Troubles with a PHP session variable after form submission

前端 未结 3 673
Happy的楠姐
Happy的楠姐 2021-01-22 12:36

I\'m setting a PHP session variable with a success message for a HTML form that I\'m submitting. If there are no form errors, I redirect to the same page (using header()) and di

相关标签:
3条回答
  • 2021-01-22 13:20

    Before displaying the message you could do a check that the message is not empty. If it isn't empty then display the message and immediately afterwards explicitly empty the session variable so that next time the preceding check won't display the message.

    I hope I understood your question :)

    0 讨论(0)
  • 2021-01-22 13:30

    Would it be enough to just clear the session variable after you display the message?

    That seems like the most straightforward solution. You could also:

    A) Check to see what information lies in the $_SERVER variable to try to detect how the user got to the page, only displaying the message if it happened from the rout.

    B) Have the redirect include a querystring variable (for instance '?messages=1') which you check using $_GET before displaying the session message.


    EDIT: I thought the order of operations is:

    1) form submit 2) if no errors, set message in session 3) redirect 4) display the message after the redirect

    I'm saying add step 5: delete the message AFTER it is displayed. As in, echo the message like you are doing, but then add code after the echo to delete or clear the session variable.


    EDIT 2: Ahh, I understand now...

    I'm curious if you should be referencing the session variable directly from your template file. Might it be better to pass it in as a template parameter that gets set by the PHP which calls the template? This gives you the ability to separate session management from display, which is probably in your best interest anyway.

    0 讨论(0)
  • 2021-01-22 13:31

    Destroy the session:

    Change your code to look something like this

    if(isset($_SESSION['sentData'])
    {
    echo "Your message";
    
    //This
    session_destroy();
    //or this
    unset($_SESSION['sentData']);
    }
    

    EDIT:

    Actually no, put this at the end of form.php/your template file/after you have displayed the message:

    unset($_SESSION['status']);
    
    0 讨论(0)
提交回复
热议问题