Ejemplo n.º 1
0
/**
* Fonction vérrifiant que les données du formulaire sont correctement remplies et ajout des messages d'erreurs dans le formulaire en cas de problèmes
* @param [string, string] $a_valeur, tableau associatif contenant les données passées au travers du formulaire
* @return [bool] renvoie vrai si les données sont validées faux sinon.
*/
function validation_formulaire($a_valeur, &$info, $label)
{
    $retour = true;
    //Vérification du code anti-spam
    if (!isset($_SESSION['livreor']) || strcmp(strtoupper($_SESSION['livreor']), strtoupper($a_valeur['code'])) != 0) {
        $info["err_code"] = setRed($label["err_code"]);
        $retour = false;
    }
    //Vérification du mail
    if (!isset($a_valeur['email']) || !validateEmail($a_valeur['email'])) {
        $info["err_mail"] = setRed($label["err_mail"]);
        $retour = false;
    }
    //Vérification du nom
    if (!isset($a_valeur['nom']) || empty($a_valeur['nom'])) {
        $info["err_nom"] = setRed($label["err_nom"]);
        $retour = false;
    }
    //Vérification du sujet
    if (!isset($a_valeur['sujet']) || empty($a_valeur['sujet'])) {
        $info["err_sujet"] = setRed($label["err_sujet"]);
        $retour = false;
    }
    //Vérification du nom
    if (!isset($a_valeur['message']) || empty($a_valeur['message'])) {
        $info["err_message"] = setRed($label["err_message"]);
        $retour = false;
    }
    return $retour;
}
Ejemplo n.º 2
0
function sendEmail($name, $email, $message)
{
    $to = get_option('smcf_to_email');
    $subject = get_option('smcf_subject');
    // Filter name
    $name = filter($name);
    // Filter and validate email
    $email = filter($email);
    if (!validateEmail($email)) {
        $subject .= " - invalid email";
        $message .= "\n\nBad email: {$email}";
        $email = $to;
    }
    // Add additional info to the message
    if (get_option('smcf_ip')) {
        $message .= "\n\nIP: " . $_SERVER['REMOTE_ADDR'];
    }
    if (get_option('smcf_ua')) {
        $message .= "\n\nUSER AGENT: " . $_SERVER['HTTP_USER_AGENT'];
    }
    // Set and wordwrap message body
    $body = "From: {$name}\n\n";
    $body .= "Message: {$message}";
    $body = wordwrap($body, 70);
    // Build header
    $header = "From: {$email}\n";
    $header .= "X-Mailer: PHP/SimpleModalContactForm";
    // Send email - suppress errors
    @mail($to, $subject, $body, $header) or die('Unfortunately, your message could not be delivered.');
}
Ejemplo n.º 3
0
/**
* Functions for checking if user exists
*/
function checkingIfUserExists()
{
    include_once 'validate.php';
    include_once 'functions.php';
    if (isset($_POST['email']) && isset($_POST['password'])) {
        $email = cleanInput($_POST['email']);
        $password = cleanInput($_POST['password']);
    }
    if (empty($email) || empty($password)) {
        echo "All fields are required. Please fill in all the fields.";
        exit;
    } else {
        /*checking correctness of form input*/
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (validateEmail($email) == false) {
            echo "E-mail should be in the format of name@example.com";
            exit;
        }
        if (validateLength($password, 6) == false) {
            echo "Password should contain not less than 6 symbols";
            exit;
        }
        //$password_hash=password_hash($password, PASSWORD_DEFAULT); //PHP 5 >= 5.5.0
        $password_hash = md5($password);
        /*checking if user already exists*/
        if (checkLoggedUserInFile($email, $password_hash) == true) {
            //echo "Hello! You have logged in as ".$_SESSION['user_name'].".";
            header('Location:products.php');
            exit;
        } else {
            echo "No such user, or wrong password.<br>";
            //exit;
        }
    }
}
Ejemplo n.º 4
0
function validateData()
{
    $required = $_GET["required"];
    $type = $_GET["type"];
    $value = $_GET["value"];
    validateRequired($required, $value, $type);
    switch ($type) {
        case 'number':
            validateNumber($value);
            break;
        case 'alphanum':
            validateAlphanum($value);
            break;
        case 'alpha':
            validateAlpha($value);
            break;
        case 'date':
            validateDate($value);
            break;
        case 'email':
            validateEmail($value);
            break;
        case 'url':
            validateUrl($value);
        case 'all':
            validateAll($value);
            break;
    }
}
Ejemplo n.º 5
0
 public function create($args)
 {
     extract(extractable(array('email', 'name', 'password'), $args));
     if ($email && $password) {
         $email = strtolower(trim($email));
         if (validateEmail($email)) {
             $ut = DBTable::get('users');
             if (!($rows = $ut->loadRowsWhere(array('email' => $email)))) {
                 $new = $ut->loadNewRow();
                 $new->name = $name;
                 $new->email = $email;
                 $new->password = sha1($password);
                 $new->created = time();
                 $new->save();
                 if ($new->users_id) {
                     return data::success($new->export());
                 }
                 return data::error("Unknown error saving user. Please try again.");
             }
             return data::error("email is already registered");
         }
         return data::error("invalid email");
     }
     return data::error("email and password required");
 }
Ejemplo n.º 6
0
function sendEmail($name, $email, $message) {
	global $to, $subject, $extra;

	// Filter name
	$name = filter($name);

	// Filter and validate email
	$email = filter($email);
	if (!validateEmail($email)) {
		$subject .= " - invalid email";
		$message .= "\n\nBad email: $email";
		$email = $to;
	}

	// Add additional info to the message
	if ($extra['ip']) {
		$message .= "\n\nIP: " . $_SERVER['REMOTE_ADDR'];
	}
	if ($extra['user_agent']) {
		$message .= "\n\nUSER AGENT: " . $_SERVER['HTTP_USER_AGENT'];
	}

	// Set and wordwrap message body
	$body = "From: $name\n\n";
	$body .= "Message: $message";
	$body = wordwrap($body, 70);

	// Build header
	$header = "From: $email\n";
	$header .= "X-Mailer: PHP/SimpleModalContactForm";

	// Send email
	@mail($to, $subject, $body, $header) or 
		die('Unfortunately, your message could not be delivered.');
}
Ejemplo n.º 7
0
 function register($username, $password, $email, $type = 'g')
 {
     if (empty($username) || empty($password) || !validateEmail($email)) {
         return false;
     }
     $rt = uc_user_register($username . '#' . $type, $password, $email);
     if ($rt > 0) {
         return array('result' => $rt, 'message' => 'register success!!');
     }
     switch ($rt) {
         case -1:
             $return = array('result' => -1, 'message' => 'invalid username!!');
             break;
         case -2:
             $return = array('result' => -2, 'message' => 'illegal words has beed found!!');
             break;
         case -3:
             $return = array('result' => -3, 'message' => 'usename exist!!');
             break;
         case -4:
             $return = array('result' => -4, 'message' => 'invalid email address!!');
             break;
         case -5:
             $return = array('return' => -5, 'message' => 'email not allow!!');
             break;
         case -6:
             $return = array('return' => -6, 'message' => 'email has been used!!');
             break;
     }
     return $return;
 }
function ValidateRegisterForm($post)
{
    if (validateFirstName($post['firstName']) && validateLastName($post['lastName']) && validateEmail($post['email']) && validatePassword($post['password']) && validateConfirmPassword($post['confirmPassword']) && validateGender($post['gender']) && validateContactNumber($post['contactNumber']) && validateAddress($post['address'])) {
        return true;
    } else {
        return false;
    }
}
Ejemplo n.º 9
0
 private function emailIsValid($otheremail = '')
 {
     if (empty($otheremail)) {
         $email = $this->toEmail;
     } else {
         $email = $otheremail;
     }
     return validateEmail($email);
 }
Ejemplo n.º 10
0
function contact_validate($app, $deployment, $contactInfo)
{
    foreach ($contactInfo as $key => $value) {
        switch ($key) {
            case "use":
            case "host_notification_period":
            case "service_notification_period":
            case "host_notification_commands":
            case "service_notification_commands":
                validateForbiddenChars($app, $deployment, '/[^\\w.-]/s', $key, $value);
                break;
            case "retain_status_information":
            case "retain_nonstatus_information":
            case "host_notifications_enabled":
            case "service_notifications_enabled":
            case "can_submit_commands":
                validateBinary($app, $deployment, $key, $value);
                break;
            case "host_notification_options":
                $opts = validateOptions($app, $deployment, $key, $value, array('d', 'u', 'r', 's', 'n'), true);
                $contactInfo[$key] = $opts;
                break;
            case "service_notification_options":
                $opts = validateOptions($app, $deployment, $key, $value, array('w', 'u', 'c', 'r', 's', 'n'), true);
                $contactInfo[$key] = $opts;
                break;
            case "email":
                validateEmail($app, $deployment, $key, $value);
                break;
            case "pager":
                if (filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
                    if (!preg_match("/^(?[2-9][0-8][0-9])?-[2-9][0-0]{2}-[0-9]{4}\$/", $value)) {
                        $apiResponse = new APIViewData(1, $deployment, "Unable use pager number provided, the value provided doesn't match the regex for pager or email address");
                        $apiResponse->setExtraResponseData('parameter', $key);
                        $apiResponse->setExtraResponseData('parameter-value', $value);
                        $apiResponse->setExtraResponseData('parameter-pager-regex', "/^(?[2-9][0-8][0-9])?-[2-9][0-0]{2}-[0-9]{4}\$/");
                        $app->halt(404, $apiResponse->returnJson());
                    }
                }
                break;
            case "contactgroups":
                if (is_array($value)) {
                    $value = implode(',', $value);
                }
                validateForbiddenChars($app, $deployment, '/[^\\w.-]/s', $key, $value);
                break;
            default:
                break;
        }
    }
    return $contactInfo;
}
Ejemplo n.º 11
0
function validateFormInputs()
{
    if (validateName()) {
        if (validateEmail()) {
            if (validateMessage()) {
                if (validateHiddenInput()) {
                    return true;
                }
            }
        }
    }
    return false;
}
Ejemplo n.º 12
0
 function UserSignUp()
 {
     if (isset($_POST['su-btn-submit'])) {
         if (isset($_POST['email']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['confirm-password']) && isset($_POST['tos-checkbox'])) {
             //Get submitted values
             $email = validateEmail($_POST['email']) ? 1 : 0;
             $user = validateUsername($_POST['username']) ? 1 : 0;
             $password = validatePassword($_POST['password']) ? 1 : 0;
             $password_hash = password_hash($_POST['password'], PASSWORD_DEFAULT);
             $cf_pass = password_verify($_POST['confirm-password'], $password_hash) ? 1 : 0;
             $tos_cb = $_POST['tos-checkbox'] ? 1 : 0;
         }
     }
 }
Ejemplo n.º 13
0
function _wpr_newsletter_form_validate(&$info, &$errors, $whetherToValidateNameUniqueness = true)
{
    $errors = array();
    if (empty($_POST['name'])) {
        $errors[] = __("The newsletter name field was left empty. Please fill it in to continue.");
        $info['name'] = '';
    } else {
        if ($whetherToValidateNameUniqueness === true && checkIfNewsletterNameExists($_POST['name'])) {
            $errors[] = __("A newsletter with that name already exists. ");
            $info['name'] = '';
        } else {
            $info['name'] = $_POST['name'];
        }
    }
    if (empty($_POST['fromname'])) {
        $errors[] = __("The 'From Name' field was left empty. Please fill it in to continue. ");
        $info['fromname'] = '';
    } else {
        $info['fromname'] = $_POST['fromname'];
    }
    if (empty($_POST['fromemail'])) {
        $errors[] = __("The 'From Email' field was left empty. Please fill it in to continue. ");
        $info['fromemail'] = '';
    } else {
        if (!validateEmail($_POST['fromemail'])) {
            $errors[] = __("The email address provided for 'From Email' is not a valid e-mail address. Please enter a valid email address.");
            $info['fromemail'] = '';
        } else {
            $info['fromemail'] = $_POST['fromemail'];
        }
    }
    if (empty($_POST['reply_to'])) {
        $errors[] = _("The 'Reply-To' field was left empty. Please fill in an email address in the reply-to field.");
        $info['reply_to'] = '';
    } else {
        if (!validateEmail($_POST['reply_to'])) {
            $errors[] = _("The 'Reply-To' field was filled with an invalid e-mail address. Please fill in a valid email address.");
            $info['reply_to'] = '';
        } else {
            $info['reply_to'] = $_POST['reply_to'];
        }
    }
    $info['id'] = $_POST['id'];
    $info['description'] = $_POST['description'];
    $info['fromname'] = $_POST['fromname'];
    $info['fromemail'] = $_POST['fromemail'];
    $info = apply_filters("_wpr_newsletter_form_validation", $info);
    $errors = apply_filters("_wpr_newsletter_form_validation_errors", $errors);
}
Ejemplo n.º 14
0
function insertMailInput()
{
    if (isset($_POST['odeslat'])) {
        if (validateEmail()) {
            insertInputAddonWithValue("email", "email", "email", "*****@*****.**", 60, trim($_POST['email']));
            insertOKSpan();
        } else {
            insertInputWithAddon("email", "email", "email", "*****@*****.**", 60);
            insertWrongSpan();
        }
    } else {
        insertInputWithAddon("email", "email", "email", "*****@*****.**", 60);
        insertWrongSpan();
    }
}
Ejemplo n.º 15
0
function auth_client($email)
{
    if (is_client_logged()) {
        return true;
    }
    if (!validateEmail($email)) {
        return false;
    }
    $client = Client::findOneBy(array('email' => $email));
    if (!$client) {
        return false;
    }
    $_SESSION["frame"]["client"] = $client;
    return true;
}
Ejemplo n.º 16
0
 public function check($source, $items = array())
 {
     foreach ($items as $item => $rules) {
         foreach ($rules as $rule => $rule_value) {
             $value = trim($source[$item]);
             $item = escape($item);
             if ($rule === 'required' && empty($value)) {
                 $this->addError("{$item} is required");
             } else {
                 if (!empty($value)) {
                     switch ($rule) {
                         case 'min':
                             if (strlen($value) < $rule_value) {
                                 $this->addError("{$item} must be minimum of {$rule_value} characters.");
                             }
                             break;
                         case 'max':
                             if (strlen($value) > $rule_value) {
                                 $this->addError("{$item} must be maximum of {$rule_value} characters.");
                             }
                             break;
                         case 'matches':
                             if ($value != $source[$rule_value]) {
                                 $this->addError("{$rule_value} must match {$item}");
                             }
                             break;
                         case 'unique':
                             $result = $this->_db->query("SELECT id FROM user_info WHERE {$rule_value} = {$value}");
                             if ($result->num_rows) {
                                 $this->addError("{$item} : {$value} already exists");
                             }
                             break;
                         case 'email':
                             if (!validateEmail($value)) {
                                 $this->addError("{$item} is invalid");
                             }
                             break;
                     }
                 }
             }
         }
     }
     if (empty($this->_errors)) {
         $this->_passed = true;
     }
 }
Ejemplo n.º 17
0
function ValidateEmailExtra($email)
{
    $pattern = "/[^a-z0-9_@.]+/i";
    $email_to_validate = $email;
    if (!preg_match($pattern, $email_to_validate)) {
        if (!empty($email)) {
            if (validateEmail($email_to_validate)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}
Ejemplo n.º 18
0
function Registration($mail, $pass, $gender, $usertype)
{
    if (checkvaliduser($mail) == true) {
        if ($pass != '' && $mail != '') {
            if (validateEmail($mail)) {
                $insert_id = insertintousers($mail, $pass, $gender, $usertype);
                if (is_numeric($insert_id) && $insert_id > 0) {
                    header("location:login.php");
                }
            } else {
                echo "Please Enter Valide email.";
            }
        } else {
            echo "Please Enter Valide email and Password.";
        }
    } else {
        echo "This is not Valide Email.";
    }
}
Ejemplo n.º 19
0
/**
* Functions for checking & validating form
*/
function checkingFormAndSaveNewUser()
{
    include_once 'validate.php';
    if (isset($_POST['username']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['confirm_password']) && isset($_POST['agree'])) {
        $username = cleanInput($_POST['username']);
        $email = cleanInput($_POST['email']);
        $password = cleanInput($_POST['password']);
        $confirm_password = cleanInput($_POST['confirm_password']);
        $agree = $_POST['agree'];
        if (validateUsername($username) == false) {
            echo "Name should contain capitals and lower case, not less than 2 symbols";
            exit;
        }
        $email = filter_var($email, FILTER_SANITIZE_EMAIL);
        if (validateEmail($email) == false) {
            echo "E-mail should be in the format of name@example.com";
            exit;
        }
        if (validateLength($password, 6) == false) {
            echo "Password should contain not less than 6 symbols";
            exit;
        }
        if (validateConfirm($password, $confirm_password) == false) {
            echo "Passwords do not match";
            exit;
        }
        //$password_hash=password_hash($password, PASSWORD_DEFAULT); //PHP 5 >= 5.5.0
        $password_hash = md5($password);
        $dir_for_saved_users = "./user/";
        if (!is_dir($dir_for_saved_users)) {
            mkdir($dir_for_saved_users, 0777, true);
        }
        chmod('./user/', 0777);
        $filename = $dir_for_saved_users . "user_info";
        $new_user_info = $username . ":" . $email . ":" . $password_hash . "\n";
        file_put_contents($filename, $new_user_info, FILE_APPEND);
        //$_SESSION['name'] = $username;
        echo "You have signed up successfully! <a href='index.php'>Log in</a>";
    } else {
        echo "All fields are required. Please fill in all the fields.";
        exit;
    }
}
Ejemplo n.º 20
0
function validate($array)
{
    $isGood = false;
    foreach ($_POST as $key => $value) {
        $value = trim(strip_tags($value));
        $_POST[$key] = $value;
        $isGood = false;
        switch ($key) {
            case 'email':
                $isGood = validateEmail($value);
                break;
            default:
                $isGood = strlen($value) > 2;
        }
        if (!$isGood) {
            return false;
        }
    }
    return $isGood;
}
Ejemplo n.º 21
0
function check_rm_form(&$err)
{
    if (isset($_REQUEST["ok"])) {
        return true;
    }
    $err = "";
    if (!isset($_REQUEST["rm_user_login"]) || !strlen($_REQUEST["rm_user_login"])) {
        return false;
    }
    if (!isset($_REQUEST["rm_user_code"])) {
        return false;
    }
    $login = clearText($_REQUEST["rm_user_login"]);
    $code = clearText($_REQUEST["rm_user_code"]);
    if (!strlen($login)) {
        $err = "Укажите адрес электронной почты";
        return false;
    }
    if (!validateEmail($login)) {
        $err = "Укажите корректный адрес электронной почты";
        return false;
    }
    if (strlen($code) != 4 || $code != @$_SESSION["remind_scode"]) {
        $err = "Неверный код";
        return false;
    }
    $client = Client::findOneBy(array('email' => $login));
    if ($client) {
        $txt = "<p>Здравствуйте, " . $client["fio"] . "!</p>";
        $txt .= "Пароль для доступа к личному кабинету: <i>" . $client["password"] . "</i>";
        $txt .= "<p><i>С уважением, компания по написанию студенческих работ.</i></p>";
        $email = new Email();
        $email->setData(array('email' => $client["email"], 'name' => $client["fio"]), "Восстановление пароля", $txt, array(), true, array(), array('email' => Filials::getEmail($client["filial_id"]), 'name' => Filials::getName($client["filial_id"])));
        $email->send();
    }
    ob_end_clean();
    header("location: ?type=remind&ok");
    die;
}
Ejemplo n.º 22
0
function getDataErrors($data)
{
    $messages = [];
    if (empty($data['first_name']) || empty($data['last_name']) || empty($data['username']) || empty($data['password'])) {
        $messages[] = 'Παρακαλούμε συμπληρώστε όλα τα πεδία';
        return $messages;
    }
    if (!validateName($data['first_name'])) {
        $messages[] = 'Το όνομα σας περιέχει μη επιτρεπτούς χαρακτήρες. Παρακαλούμε εισάγετε μόνο γράμματα της αλφαβήτας';
    }
    if (!validateName($data['last_name'])) {
        $messages[] = 'Το επώνυμό σας περιέχει μη επιτρεπτούς χαρακτήρες. Παρακαλούμε εισάγετε μόνο γράμματα της αλφαβήτας';
    }
    if (!validateUsername($data['username'])) {
        $messages[] = 'Το username σας περιέχει μη πετρεπτούς χαρακτήρες. Παρακαλούμε εισάγετε μόνο λατινικούς χαρακτήρες και αριθμούς';
    }
    if (!validateEmail($data['email'])) {
        $messages[] = 'Το e-mail σας δεν είναι έγκυρο. Παρακούμε εισάγετε ένα έγκυρο e-mail.';
    }
    if (!validatePassword($data['password'])) {
        $messages[] = 'Μη επιτρεπτός κωδικός. Ο κωδικός σας πρέπει να περιλαμβάνει τουλάχιστον 8 ψηφία.';
    }
    return $messages;
}
Ejemplo n.º 23
0
function validate()
{
    if (!validateAlpha($_POST['fname'])) {
        echo '<script type="text/javascript">alert("Not a valid firstname!")</script>';
        return false;
    }
    if (!validateAlpha($_POST['lname'])) {
        echo '<script type="text/javascript">alert("Not a valid lastname!")</script>';
        return false;
    }
    if (!validateAlphaNumeric($_POST['address'])) {
        echo '<script type="text/javascript">alert("Not a valid address!")</script>';
        return false;
    }
    if (!validatePhone($_POST['phone'])) {
        echo '<script type="text/javascript">alert("Not a valid phone number, use ###-###-####!")</script>';
        return false;
    }
    if (!validateEmail($_POST['email'])) {
        echo '<script type="text/javascript">alert("Not a valid email!")</script>';
        return false;
    }
    return true;
}
Ejemplo n.º 24
0
$captcha=$_POST['captcha'];

//almaceno en un array los valores recogidos del formulario
$informacion = array($pass1, $pass2, $mail);

//Validacion de datos enviados
if ($pass1 == "" && $pass2 == "" && $mail == "" && $user == "" && $captcha == "") {
	echo "<p style='color:red; text-align:center;'>Debe llenar todos los campos.</p>";
}else{
	if(!validatePassword1($_POST['password1'])){		
		$password1 = "error";
	}
	if(!validatePassword2($_POST['password1'], $_POST['password2'])){
		$password2 = "error";
	}
	if(!validateEmail($_POST['email'])){
		$email = "error";
	}
	if(!validateusuario($_POST['usuario'])){
		$usuario = "error";
	}
	if(!validateCaptcha($_POST['captcha'])){
		$codCaptcha = "error";
		echo "<p style='color:red; text-align:center;'>No ha ingresado el codigo correcto</p>";
	}

	//Guardamos valores para que no tenga que reescribirlos	
	$emailValue = $_POST['email'];

		if($password1 != "error" && $password2 != "error" && $email != "error" && $usuario != "error" && $codCaptcha != "error"){
			$status = 1;
Ejemplo n.º 25
0
<?php

DEFINE('INCLUDE_CHECK', 1);
require_once 'lib/connections/db.php';
include 'lib/functions/functions.php';
checkLogin('2');
// we check if everything is filled in and perform checks
if ($_POST['phone'] && !validateNumeric($_POST['phone'])) {
    die(msg(0, "Phone numbers must be of numeric type only."));
}
if ($_POST['email'] && validateEmail($_POST['email'])) {
    die(msg(0, "Invalid Email!"));
}
if ($_POST['email'] && uniqueEmail($_POST['email'])) {
    die(msg(0, "Email already in database. Please select another email address."));
}
$res = editUser($_SESSION['user_id'], $_POST['email'], $_POST['first_name'], $_POST['last_name'], $_POST['dialing_code'], $_POST['phone'], $_POST['city'], $_POST['country']);
if ($res == 4) {
    die(msg(0, "An internal error has occured. Please contact the site admin!"));
}
if ($res == 99) {
    die(msg(1, "Profile updated successfully!"));
}
function msg($status, $txt)
{
    return '{"status":' . $status . ',"txt":"' . $txt . '"}';
}
Ejemplo n.º 26
0
<?php

$myTemplate = file_get_contents('template.html');
$output = '';
// validate post
if (isset($_POST['number']) && isset($_POST['email']) && isValidNumber($_POST['number']) && (isValidEmail($_POST['email']) || $_POST['email'] == 'Enter your email(optional)')) {
    $number = $_POST['number'];
    $email = validateEmail($_POST['email']);
    $conn = new mysqli('localhost', 'muhibind_2012', 'rzabul01', 'muhibind_01');
    $response = array();
    // get results
    $myArray = $conn->query("SELECT number FROM emails");
    // fetch associative array
    while ($row = $myArray->fetch_assoc()) {
        $response[] = $row[number];
    }
    if (in_array($number, $response)) {
        $output = str_replace('[+result+]', 'This number has been already used', $myTemplate);
    } else {
        $result = $conn->query("INSERT INTO emails (email, number) values ('{$email}', '{$number}')");
        if ($result) {
            $output = str_replace('[+result+]', 'Thanks for subscribing', $myTemplate);
        } else {
            $output = str_replace('[+result+]', 'Something went wrong with the connection, please go back and try again', $myTemplate);
        }
    }
} else {
    $output = str_replace('[+result+]', 'Something went wrong, please go back and try again', $myTemplate);
}
echo $output;
function isValidNumber($numberIn)
    $userName     = (isset($_POST['username']))   ? $_POST['username']   : '';
    $firstName    = (isset($_POST['first_name'])) ? $_POST['first_name'] : '';
    $lastName     = (isset($_POST['first_name'])) ? $_POST['last_name']  : '';
    $emailAddress = (isset($_POST['email']))      ? $_POST['email']      : '';
            
    //
    $userMessage  = '';
    $firstMessage = '';
    $lastMessage  = '';
    $emailMessage = '';

    //
    validateUserName($userName,  $userMessage);
    validateFirstName($firstName,$firstMessage);
    validateLastName($lastName,  $lastMessage);
    validateEmail($emailAddress, $emailMessage);

    echo $userMessage  . '<br />';
    echo $firstMessage . '<br />';
    echo $lastMessage  . '<br />';
    echo $emailMessage . '<br />';
}

//  • username: alphanumeric and no longer than 15 characters long
function validateUserName($name, &$message) {
    $message   = '';
    $validData = ctype_alnum($name) && (strlen($name) <= 15);
    if ($validData) {
        $message = "$name is valid user name";
    } else {
        $message = "$name is a bogus user name";
Ejemplo n.º 28
0
function saveUserData($username,$fields) {
	# saves data in session, not in database
  dbg("Saving user $username");
	if (!is_array($_SESSION["userdata"])) {
  	dbg("Nothing to save");
    return;
  }
  if (!$username) {
  	$username = '******';
  }
	$res = "";
  $required_fields = explode(",",$_POST["required"]);
  $required_formats = explode(",",$_POST["required_formats"]);
  $description_fields = explode(",",$_POST["required_description"]);

  reset($fields);
  dbg("Checking fields");
  while (list($fname,$fval) = each ($fields)) {
 # 	dbg($fname);
  	$key = $fname;
    $val = $_POST[$fname];
		if (!ereg("required",$key) &&
    	$fields[$key]["type"] != "separator" &&
    	$fields[$key]["type"] != "emailcheck" &&
    	$fields[$key]["type"] != "passwordcheck"
      ) {
	#  	dbg($fname ." of type ".$fields[$key]["type"]);
       if (!is_array($_SESSION["userdata"][$key]))
       	 $_SESSION["userdata"][$key] = array();
       $_SESSION["userdata"][$key]["name"] = $fields[$key]["name"];
       $_SESSION["userdata"][$key]["type"] = $fields[$key]["type"];
       if ($fields[$key]["type"] == "creditcardno") {
       	 # dont overwrite known CC with ***
         if (!preg_match("#^\*+#",$val)) {
		     	 $_SESSION["userdata"][$key]["value"] = ltrim($val);
         }
       } else {
	     	 $_SESSION["userdata"][$key]["value"] = ltrim($val);
       }
       if ($fields[$key]["type"] == "select") {
	     	 $_SESSION["userdata"][$key]["displayvalue"] = $fields[$key]["values"][$val];
       } elseif ($fields[$key]["type"] == "checkboxgroup") {
	     	 $_SESSION["userdata"][$key]["value"] = join(",",$val);
       } elseif ($fields[$key]["type"] == "creditcardno") {
       		# erase any non digits from the CC numbers
					$_SESSION["userdata"][$key]["value"] = preg_replace("/\D/","",$_SESSION["userdata"][$key]["value"]);
					$_SESSION["userdata"][$key]["displayvalue"] = obscureCreditCard($_SESSION["userdata"][$key]["value"]);
       } elseif ($fields[$key]["name"] == "Card Number") {
					$_SESSION["userdata"][$key]["value"] = preg_replace("/\D/","",$_SESSION["userdata"][$key]["value"]);
					$_SESSION["userdata"][$key]["displayvalue"] = obscureCreditCard($_SESSION["userdata"][$key]["value"]);
/*					$_SESSION["userdata"][$key]["displayvalue"] = substr($_SESSION["userdata"][$key]["displayvalue"],0,4);
       		for ($i=0;$i<strlen($_SESSION["userdata"][$key]["value"]-4);$i++) {
		     	  $_SESSION["userdata"][$key]["displayvalue"] .= '*';
         	}
*/
		   } else {
	     	 $_SESSION["userdata"][$key]["displayvalue"] = $val;
		   }
       
/*       # remember other aspects of the fields
       foreach ($fields as $key => $val) {
         foreach ($val as $field_attr => $value) {
	       	 if (!isset($_SESSION["userdata"][$key][$field_attr]) && !preg_match("/^\d+$/",$key)
           	&& !preg_match("/^\d+$/",$field_attr)
           ) {
						 $_SESSION["userdata"][$key][$field_attr] = $value;
           }
          }
       }
*/
       # save it to the DB as well
    } else {
#  	  	dbg("Not checking ".$fname ." of type ".$fields[$key]["type"]);
		}
  }
  
  # fix UK postcodes to correct format
  if ($_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"] == "United Kingdom") {
    $postcode = $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"];
    $postcode = strtoupper(str_replace(" ","",$postcode));
    if (preg_match("/(.*)(\d\w\w)$/",$postcode,$regs)) {
      $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["value"] = trim($regs[1])." ".$regs[2];
      $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["displayvalue"] = trim($regs[1])." ".$regs[2];
    }
  }

  while (list($index,$field) = each ($required_fields)) {
 		$type = $fields[$field]["type"];
    if ($field && !$_SESSION["userdata"][$field]["value"]) {
      $res = "Information missing: ".$description_fields[$index];
      break;
    } else if ($required_formats[$index] && !preg_match(stripslashes($required_formats[$index]),$_SESSION["userdata"][$field]["value"])) {
      $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
      break;
    } else if ($field == "email" && !validateEmail($_SESSION["userdata"][$field]["value"])) {
      $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
      break;
    } else if ($field == "cardtype" && $_SESSION["userdata"][$field]["value"] == "WSWITCH" && !preg_match("/\d/",$_SESSION["userdata"]["attribute82"]["value"])) {
      $res = "Sorry, a Switch Card requires a valid issue number. If you have a new Switch card without an issue number, please use 0 as the issue number.";
      break;
    } else if ($field == "cardtype" && $_SESSION["userdata"][$field]["value"] != "WSWITCH" && $_SESSION["userdata"]["attribute82"]["value"]) {
      $res = "Sorry, an issue number is not valid when not using a Switch Card";
      break;
    } else if (($type == "creditcardno" || $field == "cardnumber") && !checkCCrange($_SESSION["userdata"][$field]["value"])) {
    	list($cid,$cname) = ccCompany($_SESSION["userdata"][$field]["value"]);
      if (!$cname)
      	$cname = '(Unknown Credit card)';
      $res = "Sorry, we currently don't accept $cname cards";
      break;
    } else if (($type == "creditcardno" || $field == "cardnumber") && !validateCC($_SESSION["userdata"][$field]["value"])) {
      $res = "Sorry, you entered an invalid ".$description_fields[$index];#.": ".$_SESSION["userdata"][$field]["value"];
      break;
    } else if (($type == "creditcardexpiry" ||$field == "cardexpiry") && !validateCCExpiry($_SESSION["userdata"][$field]["value"])) {
      $res = "Sorry, you entered an invalid ".$description_fields[$index].": ".$_SESSION["userdata"][$field]["value"];
      break;
    }
  }
	if ($_SESSION["userdata"][$GLOBALS["config"]["country_attribute"]]["displayvalue"] == "United Kingdom") {
    $postcode = $_SESSION["userdata"][$GLOBALS["config"]["postcode_attribute"]]["displayvalue"];
    if (!preg_match("/(.*)(\d\w\w)$/",$postcode,$regs)) {
      $res = "That does not seem to be a valid UK postcode";
    } elseif (!preg_match("/^[\s\w\d]+$/",$postcode,$regs)) {
      $res = "That does not seem to be a valid UK postcode";
    }
  }
  if (is_array($GLOBALS["config"]["bocs_dpa"])) {
    if (!is_array($_SESSION["DPA"]))
      $_SESSION["DPA"] = array();
  	foreach ($GLOBALS["config"]["bocs_dpa"] as $dpaatt => $val) {
    	if ($_SESSION["userdata"][$dpaatt]["displayvalue"]) {
      	$_SESSION["DPA"][$val] = "Y";
     	} else {
      	$_SESSION["DPA"][$val] = "N";
      }
   	}
  }
  return $res;
}
Ejemplo n.º 29
0
<?php

include "validate.php";
$formSend = count($_POST) > 0;
$username = "";
$email = "";
if ($formSend) {
    $usernameValid = validateUsername($_POST["username"]);
    $emailValid = validateEmail($_POST["email"]);
    $passwordValid = validatePassword($_POST["password"]);
    $passwordCValid = validateCPassword($_POST["password"], $_POST["passwordC"]);
    $username = htmlspecialchars($_POST["username"]);
    $email = htmlspecialchars($_POST["email"]);
    if ($usernameValid == "" && $emailValid == "" && $passwordValid == "" && $passwordCValid == "") {
        header('Location: welcome.php?username='******'text/css' rel='stylesheet' href='style.css'/>
  <script src="jquery-2.1.4.min.js"></script>
  <script src="jquery.validate.js"></script>
  <script type="text/javascript" src="registration.js"></script>
  <script type="text/javascript" src="script.js"></script>
</head>
<body>
  <header>
Ejemplo n.º 30
0
// Enter the subject here.
$error_message = 'Error sending your message';
// Message displayed if an error occurs
$success_message = 'Message Sent';
// Message displayed id the email has been sent successfully
/* ==============================================
Do not modify anything below
============================================== */
$message = "Name: {$frm_name}\r\nEmail: {$frm_email}\r\nMessage: {$frm_message}";
$headers = "From: {$frm_name} <{$frm_email}>" . "\r\n" . "Reply-To: {$frm_email}" . "\r\n" . "X-Mailer: PHP/" . phpversion();
function validateEmail($email)
{
    if (preg_match("/^[_\\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\\.)+[a-zA-Z]{2,6}\$/i", $email)) {
        return true;
    } else {
        return false;
    }
}
if (strlen($frm_name) < 1 || strlen($frm_email) < 1 || strlen($frm_message) < 1) {
    echo $error_message;
} else {
    if (validateEmail($frm_email) == FALSE) {
        echo "could not validate email address";
    } else {
        if (mail($mailto, $subject, $message, $headers)) {
            echo $success_message;
        } else {
            echo $error_message;
        }
    }
}