سیستم خبرنامه در PHP آموزش ( Email Subscription )

خبرنامه در PHP – حتما در خیلی از وب سایت ها شاهد این بوده اید که امکان ثبت ایمیل درخبرنامه برای دریافت تخفیف ها ، محصولات ، مطالب وجود دارد .
در این آموزش قصد داریم که یک سیستم اشتراک خبرنامه را در پی اچ پی پیاده سازی کنیم که شامل اسکریپت های php و جاوا اسکریپت :
- index.php ( فرم ارسال ایمیل )
- app.js ( محتوای جاوا اسکریپت از جمله ارسال ajax برای ثبت ایمیل )
- api.php ( سیستم rest که اطلاعات ارسال شده http را دریافت و پاسخ می دهد )
- functions.php ( توابع مورد نیاز از جمله برای ثبت ، لیست و جستجو رکورد )
- list.php ( لیست ایمیل های ثبت شده را در این فایل نمایش می دهیم )
خروجی برنامه خبرنامه در PHP
فایل index.php
<?php require_once "parts/header.php" ?>
<a id="introduce" href="https://rapidcode.ir" target="_blank">رپید کد • کتابخانه مجازی برنامه نویسان</a>
<form action="" class="row">
<div class="wrapper col-6 m-auto">
<img src="static/img/email.png" alt="email">
<input type="text" id="emailField" class="form-control text-center" dir="ltr" placeholder="ایمیل خود را برای خبرنامه وارد کنید">
<button type="button" id="btnSubmit" class="btn btn-lg ps-3 pe-3 pt-0 pb-1 mt-3 btn-success">ثبت</button>
</div>
</form>
</div>
<?php require_once "parts/footer.php" ?>
فایل app.js
function initXHR(config) {
const xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open(config['method'], location.origin + "/" + "inc/api.php" + config['query']);
xhr.onload = config['onload'];
xhr.onerror = config['onerror'];
xhr.send(JSON.stringify(config['data']));
}
String.prototype.getBaseConversionNumber = function(label){
const faDigits = ['۱','۲','۳','۴','۵','۶','۷','۸','۹','۰'];
const enDigits = ['1','2','3','4','5','6','7','8','9','0'];
const arDigits = ['٠','٩','٨','٧','٦','٥','٤','٣','٢','١']
var whichDigit = {};
switch(label){
case 'fa':
whichDigit[label] = faDigits;
break;
case 'en':
whichDigit[label] = enDigits;
break;
case 'ar':
whichDigit[label] = arDigits;
break;
case 'all':
whichDigit = {"fa" : faDigits, "en" : enDigits, "ar" : arDigits};
break;
default:
whichDigit = [];
}
return whichDigit;
}
String.prototype.CvnFromTo = function(fromDigits,toDigits,str){
var str = str == undefined ? this : str;
for(var i=0;i<toDigits.length;i++){
const currentFromDigit = fromDigits[i];
const currentToDigit = toDigits[i];
const regex = new RegExp(currentFromDigit,'g');
str = str.replace(regex, currentToDigit);
}
return str;
}
String.prototype.convertDigits = function(to){
let str = this;
const toCvn = (this.getBaseConversionNumber(to))[to];
const allDigits = this.getBaseConversionNumber("all");
delete allDigits[to];
const Objkeys = Object.keys(allDigits);
for(var i=0;i<Objkeys.length;i++){
const currentKey = Objkeys[i];
const fromCvn = allDigits[currentKey];
str = this.CvnFromTo(fromCvn,toCvn,str)
}
return str;
}
function toLocalDate(date , sameNumber = false) {
const localDate = new Date(date).toLocaleDateString('fa');
return sameNumber ? localDate.convertDigits("en") : localDate;
}
function disableElement(element, reverse = false) {
if (!reverse) {
element.setAttribute("disabled", true);
} else {
element.removeAttribute("disabled");
}
}
function sendEmailSubscription() {
disableElement(btnSubmit);
initXHR({
method: "POST",
query: "?action=insertEmailSubscriptionApi",
onload: function () {
const response = this.response;
if (response['message']) {
alert(response['message']);
}
if (response['success'] == 1) {
email_field.value = "";
}
disableElement(btnSubmit, true)
},
onerror: function () {
console.warn("XHR ERROR");
alert("خطا");
disableElement(btnSubmit, true)
},
data: {
email: email_field.value
}
});
}
// send email
const btnSubmit = document.getElementById("btnSubmit");
const email_field = document.getElementById("emailField");
if (btnSubmit)
btnSubmit.addEventListener("click", sendEmailSubscription);
// convert date
const dateFa = document.getElementsByClassName("dateFa");
if (dateFa.length) {
for (var i=0;i<dateFa.length;i++) {
const currentElement = dateFa[i];
currentElement.textContent = toLocalDate(currentElement.textContent , true);
}
}
فایل api.php
<?php
require_once "functions.php";
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
$action = @$_GET['action'];
$args = @file_get_contents("php://input");
$valid_actions = [
"insertEmailSubscriptionApi"
];
if(is_callable($action) && in_array($action , $valid_actions)){
$args_list = [];
if($args){
$args_list = json_decode($args , true);
}
die(call_user_func($action , $args_list));
}else{
die('{}');
}
?>
فایل functions.php
<?php
$GLOBALS['valid_stuffix_email_domain'] = [
"gmail.com",
"yahoo.com"
];
function startMysql()
{
$GLOBALS['mysqli'] = new mysqli("localhost", "root", "", "subscription");
if ($GLOBALS['mysqli']->connect_error) {
die("MYSQL ISSUE : " . $GLOBALS['mysqli']->connect_error);
}
$GLOBALS['mysqli']->set_charset("utf8");
$GLOBALS['stmt'] = $GLOBALS['mysqli']->stmt_init();
}
function endMysql()
{
$GLOBALS['stmt']->close();
$GLOBALS['mysqli']->close();
}
function insertRow($data, $table = "email")
{
startMysql();
$keys = array_keys($data);
$keysStr = join(",", $keys);
$values = array_values($data);
$valuesStrQuestion = str_repeat("? , ", count($values));
if (1 < count($values)) {
$valuesStrQuestion .= "?";
} else {
$valuesStrQuestion = str_replace(" , ", "", $valuesStrQuestion);
}
$query = "INSERT INTO `{$table}` ({$keysStr}) VALUES ({$valuesStrQuestion})";
$inserted_id = 0;
$GLOBALS['stmt']->prepare($query);
$GLOBALS['stmt']->bind_param(str_repeat("s", count($values)), ...$values);
if ($GLOBALS['stmt']->execute()) {
$inserted_id = $GLOBALS['stmt']->affected_rows ? $GLOBALS['stmt']->insert_id : 0;
}
endMysql();
return $inserted_id;
}
function selectRow($data = [], $concat_query = "1=1", $table = "email")
{
startMysql();
$query = "SELECT * FROM `{$table}` WHERE {$concat_query}";
$rows = [];
$GLOBALS['stmt']->prepare($query);
if ($data) {
$GLOBALS['stmt']->bind_param(str_repeat("s", count($data)), ...$data);
}
if ($GLOBALS['stmt']->execute() && $res = $GLOBALS['stmt']->get_result()) {
if ($GLOBALS['stmt']->affected_rows || $res->num_rows) {
while ($row = $res->fetch_assoc()) {
$rows[] = $row;
}
}
}
endMysql();
return $rows;
}
function insertEmailSubscriptionApi($list)
{
$res = [
"message" => "",
"success" => 0
];
$list['email'] = trim($list['email'] ?? "") ?? "";
if ($list['email'] && filter_var($list['email'], FILTER_VALIDATE_EMAIL)) {
$response = selectRow([$list['email']], "email=?");
$email_domain = explode("@", $list['email']);
$email_domain = count($email_domain) ? $email_domain[count($email_domain) - 1] : false;
if ($GLOBALS['valid_stuffix_email_domain'] && !in_array($email_domain, $GLOBALS['valid_stuffix_email_domain'])) {
$res["message"] = "ایمیل وارد شده عضو دامنه های معتبر نمی باشد";
} else if ($response) {
$res["message"] = "این ایمیل از قبل در سیستم ثبت شده است ایمیل دیگری را وارد کنید";
} else if (!$response) {
insertRow([
"email" => $list['email'],
]);
$res["message"] = "ایمیل تان با موفقیت در خبرنامه ثبت گردید";
$res["success"] = 1;
}
} else {
$res["message"] = "ایمیل وارد شده نامعتبر می باشد";
}
return json_encode($res);
}
در نظر داشته باشید که اگر میخواهید تمامی دامنه ها معتبر باشند میتوانید متغیر valid_stuffix_email_domain را خالی بگذارید خط 3 functions.php
فایل list.php
<?php
require_once "inc/functions.php";
require_once "parts/header.php";
$rows = selectRow();
?>
<a id="introduce" href="https://rapidcode.ir" target="_blank">رپید کد • کتابخانه مجازی برنامه نویسان</a>
<table class="table table-success">
<thead>
<tr>
<td>آیدی</td>
<td>ایمیل</td>
<td>تاریخ ایجاد</td>
</tr>
</thead>
<tbody>
<?php
foreach($rows as $row):
// created_at -> date and time
$created_d_date = explode(" " , $row['created_at']);
$created_d_time = $created_d_date[1];
$created_d_date = $created_d_date[0];
?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['email'] ?></td>
<td dir="ltr"><span class="dateFa"><?= $created_d_date ?></span> | <span class="time"><?= $created_d_time ?></span></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php require_once "parts/footer.php" ?>
قبل از استفاده از سورس فایل subscription.sql در پوشه import را وارد MySQL کنید .
ارسال نظر