Use this php code to open a pdf in a new tab

Use this php code to open a pdf in a new tab

October 19, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Use this php code to open a pdf in a new tab

Opening PDF Files in a New Browser Tab

In web development, there are often occasions where you might want a file, such as a PDF document, to open not in the same page but rather in a new browser tab. This is particularly useful when you have a large amount of content on your page and opening resources in a new tab provides a better user experience.

Let’s dive into how we can achieve this using the PHP code snippet you’ve provided:

Understanding Your Current Code

You’re currently using header() functions to set the appropriate response for downloading or viewing the PDF file. The headers are correctly configured to send a binary file of type ‘application/pdf’. However, the file is being displayed inline in the current page.

$file = $pdf_file_path;
$filename = $file_name;

header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

@readfile($file);

The Content-Disposition header with inline is causing the PDF to be displayed in the current window. If we want it to open in a new tab, we need to change this.

Opening PDFs in a New Tab

To open a file in a new browser tab, you can use JavaScript along with PHP. The idea is to generate an anchor tag that will trigger when clicked and force it to open the link in a new window or tab using target="_blank".

Here’s how we can modify your existing code:

$file = $pdf_file_path;
$filename = $file_name;

header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
header('Accept-Ranges: bytes');

// Serve the PDF
readfile($file);

We’ve changed inline to attachment. This tells the browser that it should force a download of this file, which will trigger your browser to create a new tab.

Conclusion

Opening files in a new tab is a great way to improve the user experience on your website. By using a combination of PHP and JavaScript, you can ensure that when users click on links, they open in a new window or tab rather than staying on the current page.

Remember, this method works best with PDFs and other downloadable files. For content that is meant to be viewed within your website, it’s usually better to keep them inline.

PHP JavaScript CLI

Our network