Search code examples
phpauthenticationuser-controls

php convert if in function


i have this code:

if (isset($_SESSION['fb_token'])){
    if ($queryusers['user_roll'] != '3'){
        header('location:' . $UrlBase."login");
        exit();
    }
}

I would like to turn it into a shorter function, in my project I am going to use this code a lot and I think there is an easier way to call the code, can you help me? Thank you!


Solution

  • I think the code will be self-explanatory:

    function shortCheck ($qu, $ub) {
        if (isset($_SESSION['fb_token']) && $qu != '3') {
            header('location: ' . $ub."login");
            exit();
        }
    }
    

    And than you call it like this:

    if (shortCheck($queryusers['user_roll'], $UrlBase)) {
        echo 'Hello admin!';
    } else {
        echo 'Not admin!';
    }
    

    EDIT: You're right about naming variables, but this is an example, not production code. For example, I name them in the way that comments are unnecessary, very long and descriptive, so the one who asked question should rename it anyway he/she finds it best.

    Maybe I don't understand the question, but summarized, to me it sounds like "I have this checks, I want to reuse it multiple times". This is why functions were invented and somebody suggested creating class for task simple as this one so I wrote this on fly.