简体   繁体   中英

PHP passing messages between pages

I have a form on a page where the user has inputs to edit a XML file, the action for the form is to send it to a separate PHP script where the editing takes place after they hit submit. The script will either write successful or fail, either way I have it redirect back to the form page via a header. Is there an easy way to pass back a confirmation or failure message to the form page? I can do it in the URL but I rather keep that clean looking.

The way that I've seen it done (and I personally use) is simply sessions.

// process something
if($success) {
    flash_message('success','Did whatever successfully.');
} else {
    flash_message('error','Oops, something went wrong.');
}
header('Location: whatever.php');

Then somewhere else, in your library or function file or whatever:

function flash_message($type, $message) {
    // start session if not started
    $_SESSION['message'] = array('type' => $type, 'message' => $message);
}

Then in the view/page you could do:

if(isset($_SESSION['message'])) {
    printf("<div class='message %s'>%s</div>", $_SESSION['message']['type'],
    $_SESSION['message']['message']);
    unset($_SESSION['message']);
}

This is pretty basic but you could expand it from there if you want multiple messages and so on. Bottom line is that I believe sessions are best for this.

I prefer to put the form handling code and the form show code in the same page. If you really want to separate it you can move the code to a different file and include that file from the form file, but from the client-side it will look like the same PHP file.

Then, always submit to the form and do your error checking at the top before you display the form. If there is a message to display you just render the form again and show the message along with the users' data so they can fix the problem. They can submit again and you can check for errors again. If they successfully submit you can redirect them somewhere else or just show a "Success" message instead.

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