LostCore
9/11/2017 - 9:25 AM

WP File privati

WP File privati

<?php

/**
 * Make a file uri private
 *
 * @param $fileuri
 *
 * @return string
 */
function privatize_file_uri($fileuri){
	$filename = basename($fileuri);
	$secure_url = add_query_arg(["secure-download" => $filename],site_url());
	return $secure_url;
}
<?php

/**
 * Send private files to the browser
 */
function sample_download_reserved_files(){
	if(!isset($_GET['secure-download'])) return;
	
	//Begin: condizioni di sicurezza
	if(!is_user_logged_in()){
		die("404 - No file found");
	};
	//End: condizioni di sicurezza

	$filename = $_GET['secure-download'];
	$file = WP_CONTENT_DIR.'/uploads/private-files/'.$filename; //<- cartella file privati
	if(!is_file($file)){
		die("404 - No file found");
	}

	$fileInfo = new \SplFileInfo($file);

	$getMime = function($file){
		$mime = mime_content_type($file);
		return $mime === 'inode/x-empty' || !$mime ? "application/force-download" : $mime;
	};

	$getSize = function($file){
		$size = filesize($file);
		return $size;
	};

	$mimeType = $getMime($file);
	$size = $getSize($file);

	if($fileInfo->getExtension() === 'pdf'){
		header('Content-Type: '.$mimeType);
		header('Content-disposition: inline; filename="' . basename($file) . '"');
		header('Content-Transfer-Encoding: binary');
		header('Accept-Ranges: bytes');
		@readfile($file);
	}else{
		$pointer = fopen($file,"rb");

		header('Content-Type: '.$mimeType);
		header('Content-Disposition: attachment; filename="'. basename($file) . '"');
		header('Content-Transfer-Encoding: binary');
		header("Content-Length: {$size}");

		@ob_clean();
		rewind($pointer);
		fpassthru($pointer);
	}
}
add_action('send_headers', 'spi_download_reserved_files', 10);
<?php

//Ottengo in qualche modo l'url originale...
$secure_url = privatize_url($url_origiale);

?>

<a href="<?php echo $secure_url; ?>">....</a>