0

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]
Community
  • 1
  • 1
melissa
  • 7
  • 7

1 Answers1

0

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.

Paulo Lima
  • 76
  • 9
  • Thank you for taking the time to help. I greatly appreciate it! I will check out your suggested code. – melissa Feb 13 '15 at 05:39