Search code examples
phpmodel-view-controller

PHP And mvc for back office


I have both the login and the dashboard at the same time.

Here is my code:

session_start();

require_once('controllers/dashboard.php');
require_once('controllers/admin.php');
require_once('controllers/login.php');



try {
    if (!isset($_SESSION['username'])) {
        login();
    }

    if (isset($_GET['action']) && $_GET['action'] == "signout") {
        session_destroy();
    }

    if (isset($_GET['page']) && $_GET['page'] != NULL) {
        $page = strval($_GET['page']);

        // Page d'accueil
        if ($page == "dashboard") {
            dashboard();
        } elseif ($page == "admin") {
            admin();
        }
    } else {
        require_once('templates/dashboard.php');
    }
} catch (Exception $e) {
    $errorMessage = $e->getMessage();
    require('templates/error.php');
}

I tried to first have the login page and then, after the admin logs in, to have the dashboard.


Solution

  • The issue arises from the fact that you are calling both functions at the same time, resulting in that outcome.

    So, to solve this problem, you should have a 'public' folder in your MVC with the 'login' and 'index' files. Then, remove your 'login' controller and place the code responsible for connecting you within your 'login' file.

    Normally, this should work.

    If you're having trouble, here's an example that should be your index.php:

    session_start();
    
    require_once('controllers/dashboard.php');
    require_once('controllers/admin.php');
    
    
    
    try {
        if (!isset($_SESSION['username'])) {
           header('location: login.php');
    
        }
    
        if (isset($_GET['action']) && $_GET['action'] == "signout") {
            session_destroy();
        }
    
        if (isset($_GET['page']) && $_GET['page'] != NULL) {
            $page = strval($_GET['page']);
    
            // Page d'accueil
            if ($page == "dashboard") {
                dashboard();
            } elseif ($page == "admin") {
                admin();
            }
        } else {
            require_once('templates/dashboard.php');
        }
    } catch (Exception $e) {
        $errorMessage = $e->getMessage();
        require('templates/error.php');
    }