doudieheng5322 2015-01-26 06:18
浏览 56

PHP if(登录)然后(加载页面)else(重定向登录)?

I'm trying to understand how to write PHP code to only allow logged-in visitors to access a directory/folder. I already have the .htaccess rule to load a PHP doc when visiting the url, and it redirects to the login page like I want. But I'm trying to understand the PHP to load the url content when the user is logged in.

Here is what I have so far:

<?php
/* Protect directory files with login. */

 /* Load WordPress heading */
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();


/* If user is logged-in else redirect to login */
is_user_logged_in() ||  auth_redirect();

I found this answer to get the current page url using this code:

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 return $pageURL;
}

But how do I write an expression to load the page if the user is logged in?


And for those who want to know the .htaccess rule I'm using to load the login-check.php file is this:

RewriteCond %{REQUEST_URI} ^.*protected/.*
RewriteRule ^protected/(.*)$ login-check.php?file=$1 [QSA,L]
  • 写回答

1条回答 默认 最新

  • duanliaolan6178 2015-01-26 16:45
    关注

    You must save the information that the user is logged in a $_SESSION so you can validade it everytime you load a page.

    What you need is something like this:

    When your user is loggin in you should do this:

    if($user == 'user' && $pass =='password'){ $_SESSION['auth']['user'] = $user; $_SESSION['auth']['logged'] = true; }

    Create a function to check if the user is logged in:

    function checkLoggedUser($user) { if ($_SESSION['auth']['user'] != $user || $_SESSION['auth']['logged'] != true) header('location:redirectpage.php'); echo 'page content here.'; }

    at the start of every 'protected' PHP file call the function:

    checkLoggedUser($_SESSION['auth']['user']);

    Remember this is an example, avoid using logged==true at all costs for security reasons.

    Sorry for my bad english.

    评论

报告相同问题?

悬赏问题

  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图