HTML Email Subscribe with PHP

Today we are going to see about email subscription for newsletter or mail alerts.
Recently when I was creating newsletter for my users, I got this topic in my mind so plan to create post for this one.

Email subscription used for varies side, newsletter which works weekly and monthly or mail alerts works for send alert mail based on the keywords, post content and much more.

1) Subscribe table – which hold subscription data for the email address
2) Html and server-side script (PHP)

Subscribe table which hold subscribed email address, status, ip address & datetime.

CREATE TABLE IF NOT EXISTS `subscribe` (
  `ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `Email` varchar(255) NOT NULL,
  `subscribeStatus` enum('A','D') NOT NULL DEFAULT 'D',
  `subscribeIP` int(11) unsigned NOT NULL,
  `subscribeDateTime` datetime NOT NULL,
  `unSubscribeIP` int(11) unsigned NOT NULL,
  `unSubscribeDateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `idx_email` (`Email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

subscribe.html file for subscribe email address

<html>
<head>
<title>Codeasearch.com - HTML Email Subscribe with PHP - Subscribe form</title>
</head>
<body>
<table>
<form method="post" action="email_subscribe.php">
<tr>
<td>Email Address:</td>
<td>
<input type="text" name="txtEmail" /> <input type="submit" name="btnSubmit" value="Submit" /></td>
</tr>
</form>
</table>
</body>
</html>

Now our server-side scripting, first we will create database connection file called db_con.php its a mysqli connection.

<?php 
// database connection
$mySqli = new mysqli("localhost","root","","test");

email_subscribe.php file to check email address already exists or not and subscribe the email address.

<?php 
// include database connection
require("db_con.php");

// check the btnSubmit button 
if(isset($_POST["btnSubmit"])) {

	// default value assign to strFlag variable
	$strFlag = 'invalid';
	
	// validating email address
	if(filter_var($_POST["txtEmail"],FILTER_VALIDATE_EMAIL,FILTER_FLAG_PATH_REQUIRED)==true) {
	
		// assigning values in email and ip variable
		$email = addslashes($_POST["txtEmail"]);
		$ip = ip2long($_SERVER["REMOTE_ADDR"]);
		
		// querying the email already exists or not
		$strSql = "select ID from subscribe where email='".$email."'";
		$result = $mySqli->query($strSql);
		
		// if the email address not exists, we are insert data into database
		if($result->num_rows==0) {
			$mySqli->query("insert into subscribe (Email,subscribeStatus,subscribeIP,subscribeDateTime) values ('".$email."','A','".$ip."','".date("Y-m-d H:i:s")."')");
			
			// assign the flag to valid
			$strFlag = 'valid';			
		}
	}	
	
	// redirected into same url with the flag assigned value
	header("Location: email_subscribe.php?flag=".$strFlag);
}

// checking the flag parameter
if(isset($_GET["flag"])) {
	switch($_GET["flag"]) {		
		case "valid":
			$str = 'Email address has been Subscribed';
		break;
		
		case "invalid":
			$str = 'Email address already exists';
		break;
	}	
	
	// printing the value based on the switch case
	echo $str;
}

email_unsubscribe.html for unsubscribe the email address, there is no change between first and second html.

Because both the html tag are same but action are different subscribe.html file action to email_subscribe.php file for subscription and email_unsubscribe.html file action to email_unsubscribe.php for unsubscribe the email address.

<html>
<head>
<title>Codeasearch.com - HTML Email Subscribe with PHP - unSubscribe form</title>
</head>
<body>
<table>
<form method="post" action="email_unsubscribe.php">
<tr>
<td>Email Address:</td>
<td>
<input type="text" name="txtEmail" /> <input type="submit" name="btnSubmit" value="Submit" /></td>
</tr>
</form>
</table>
</body>
</html>

email_unsubscribe.php file same as email_subscribe.php little different, if email address already exists it will update the subscribe status to de-active mode and update the ip and datetime.

<?php 
// include database connection
require("db_con.php");

// check the btnSubmit button 
if(isset($_POST["btnSubmit"])) {
	
	// default value assign to strFlag variable
	$strFlag = 'invalid';
	
	// validating email address
	if(filter_var($_POST["txtEmail"],FILTER_VALIDATE_EMAIL,FILTER_FLAG_PATH_REQUIRED)==true) {
		
		// assigning values in email and ip variable
		$email = addslashes($_POST["txtEmail"]);
		$ip = ip2long($_SERVER["REMOTE_ADDR"]);
		
		// querying the email already exists or not
		$strSql = "select ID from subscribe where email='".$email."'";
		$result = $mySqli->query($strSql);
		
		// if the email address exists, we are deactivating the status
		if($result->num_rows>0) {
			$mySqli->query("update subscribe set subscribeStatus='D',unSubscribeIP='".$ip."' where email='".$email."'");
			
			// assign the flag to valid
			$strFlag = 'updated';			
		}
	}

	// redirected into same url with the flag assigned value	
	header("Location: email_unsubscribe.php?flag=".$strFlag);
}

// checking the flag parameter
if(isset($_GET["flag"])) {
	switch($_GET["flag"]) {
		
		case "updated":
			$str = 'Email address has been unSubscribed';
		break;
		
		case "invalid":
			$str = 'Email address already exists';
		break;
	}

	// printing the value based on the switch case	
	echo $str;
}

We are not sending mail to user, when user subscribe or unsubscribe the email address. Just we are making insert and update statement.