简体   繁体   English

检查用户是否通过php中的函数登录

[英]Check if the user is logged in through a function in php

I have a little problem with PHP, probably for most of you it's a stupid problem, but I need your help. 我的PHP有点问题,对于大多数人来说可能是一个愚蠢的问题,但我需要您的帮助。
Here's my code: 这是我的代码:

function is_logged() {
if(isset($_COOKIE['username'])) {
    return true;
} else {
    return false;
}
}

And here is a piece of the whole code where I need to deny someone the access if isn't logged. 这是整个代码的一部分,如果没有登录,我需要拒绝某人的访问。

if(!is_logged()) {
header("Location: ./?act=Home");
}

Where do I made the mistake? 我在哪里弄错了?

EDIT: I'm sorry, I haven't explained the problem at all... This function does not redirect, leaving blank the page! 编辑:对不起,我根本没有解释问题。此功能不会重定向,将页面留空!

Try this: 尝试这个:

At the very beginning of the page, put ob_start() to prevent any error messages from being outputted, and then change the check to this: 在页面的最开始,放置ob_start()以防止输出任何错误消息,然后将检查更改为此:

if(!is_logged()) {
    ob_clean();
    header("Location: ./?act=Home");
    die();
}

The die() here prevents the PHP from doing something else (perhaps modifying the header so there is no redirect). die()可以防止PHP进行其他操作(可能会修改标头,因此没有重定向)。 You should also check to see if there is an error message being generated before this code is called (as this is usually the problem with header() redirects). 您还应该在调用此代码之前检查是否生成了错误消息(因为通常这是header()重定向的问题)。 Make sure error messages are turned on in php.ini and/or in your PHP with display_errors . 确保在php.ini和/或PHP中使用display_errors打开错误消息。 Note that ob_start and ob_clean will prevent error messages from showing up, so you will want to temporarily remove them to see what the errors are.... 请注意, ob_startob_clean将阻止显示错误消息,因此,您将需要临时删除它们以查看错误是什么...。

That all being said, just using cookies to determine if a user is logged in or not is considered bad practice, as it is incredibly easy for anyone to make a cookie on their browser. 综上所述,仅使用cookie来确定用户是否已登录是不正确的做法,因为任何人都可以在其浏览器上创建cookie,这非常容易。 You should being doing some server-side check to make sure it is a valid login. 您应该在服务器端进行一些检查,以确保它是有效的登录名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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