How to Hide Download Url - WordPress - Kvcodes
X

Congrats, You are Subscribed to Receive Updates.

How to Hide Download Url – WordPress


Whenever you allow users to download your files, its kept simple and just ping your files path to the download button, When user press this button, it will  start downloading automatically. Which is not secure way, because many evil eyes are looking your folder path for download file. so they may access your host files directly, We can prevent it by adding some fake urls instead of the original path for every downloads.

<?php 

ob_start();
function download_link_page(){
    global $wpdb , $current_user , $wp_roles;	
    get_currentuserinfo();
    $setting = wp_upload_dir();
    $allowed_referred = "";
    $base_dir = $setting['basedir'];
    $log_downloads = true;
    $down_stat_table = $wpdb->prefix.'download_stat';

    if(!empty($settings)) {
        foreach($settings as $setting) {
            if(rtrim($setting->allowed_referred) != "")
                $allowed_referred =  $setting->allowed_referred;

            if(rtrim($setting->base_dir) != "")
                $base_dir =  $setting->base_dir;

            if($setting->log_downloads == "0")
                $base_dir =  false;
        }
    }    

    define('ALLOWED_REFERRER', $allowed_referred);
    define('BASE_DIR',$base_dir);
    define('LOG_DOWNLOADS',$log_downloads);   
    define('LOG_FILE','downloads.log');

    $allowed_ext = array (
        'zip' => 'application/zip',
        'txt' => 'application/txt',
        'doc' => 'application/msword'   
    );  							//Specify your support mine type for user download
    ####################################################################
    ###  DO NOT CHANGE BELOW
    ####################################################################
    if (ALLOWED_REFERRER !== '' && (!isset($_SERVER['HTTP_REFERER']) || strpos(strtoupper($_SERVER['HTTP_REFERER']),strtoupper(ALLOWED_REFERRER)) === false)) {
     	   if(strtoupper($_SERVER['HTTP_REFERER']) != home_url())  {
            $referredBy = strtoupper($_SERVER['HTTP_REFERER']);
            $parent   = strtoupper(home_url());
            $pos = strpos($referredBy, $parent);
            if ($pos === false) 
                die("Internal server error. Please contact system administrator.");
             else {     }
        }
    }
    set_time_limit(0);

    if (isset($_POST['item_number']) || (!empty($_POST['item_number']))) {
		 if (strpos($_POST['item_number'], "\0") !== FALSE) die('');
	$post_id= trim($_POST['item_number']);
	$args = array(
			'post_type'   => 'attachment',
			'numberposts' => -1,
			'post_parent' => $post_id,
			'post_mime_type' => 'application'
			);
		$attachments = get_posts( $args );
			if ( $attachments ) {
				foreach ( $attachments as $attachment ){ 		
					$fname = get_post_meta($attachment->ID,'_wp_attached_file',true);
			 		$fname = substr($fname, 8); 
				}
			}
			_e("Your download starts within five seconds.");

	}else {

    	_e("Sorry No File is specified to download.");
	echo '</section>';
	get_footer();
	exit(0);
	}

 if (!isset($_POST['txn_id']) || empty($_POST['txn_id'])) {	
	$gateway = "Free Gateway" ;
	$txn_id = $post_id."_".$current_user->ID;
	}
  else {
	$txn_id = trim($_POST['txn_id']);
	$gateway = trim($_POST['custom']);
	}
    function find_file ($dirname, $fname, &$file_path) {        
        $dir = opendir($dirname);        
        while ($file = readdir($dir)) {
            if (empty($file_path) && $file != '.' && $file != '..') {
                if (is_dir($dirname.'/'.$file))
                    find_file($dirname.'/'.$file, $fname, $file_path);                
            else {
                if (file_exists($dirname.'/'.$fname)) {
                    $file_path = $dirname.'/'.$fname;
                    return;
                	   }
            	}
            }
        }

    } // find_file
    // get full file path (including subfolders)
    $file_path = '';
    find_file(BASE_DIR, $fname, $file_path);
    echo $file_path;
	$fname ; 
    if (!is_file($file_path)) _e("File does not exist. Make sure you specified correct file name.");    

    $fsize = filesize($file_path); 
    $fext = strtolower(substr(strrchr($fname,"."),1));
    if (!array_key_exists($fext, $allowed_ext))  _e("Not allowed file type.");     

    if ($allowed_ext[$fext] == '') {
        $mtype = '';       
        if (function_exists('mime_content_type') && is_file($file_path) ) {
            $mtype = mime_content_type($file_path);
        }
        else if (function_exists('finfo_file') && is_file($file_path) ) {
            $finfo = finfo_open(FILEINFO_MIME); // return mime type
            $mtype = finfo_file($finfo, $file_path);
            finfo_close($finfo);  
        }
        if ($mtype == '') {
            $mtype = "application/force-download"; 
        }
    }
    else    $mtype = $allowed_ext[$fext];

    if (!isset($_GET['fc']) || empty($_GET['fc'])) {
        $asfname = $fname;
    }
    else {
        $asfname = str_replace(array('"',"'",'\\','/'), '', $_GET['fc']);
        if ($asfname === '') $asfname = 'NoName';
    }

    $date =date('Y-m-d H:i:s');   
    $wpdb->insert($down_stat_table , array(
			'time' => $date,
			'project_id' => $post_id,
			'buyer_name' => $current_user->user_login,
			'buyer_email' => $current_user->user_email,
			'txn_id' => $txn_id,
			'gateway' => $gateway,
			'ip_addr' => $_SERVER["REMOTE_ADDR"]
		));
	if( $gateway == 'Free Gateway' ) {
		$down_count = get_post_meta($post_id, 'down_count', true);
		$down_count = $down_count + 1;
		update_post_meta($post_id, 'down_count', $down_count); 
	}
	$tot_charge = get_post_meta($post_id , 'total_charges', true);
	$tot_charge = $tot_charge + $down_count * 1.25;
	update_post_meta($post_id, 'total_charges' , $tot_charge);

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Type: $mtype");
    header("Content-Disposition: attachment; filename=\"$asfname\"");
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: " . $fsize);

	ob_clean();   // discard any data in the output buffer (if possible)
	flush();      // flush headers (if possible)

	//readfile($file_path);
	//exit();
	//@readfile($file_path);

    $file = @fopen($file_path,"rb");
    if ($file) {
        while(!feof($file)) {
            print(fread($file, 1024*8));
            flush();
            if (connection_status()!=0) {
            @fclose($file);
            die();
        }
    }
    @fclose($file);
    }
    // log downloads
    if (!LOG_DOWNLOADS) die();

    $f = @fopen(LOG_FILE, 'a+');
    if ($f) {
        @fputs($f, date("m.d.Y g:ia")."  ".$_SERVER['REMOTE_ADDR']."  ".$fname."\n");
        @fclose($f);
    }    
}    add_shortcode( 'download_page', 'download_link_page' ); ?>
?>

The above code help you to hide your uploads folder path and download file location. you can use this functionality by creating your download page and add the short code [download_page] .  You are required to pass your download file id by using post method, than the download begins automatically.

Here is the sample form to pass the id to download page.

<form method="post" action="<?php echo site_url('download-page'); ?>" >
	<input type="hidden" name="item_number" value="<?php echo $post->ID; ?>" >
	<input type="submit" value="Download" class="class-btn" name="submit"> 
</form>

That’t it . Queries comment below.

 

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, OpenCart Theme Development, PHP, HTML, CSS, jQuery, Bootstrap development and content SEO.

Comment Below

Your email address will not be published. Required fields are marked *

*

Current ye@r *

Menu

Sidebar

Subscribe E-mail Updates

Congrats, You are Subscribed to Receive Updates.

Advertisement

Category Posts