Search code examples
phppostmessage

Using php header Location to exchange messages between pages with POST


I am using already this code:

<?php
// [...]
ELSE IF(isset($_GET['msg'])){
    echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
    <h2 class='panel-title'>Good job!</h2></div>
    <div class='panel-body'><h4>".addslashes(strip_tags(trim(@$_GET[msg])))."</h4></div></div>";
    }
//[...]
?>

Which is called from other pages if some operation goes well:

  if ($result){
      header("Location:index.php?msg=DB updated succesfully");
      exit;
  }

BUT as you may imagine, it is not clean. Working, but not the best.

Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?

And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google. But I just can't understand how to do it.

Thanks a lot guys!


Solution

  • Because you prefer to keep your code pure

    i just suggest you to do not send the message in GET/POST

    just send the status like

    index.php?status=success
    

    then check the status in result file

    if(isset($_GET['status']) AND $_GET['status'] == success){
       echo "bla bla";
    }elseif(isset($_GET['status']) AND $_GET['status'] == fail){
       echo "bla bla";
    }else{
       //do something
    }
    

    EDIT

    If you have many messages, then you can create array

    $message = [
      'success' => 'success message here',
      'fail' => 'failmessage here',
      'notFound' => 'not found message'
    ];
    
    $status = ( isset($_GET['status']) AND 
                isset($message[$_GET['status']]) )?$_GET['status']:'notFound';
    
    echo $message[$status];