PrototypeX7 PrototypeX7 - 4 months ago 26
PHP Question

Where to store error/info messages for the user in PHP?

I was wondering, what's the best way to store messages for the user in PHP. With messages i mean something like


Authentication successful


or


Please enter a valid e-mail address


Currently I'm working on a project where they are stored in the
$_SESSION
variable, but I don't think this is a good solution.

Short explanation how I do it at the moment (The class
Message
was created by me)

$_SESSION["msg"][] = new Message("...");


and

foreach ( $_SESSION ["msg"] as $msg ) :
echo $msg->getText();
endforeach;

unset ( $_SESSION ["msg"] );


This is just a simplified version of the complete code, but you should get the idea.

EDIT: Forgot to say, that I'm working with an MVC framework and want to speperate the logic from the output.

Answer

One can only speculate on the nature/contents of your Message Class. However, here; attempt was made to simulate a mock-up of a class called Message; also the Usage in your View Script was shown below the Class. Be sure that $_SESSION is active on both Scripts.... Perhaps, this may shed some new light on how to go about your unique case:

    <?php

        //FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
        if (session_status() == PHP_SESSION_NONE  || session_id() == '') {
            session_start();
        }

        class Message {

            protected $msg;

            public function __construct() {
                if(!isset($_SESSION['msg'])){
                    $_SESSION['msg']    = array();
                }
            }

            public function setText($message){
                if(!in_array($message, $_SESSION['msg'])){
                    $_SESSION['msg'][]  = $message;
                }
            }

            public function getText(){
                return "Some Logic for getting Message";
            }
        }
        ?>


        <?php
            // INSIDE OF YOUR VIEW SCRIPT; AT THE VERY TOP, ENABLE SESSION AS WELL:

            //FIRST CHECK IF SESSION EXIST BEFORE STARTING IT:
            if (session_status() == PHP_SESSION_NONE  || session_id() == '') {
                session_start();
            }

            // THEN LOOP THROUGH THE SESSION DATA FOR MESSAGES TO BE DISPLAYED
            $msg    = new Message();
            if(isset($_SESSION['msg'])) {
                foreach ($_SESSION ["msg"] as $msg) :
                    echo $msg->getText();
                endforeach;

                unset ($_SESSION ["msg"]);
            }
Comments