Protect custom php file with login

I’ve developed a php app and I’d like that it’s restricted to WP users (use WP like a private area).
Is there a way to use WP is_user_logged_in function in a custom file (i.e. www.mysite.com/app.php)? where should I put the folder with the app ?
I tried but the page is not recognized.. (.htaccess?)

Related posts

Leave a Reply

2 comments

  1. This is impossible to answer definitively without a better description, but I am assuming that app.php is a completely distinct piece of code. In which case, WordPress can’t really manage access to it. You will need to incorporate it into WordPress. While this is not the only way to do it I would advise:

    1. Create a custom page template for the app.
    2. In that page template paste your app code or include it.
    3. Create a “Page” from wp_admin->Pages and select your template file as the “Template”
    4. To control access you can include if ( is_user_logged_in()) { logic directly in the template. Do this if you want to provide some kind of “Must be logged message”

      if ( is_user_logged_in()) {
          // your app code
      } else {
         echo "Please don't do that";
      }
      
    5. Or, hook to template_redirect. This will let you redirect to some other page

      function protect_my_app_wpse_90691() {
        if (is_page_template('template-name.php') && !is_user_logged_in()) {
          wp_safe_redirect(get_bloginfo('url').'/wp-login.php'); // or some other page that you prefer
        }
      }
      add_action('template_redirect','protect_my_app_wpse_90691');
      
  2. You’ll need to bring your code into the WordPress realm. Easiest way to do it is to create a new template (a standard .php file that will reside inside wp-content/themes/your-theme-name directory) and assign that template to a page (check this page for instructions). Look around this series of guides for more help on templates and how to build one. Your simplest template would look something like this:

    <?php
    /*
      Template Name: My Custom Template
    */
    
    get_header(); ?>
    
      <?php if ( is_user_logged_in() ) { ?>
    
    <!-- user logged in, show something to them -->
    
      <?php } else { ?>
    
    <!-- user not logged in, show error message or forward them to homepage -->
    
      <?php } // end else ?>
    
    <?php get_footer(); ?>
    

    Once you have a working page with a template, you can incorporate your code into that template and use is_user_logged_in function to do what you need to do.