How to create downloadable PDF link that works in all mobile browsers – Chrome, Safari etc.

In some mobile browsers PDF links might not work properly.
Instead of downloading, its tab just disappears immediately after opening. And we get no downloaded PDF.

Auto-close, auto-disappear – whatever you call that – but the problem exists.

So for WordPress websites, here is how to skip this pdf-download block for mobile browsers.

We will use pseudo-page link in order to bypass that block.

I mean, instead of direct links to PDF, we will use pseudo-pdf link which doesn’t look like PDF, but actually returns PDF header and body.

Let’s say that we have a PDF ile in “wp-content/uploads/2022.pdf”.

Here is how to create downloadable PDF links in mobile Chrome, Safari etc.

First, instead of using such links

<a href="https://yourwebsiteurl/wp-content/2022.pdf">Download</a>

we will use this

<a href="https://yourwebsiteurl/downloadpdf/2022">Download</a>

Now we have non-pdf link which should actually return PDF file.

By turning the PDF link into an ordinaty WP page link we actually solved mobile-browser PDF blocking problem. Now the link will be loaded in all possible browsers.

Now we can write its backend code:

<?php
add_action('init',function(){
	if(strpos($_SERVER["REQUEST_URI"],'downloadpdf')!==false){
		$pdfname=explode("/",trim($_SERVER["REQUEST_URI"]));
		$pdfname=$pdfname[count($pdfname)-1];
		$pdfname=str_replace(['.','/'],'',$pdfname);
		if(file_exists('2022/sertifikat/'.$pdfname.'.pdf')){
			$filename = '2022/sertifikat/'.$pdfname.'.pdf';
			$fileinfo = pathinfo($filename);
			$sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);
			header('Content-Type: application/pdf');
			header("Content-Disposition: attachment; filename=\"$sendname\"");
			header('Content-Length: ' . filesize($filename));
			readfile($filename);
			die();
		}	
	}
});

After applying this code (to your theme’s functions.php f.i.) the link

“https://yourwebsiteurl/downloadpdf/2022”

will download your PDF file which actually is in wp-content/uploads directory.


Discover more from WP DEV - Elvin Haci

Subscribe to get the latest posts sent to your email.

Leave a Reply

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

Discover more from WP DEV - Elvin Haci

Subscribe now to keep reading and get access to the full archive.

Continue reading