简体   繁体   中英

Display message only for the first page load

I would like to display thank you message after adding comment only for the first page load... The comment form is processed using an external php file and than redirected back to the page. I would like to display some message after the redirection only... What would be the best way to do this using php?

Assuming you have access to the external php file that processes the file you could do something similar to the following on the processing file:

$_SESSION['flashMessage'] = 'Thank you for posting.';
header("Location: your-page.php');

And then add the following to the redirect page:

if ($_SESSION['flashMessage']) {
    echo $_SESSION['flashMessage'];
    $_SESSION['flashMessage'] = NULL;
}

Save the mesage into a session. Display it, and after just unset the session variable.

On the page where the comment is processed:

if($success)
{
    $_SESSION['userMsg'] = "<p>Your comment has been added. Thank you.</p>";
}

In any/all pages (but mainly the one you're redirecting to):

if($_SESSION['userMsg'] != '')
{
    print $_SESSION['userMsg'];
    unset($_SESSION['userMsg'];
}

This is assuming you're using Sessions and have therefore previously called the session_start() function

When you redirect send via $_GET array a variable something like this:

header("LOCATION: index.php?msg=1" );

On index check if $_GET['msg']==1 then display your message

You may want to apply PRG pattern. Basically you post the comment and the server replies to the client to perform a redirection to your page with additional info in Query string as Vadim argued.

"Elegant", sessionless and functional.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM