Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP passing messages between pages

Tags:

php

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.

like image 948
roflwaffle Avatar asked Dec 03 '22 08:12

roflwaffle


1 Answers

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.

like image 93
Paolo Bergantino Avatar answered Dec 17 '22 22:12

Paolo Bergantino