Home >Backend Development >PHP Tutorial >How to Display PDFs in Browsers with Click Tracking and Location Concealment Using PHP or Perl?

How to Display PDFs in Browsers with Click Tracking and Location Concealment Using PHP or Perl?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 18:13:01520browse

How to Display PDFs in Browsers with Click Tracking and Location Concealment Using PHP or Perl?

Displaying PDF Files in Users' Browsers Using PHP or Perl

Problem: Users require the ability to view PDF files within their browsers, with the additional functionality of tracking clicks and concealing the PDF's actual location.

Solution:

Both PHP and Perl offer methods to render PDF files directly in a browser. Here are the basic steps involved:

PHP:

<code class="php">header('Content-type: application/pdf');
readfile('the.pdf');</code>

Perl:

<code class="perl">open(PDF, "the.pdf") or die "could not open PDF [$!]";
binmode PDF;
my $output = do { local $/; <PDF> };
close (PDF);

print "Content-Type: application/pdf\n";
print "Content-Length: " .length($output) . "\n\n";
print $output</code>

Additional Considerations:

  • To embed the PDF within the page, set the Content-Disposition header to inline; filename="the.pdf".
  • Ensure that users have the necessary PDF reader plugin installed (e.g., Adobe Reader).
  • To disable the loading progress bar, disable the Accept-Ranges: bytes header.

Example Code:

PHP (complete):

<code class="php">$file = './path/to/the.pdf';
$filename = 'Custom file name for the.pdf';

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);</code>

Perl (complete):

<code class="perl">use strict;
use warnings;

my $file = 'the.pdf';
my $filename = 'Custom file name for the.pdf';

open(PDF, "<$file>") or die "Could not open PDF: $!";
binmode PDF;

my $size = -s PDF;

print "Content-type: application/pdf\n";
print "Content-Disposition: inline; filename=\"$filename\"\n";
print "Content-Transfer-Encoding: binary\n";
print "Content-Length: $size\n\n";

print while <PDF>;</code>

Note: Browser settings may override these techniques and force the PDF to download or open in an external application.

The above is the detailed content of How to Display PDFs in Browsers with Click Tracking and Location Concealment Using PHP or Perl?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn