PDF to Email with registration

Serve PDF files on your website by requesting the user to register their email address. The PDF file is sent to the given email address and the user details registered on a database. This is a very simple script and relies on four main features.

Apache mod_rewrite (via the .htaccess file)

PHPMailer

MySQL database

the simple-register.php script itself

See a demo here

Let’s start, first you need to create the folder on your site where you are going to place your PDF files, in my case I called it /pdf/ so the address to your files should be something like this, http://yoursite.com/pdf/yourfile.pdf

1. Apache mod_rewrite (via the .htaccess file)

create a text file and name it .htaccess and add the follwing text

RewriteEngine On
RewriteBase /
RewriteRule ^(.*).pdf$ /pdf/simple-register.php?file=$1 [R=301,NE,L]

Mod_rewrite will redirect any trffic to your .pdf file to the registration form “/pdf/simple-register.php”, if you save the php file with a different name you will need to adjust this file with the correct filename.

2. PHPMailer

is an openSource mailer script which you can download from their official site. After download extract the class.phpmailer.php file to your /pdf/ folder

3. MySQL database

Create a database with a table with the following details

`ID` int(10) unsigned zerofill NOT NULL auto_increment,
  `name` text NOT NULL,
  `email` text NOT NULL,
  `file` text NOT NULL,
  `ip` text NOT NULL,
  PRIMARY KEY  (`ID`)

if you want you can save the following code as a .sql file and upload to your MySQL using PHPmyAdmin.

CREATE DATABASE `pdflog`;
USE `pdflog`;

-- --------------------------------------------------------

--
-- Table structure for table `download_log`
--

CREATE TABLE IF NOT EXISTS `download_log` (
  `ID` int(10) unsigned zerofill NOT NULL auto_increment,
  `name` text NOT NULL,
  `email` text NOT NULL,
  `file` text NOT NULL,
  `ip` text NOT NULL,
  PRIMARY KEY  (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

4. Create the simple-register.php script

just copy the following code to a text editor and save the file as “simple-register.php” or any other name you may want to, but remember to also change the redirection on your .htaccess file.

Before you can upload your script you will need to edit some details on your file, just look at the section “############ variables for the email function ######” and add the required information. You will also need to change the database connection information, just look for the line matching the details below and change accordingly.

$dbHost = "localhost"; 	# set host - most likely you don't need to change this
$dbUser = "user";		# set database user
$dbPass = "password";		# set password
$dbName = "databbse";		# set database name

The script code

 <?php

echo "<center><div style=\"width:500px;text-align:left\">";
$email = $_POST['email'] ;
$name = $_POST['name'] ;
$pdf_file = $_REQUEST['file'] ;

$file = str_replace(".pdf","",$pdf_file); # a workaround for frinedly URL stuff

$allowed_file = "pdf"; # set single filetype

$file = "$pdf_file.$allowed_file";

$filename = str_replace("/pdf/","",$file); # removes the directory /pdf/ from the string

$ip=@$REMOTE_ADDR; // get IP address
if(!$ip) {$ip=$_SERVER['REMOTE_ADDR'];}

############ variables for the email function ######

$webmaster = "webmaster@yourdomain.com"; 	#webmaster or site email address
$site_name = "your site name";			#website name

$subject = "Your requested File: $filename"; #email subject line
$body_html = "<b>Dear $name</b><br><bR>Please find attached the file requested.</b>"; # HTML version of the message sent to user
$body_txt = "Dear $name\n\nPlease find attached the file requested."; # TEXT only version of the message sent to user
$sent_msg = "<center><h2>Thank you</h2> The file has been sent to $name - $email</center>"; # message displayed on the page after file has been sent

$errot_subject = "Blocked action attempt [$email]"; # error email subject line
$error_body_html    = "<b>This person: $name - $email</b><br><br>has attempted to downlod the file: $filename"; # HTML message to webmaster in case of attempt to access not permited file
$error_body_txt = "This person: $name - $email\n\nhas attempted to downlod the file: $filename";# TEXT message to webmaster in case of attempt to access not permited file
$error_msg = "<br><br><br><h2><center><font color=#ff0000>Access to this file is not permited.</center></h2><h4></font><br>Your details have been logged.<br><br>IP Address: $ip <br> Email: $email <br> Name: $name <br> </h4>"; # error message showed when user attempt to download a not permited filetype 

############ end vadiables #########################

if(!$email) {  #if email field is blank display the registration form

echo "<center><br><br><h2><b>Please enter your details to proceed!</b></h2><br><br><form method=post><input type=hidden value=\"$filename\" name=name> Name: <input type=text name=name><br>Email: <input type=text name=email><br> <input type=submit value=send><br><br><div style=\"text-align:left\">"; 

echo "</div></form></center>";

}

else { #otherwise send the file 

$data[] = explode(".", $file);

while (list ($key,$val) = @each ($data)) {

$file_type = $val[1];

}
 # can only email PDF files, for security
if($file_type == $allowed_file) { 
$blocked = 0; # information for the database 0 = no attempt to access unauthorized file

sendInfo($webmaster, $site_name, $name, $email, $subject, $body_html, $body_txt, $filename, $sent_msg);

}

else { 
$blocked = 1; # information for the database 1 = attempt to access unauthorized file

sendInfo($webmaster, $site_name, $webmaster, $site_name, $error_subject, $error_body_html, $error_body_txt, $filename, $error_msg);
}

	}# end else

###### write details to to database 
regtodb($name, $email, $filename, $ip, $blocked); 

echo "<div></center>";

?>

<?php

############## functions #############

# write to database

function regtodb($name, $email, $dfiles, $ip, $blocked) {

$dbHost = "localhost"; 	# set host - most likely you don't need to change this
$dbUser = "user";		# set database user
$dbPass = "password";		# set password
$dbName = "databbse";		# set database name

mysql_connect ($dbHost, $dbUser, $dbPass) or die ('MySQL connect failed. ' . mysql_error());
mysql_select_db($dbName) or die('Cannot select database. ' . mysql_error());
$query="INSERT INTO download_log VALUES ('','$name','$email','$dfiles','$ip', '$blocked')";
$result=mysql_query($query);

mysql_close();

}

# send email with phpMailer

function sendInfo($webmaster, $site_name, $name, $email, $subject, $body_html, $body_txt, $filename, $sent_msg) {

require_once("class.phpmailer.php");

$mail = new PHPMailer();

$mail->From = $webmaster;
$mail->FromName = $site_name;
$mail->AddAddress($email, $name);
$mail->AddAttachment($filename, $filename);

$mail->IsHTML(true);                                  // set email format to HTML

$mail->Subject = $subject;
$mail->Body    = $body_html;
$mail->AltBody = $body_txt;

if(!$mail->Send())
{
   echo "Message could not be sent. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo $sent_msg;

	}

?>

Now upload your files to your newly create /pdf folder together with your pdfs. Remember that your links must be to the pdf file and not the script, the mod_rewrite will take care of the redirection for you.

You may also want to add a captcha type feature to avoid spam.

Technorati Tags: , , ,

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>