简体   繁体   中英

Create one function to check if user logged in php

I want to create a function that will check if the user is logged in. If so, the user should be navigated to userActive, otherwise the loginForm should be displayed.

I also want to carry out a check on the loginForm page to check if the user is logged in. If so, they should be taken to userActive, or kept on the loginForm page.

Why issue is why the following code doesn't work. I keep hitting a loop.

$_COOKIE['user_id'] = "user_id: 1";

activeUser();

function activeUser()
{
    if($_COOKIE['user_id'] == "user_id: 1")
    {
        header('location: index.php?a=activeUser');
    }
    else
    {
        header('location: index.php?a=loginForm');
    }
}

switch($_GET['a'])
{
    case 'loginForm':
        include_once('loginForm.php');
    break;

    case 'activeUser':
        include_once('activeUser.php');
    break;
}

That is not the proper way to set cookies in PHP. See the documentation for details.

If you are putting this on your index page... you are redirecting to your index page with a GET variable.... so... loop after loop to the same page.

You are not setting cookies properly as well.

You may want to research SESSION variables as well as that may be easier to grasp when implementing a login system.

This is how most frameworks do it :

Redirect all of the request to a single page : index.php

In this file load all the functions/classes you need (bootstrap), this could be :

  • Is the user logged in (restricted access)?

  • what country is he from (show content near him) ?

  • what language does he speak (site in english or spanish...) ?

  • ...

  • finally : where does he want to go (the page), can he go there? if not redirect.

Building all of this from scratch could be tricky, sessions, cookies, redirects, layouts, views, 404, 500, databse queries (safe ones)... Most people use frameworks, here is a list of some of them :

  • CakePHP

  • CodeIgniter

  • Symfony

  • Zend Framework

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM