The Slim Framework support forum has moved to http://discourse.slimframework.com. This Tender forum is no longer maintained or monitored.

Include

neex1233's Avatar

neex1233

09 Mar, 2012 03:01 AM

Is it possible to one route inside of another route? I'm using it to check the login, like it would be included, the the user would be checked.

  1. Support Staff 1 Posted by Andrew Smith on 09 Mar, 2012 10:51 AM

    Andrew Smith's Avatar

    I would suggest you use a middleware to do any kind of authentication checks. Sorry I don't have an example at hand but if you look in the docs you will see information about middleware.

  2. 2 Posted by neex1233 on 10 Mar, 2012 06:31 PM

    neex1233's Avatar

    I don't really understand how to use middleware. This is the code I'm using now to authenticate users:
    `

    $userID = $getUserID->id;
    $getCred = ORM::for_table('users')->where('id', $userID)->find_one();
    $username = $getCred->username;
    $password = $getCred->password;
    $auth = ORM::for_table('users')->where('username', $username)->where('password', $password)->count();
    if($auth!==1){$app->redirect('/login');$app->halt(403, 'Unauthorized');}`
    

    However, when I try to include it via middleware, it won't work.

  3. 3 Posted by Garnier on 10 Mar, 2012 07:05 PM

    Garnier's Avatar

    See if this helps:

    <?php
    require 'Slim/Slim.php';
    
    $app = new Slim();
    
    // check if user is logged in.
    $checkUser = function() use ($app) {
        if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) $app->redirect('/notloggedin');
    };
    
    // user log in
    $app->get('/login', function() use ($app) {
        $_SESSION['logged_in'] = true;
        $app->redirect('/');
    });
    
    // user log out
    $app->get('/logout', function() use($app) {
        session_destroy();
        $app->redirect('/');
    });
    
    // check if user is logged in using middleware
    $app->get('/', $checkUser, function() use ($app){
        echo 'You are now logged in. <a href="/logout">Log out.</a>';
    });
    
    // user is redirected here if not logged in
    $app->get('/notloggedin', function() {
        echo 'You are not logged in. <a href="/login">Log in</a>.';
    });
    
    $app->run();
    ?>
    

    You should be able to do something similar replacing the checkUser function with your own code.

  4. 4 Posted by neex1233 on 10 Mar, 2012 08:28 PM

    neex1233's Avatar

    Thanks, helped me understand it a lot better.

  5. neex1233 closed this discussion on 10 Mar, 2012 08:28 PM.

Comments are currently closed for this discussion. You can start a new one.

Keyboard shortcuts

Generic

? Show this help
ESC Blurs the current field

Comment Form

r Focus the comment reply box
^ + ↩ Submit the comment

You can use Command ⌘ instead of Control ^ on Mac