Search code examples
phphttpresponsehttp-status-code-403slim

Slim PHP custom http response pages


Ok I have read the docs on Slim PHP and read quite a few tutorials, and have an application nicely under way. However I am trying to get to grips with things such as customizing the HTTP response codes. I have managed to get the following :

$app->notfound('template.file', array(
    'data' => 'passed'
));

This seems to work nicely (as it should as it is a Method directly within Slim), however not I am trying to control things such as the 403 response. I have controlled the not permitted using Apache as I usually would do, however I am wondering if there is a way with Slim that I can serve a custom Not Permitted page? Or because I have blocked it at the Apache level, will Slim not even notice?

I did read that I can manually halt certain routes? Is this the way I should do it? For example, I don't want people to access my JS directory so :

$app->group('/js', function () use($app) {
    $app->get('/', functin () use($app) {
        $app->halt(403, "You shall not pass!");
    });
});

My reason for grouping this would be because I want access to my actual scripts, just not directory browsing.

Has anybody come across this before? What would you suggest? Or am I totally over thinking something simple....


Solution

  • You could simply redirect user to another route where you print your custom template. Example:

    require 'vendor/autoload.php';
    
    session_start();
    
    $app = new \Slim\Slim();
    
    $app->group('/js', function () use($app) {
        $app->get('/', function () use($app) {
            $app->flash('httpStatusCode', '403');
            $app->redirectTo('NotAuthorized');
        });
    });
    
    $app->get('/notAuthorized', function () use($app) {
        echo 'You\'re here because you\'re Balrog!';
        echo 'Http Status Code: ' . $_SESSION['slim.flash']['httpStatusCode'];
    })->name('NotAuthorized');
    
    $app->run();