How to Automatically Cloak Your WordPress File Download Links Without Using a Plugin

by Montel Anthony
How to Automatically Cloak Your WordPress File Download Links Without Using a Plugin

Link cloaking is a practice where one ensures that the URLs in their web content do not point directly to affiliate links or a place where pirated files can be downloaded. It involves creating a forwarding service to ensure that, instead of directing the link the user clicks to the desired destination. However, the actual destination is not directly linked to the cloaked link; instead, upon being clicked, the user is taken through a number of intermediate pages before arriving at the actual destination. This conceals the actual location from those who will search for anti-infringement and avoids the exposure of the real server. Nevertheless, link cloaking is prohibited in most parts of the website’s terms of service. It is utilized to direct clicks to P2P sites that offer files to download for a price although these sites may be illicit. When the relationship between link cloaking and restricted downloads is comprehended, it is easier to spot the prohibited downloads and penalize the accountable parties for violating the service provision or copyright laws. Read on 7 Best URL Shorteners for WordPress to Track Links

Link Cloaking can be defined as the process of masking the original destination URL of a link behind a more familiar looking URL that is actually not the original one. When a user follows a link, he is first transferred to an intermediate website or an intermediate link before being redirected to the final link.

There are several potential benefits to cloaking download links:

  • Enhanced security: Cloaking links entails the ability of the site owners to conceal the server’s physical location and the specific file destinations of the downloads. This makes it difficult for hackers and other ill-intentioned people to retrieve or tamp with files. As captivating as it sounds, the facade URL here does not tell the full story of the actual download location.
  • Improved click-through rates: Cloaked links help site owners to use any custom pages they may have where they put up promotions, instructions, terms of service, etc., before directing the user to the actual page they wanted to get them to go to; like downloading a file.
  • Better user experience: Intermediate landing pages are slightly more flexible in terms of control that site owners have over the download process. Some of the things that can be presented are messages, progress bars, contact details and others. In summary, cloaking links can cause of a less cluttered, therefore giving the users a less confusing experience while getting to the downloads.

Preparing Your WordPress Environment

  • Ensure WordPress is up to date
  • Backup your site before making changes

Access the Functions.php File

To start, log in to your Cpanel/Hpanel/Direct Admin.

Locate, the File Manager >> Public_html folder for the website.

Click on the wp-content > themes > Open the theme’s folder.

Edit the functions.php file, Add the below code at the end of the functions.php:

function cloak_download_link($content) {
    $pattern = '/<a([^>]+)href=["\']([^"\']+\.(mp3|mp4|pdf|zip|rar|docx?|xlsx?|pptx?))["\']([^>]*)>(.*?)<\/a>/i';
    return preg_replace_callback($pattern, 'replace_download_link', $content);
}

function replace_download_link($matches) {
    $original_url = $matches[2];
    $file_extension = $matches[3];
    $link_text = $matches[5];
    
    // Generate a unique identifier for this download
    $unique_id = substr(md5($original_url . uniqid(rand(), true)), 0, 10);
    
    // Create the cloaked URL
    $cloaked_url = home_url('download/' . $unique_id . '.' . $file_extension);
    
    // Store the original URL in a transient, which expires after 1 hour
    set_transient('cloaked_download_' . $unique_id, $original_url, HOUR_IN_SECONDS);
    
    // Return the new link HTML
    return '<a' . $matches[1] . 'href="' . esc_url($cloaked_url) . '"' . $matches[4] . '>' . $link_text . '</a>';
}

function handle_cloaked_download() {
    if (preg_match('/^\/download\/([a-zA-Z0-9]+)\.(.+)$/', $_SERVER['REQUEST_URI'], $matches)) {
        $unique_id = $matches[1];
        $file_extension = $matches[2];
        $original_url = get_transient('cloaked_download_' . $unique_id);
        
        if ($original_url) {
            // Get file information
            $file_info = wp_remote_head($original_url);
            if (is_wp_error($file_info)) {
                wp_die('Error accessing the file.');
            }

            $file_size = wp_remote_retrieve_header($file_info, 'content-length');
            $file_type = wp_remote_retrieve_header($file_info, 'content-type');
            $file_name = basename(parse_url($original_url, PHP_URL_PATH));

            // Set headers for download
            nocache_headers();
            header('Content-Type: ' . $file_type);
            header('Content-Length: ' . $file_size);
            header('Content-Disposition: attachment; filename="' . $file_name . '"');
            header('Expires: 0');

            // Output file contents
            readfile($original_url);
            exit;
        } else {
            wp_die('This download link has expired or is invalid.');
        }
    }
}

// Hook the cloaking function to the_content filter
add_filter('the_content', 'cloak_download_link');

// Hook the download handler to init action
add_action('init', 'handle_cloaked_download');

// Add a function to clear expired transients periodically
function clear_expired_download_transients() {
    global $wpdb;
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_cloaked_download_%' AND option_value < " . time());
    $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_cloaked_download_%' AND option_name NOT IN (SELECT CONCAT('_transient_', option_name) FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout_cloaked_download_%')");
}

// Schedule the cleanup function to run daily
if (!wp_next_scheduled('clear_expired_download_transients')) {
    wp_schedule_event(time(), 'daily', 'clear_expired_download_transients');
}
add_action('clear_expired_download_transients', 'clear_expired_download_transients');

Access the .htaccess file

Inside the public_html, edit the .htaccess file

Add the code below:

# Cloaked Download Links
RewriteRule ^download/([a-zA-Z0-9]+)\.(.+)$ /index.php [L]

Once you are done, save the file and test your site. To every .mp3, .mp4, .pdf files you added in a post, It will look like https://www.mp3juiceng.com/download/randomCharacters. This also refreshes and expires after 1 hour. You can modify the code to your taste.

Conclusion

People want to hide file download links on their WordPress site and this post gives multiple tricks to do that without having to use plugins. One way to do this is to include simple PHP snippets in the theme files, where you can provide direct file links for human users while presenting bots and crawlers with intermediate pages with CAPTCHA. This enhances the experience of the end user while safeguarding your bandwidth and server capacity.

Recap of the advantages of cloaking file download links:

  • Improved traffic – visitors are more comfortable since they can download files without having to go through endless pages and captcha.
  • Conserves space – downloads and uploads are protected from malicious bots and crawlers from accessing large files.
  • Less stress to your server – this means that the number of large files being downloaded without permission from your website is reduced and so the stress to your server is also reduced.
  • No plugin necessity – cloaking can be implemented with PHP and localized in the theme, so there will be no compatibility problems.

It is also important to note that the PHP code snippets provided in this article can be easily modified to fit your WordPress site and can also be incorporated into it. Thus, while it is time-consuming to cloak the files you host to facilitate downloads, there are multiple direct benefits, as has been described above. Try it – I am sure that this strategy of using direct download in combination with bot protection is good not only for you but for users as well.

Related Posts

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Blogarama - Blog Directory

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.