How to require login to Wordpress to view a subdirectory on a Wordpress site?

I have a Wordpress site at xroads.com

Inside there is a folder named "_warehouse" which contains the php CRUD application

Can I require the same login page I use for my Wordpress site to view the _warehouse directory?

Thanks in advance!

enter image description here

+3


source to share


2 answers


If the user already has a WordPress account:

Redirect the user to the login form. Use wp_login_url

with a parameter $redirect

to specify where they go after login:

$loginUrl = wp_login_url( home_url('_warehouse') );

      

https://codex.wordpress.org/Function_Reference/wp_login_url



Then use the action wp_login

to manually authenticate the user to the application:

add_action('wp_login', function($username, $user) {
    // Log user into external application
}, 10, 2);

      

https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login

The actual setting of the user as "logged in" will depend on how your external application is configured. It can be as simple as setting a session variable and then checking if that is set in your storage app.

0


source


Here is one possible solution (use at your own risk).

Create a file .htaccess

in a directory _warehouse

with the following content:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ wplogin.php [NC,L]

      

This will redirect all requests for files existing in _warehouse

and any subdirectories to_warehouse/wplogin.php

Create _warehouse/wplogin.php

with the following content:

<?php

// Edit this path to include wp-load.php from your WordPress directory
require_once '../wp-load.php';

if (!is_user_logged_in()) {
    // if user is not logged in, set redirect URI, show WP login
    $_REQUEST['redirect_to'] = $_SERVER['REQUEST_URI'];
    require_once '../wordpress/wp-login.php';
    exit;
} else {
    // user is logged into wordpress - show the requsted file.
    require_once $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
}

      



Finally, and very importantly, add this to your wp-config.php

file:

define('COOKIEPATH', '/');

      

This is because WordPress will set cookies with the specified path. This will prevent login cookies from being recognized _warehouse

.

And as I said, use at your own risk. It's not ideal, but it's probably the fastest way to get what you want and will handle many cases.

Note: this does not apply to directories without an index. If Apache is Options +Indexes

enabled, someone might see the directory lists in _warehouse

, but if they try to access it, it will display the login page.

-1


source







All Articles