Skip to content

Instantly share code, notes, and snippets.

@sv3tli0
Created February 23, 2015 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sv3tli0/130876213b139ca33508 to your computer and use it in GitHub Desktop.
Save sv3tli0/130876213b139ca33508 to your computer and use it in GitHub Desktop.
PHP subscribe - simple subscribe functionality responding in json format
<?php
$email = (string) filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var( $email, FILTER_VALIDATE_EMAIL);
$name = (string) filter_input( INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
if( $email) {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=database', 'username', 'password');
$stm = $pdo->prepare("SELECT COUNT(*) FROM `subscribes` WHERE `email` = ? ;");
$stm->execute([$email]);
if( ! $stm->fetchColumn() && $ip_address = getClientIp()){
$stm = $pdo->prepare("INSERT INTO `subscribes` (`email`,`name`,`ip_address`) VALUES (?, ?, ?);");
$stm->execute([$email, $name, $ip_address]);
if( $stm->rowCount()) {
$return = ['status'=>'success', 'msg'=>'You are now subscribed'];
} else {
$return = ['status'=>'error', 'msg'=>'We were unable to subscribe you'];
}
} else {
$return = ['status'=>'error', 'msg'=>'You are already subscribed'];
}
} else {
$return = ['status'=>'error', 'msg'=>'Missing/Invalid e-mail address'];
}
function getClientIp( $proxy = FALSE) {
if( $proxy) {
if ( !empty($_SERVER['HTTP_CLIENT_IP']))
return $_SERVER['HTTP_CLIENT_IP'];
if ( !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
return $_SERVER['HTTP_X_FORWARDED_FOR'];
return FALSE;
}
return !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : FALSE;
}
header('Content-Type: application/json');
echo json_encode($return);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment