Created
February 23, 2015 21:32
-
-
Save sv3tli0/130876213b139ca33508 to your computer and use it in GitHub Desktop.
PHP subscribe - simple subscribe functionality responding in json format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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