ten80snowboarder

Force Login for a WordPress Attachment

Dec 19th, 2016
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <p>Pass in the query-param "file" that is a numeric value of the attachment ID in WordPress<br />
  2. Example: http://www.mysite.com/loader/?file=12804</p>
  3.  
  4. <?php
  5. //  load file pass-through
  6. //  include the WP environment
  7.     include_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
  8.  
  9. //  IF USER IS NOT LOGGED IN, FORCE THE LOGIN
  10. if( !is_user_logged_in() ):
  11.  
  12.     get_header(); ?>
  13.     <section id="content">
  14.         <div class="layout">
  15.  
  16.             <aside id="sidebar">
  17.                 <?php get_sidebar(); ?>
  18.             </aside>
  19.  
  20.             <article id="main">
  21.                 <h1>Login Required to View this Resource</h1>
  22.                 <?php wp_login_form(); ?>
  23.             </article>
  24.  
  25.         </div>
  26.     </section>
  27.     <?php
  28.     get_footer();
  29.  
  30. else:
  31. //  set the incoming FILE ID to a var, and then look up the file
  32. //  if the param is NOT SET or is NOT A NUMBER then display an error
  33.     $fileID = ( !is_numeric( $_GET['file'] ) || !isset( $_GET['file'] ) ? null : $_GET['file'] );
  34.  
  35. //  get the file object
  36.     $fileObj = get_post( $fileID );
  37.  
  38. //  display error if ID ENDS UP BEING NULL
  39.     if( is_null( $fileObj ) ):
  40.  
  41.         echo 'There was an error loading the file.  Please check the URL and try again.  If this error persists, please contact the website administrator with the TITLE and URL of this file.  Thank you!';
  42.  
  43.     else:
  44.  
  45.         $file = array();
  46.         $file['location']   = $_SERVER['DOCUMENT_ROOT'] . str_replace( site_url(), '', $fileObj->guid );
  47.         $file['url_parts']  = explode( '/', $file['location'] );
  48.         $file['save_as']    = end( $file['url_parts'] );
  49.         $file['mimetype']   = $fileObj->post_mime_type;
  50.  
  51.         header("Content-Type: application/octet-stream");
  52.         header("Content-Transfer-Encoding: Binary");
  53.         header("Content-disposition: attachment; filename=\"".$file['save_as']."\"");
  54.         echo readfile( $file['location'] );
  55.  
  56.     endif;
  57.  
  58. endif;
  59. ?>
Add Comment
Please, Sign In to add comment