Validate Dynamically Form Data - php

I have a form field in my site that I need to know if the email that the user want to use isn't already used by other user.
I am using JavaScript and PHP for that but can make it work.
function validateEmail(){
//testing regular expression
var a = $("#email").val();
var filter = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}$/;
//if it's valid email
if(filter.test(a)){
if($("#email").val() != ""){
$.getScript("http://localhost/sisdelivery/validaEmail.php?&email="+$("#email").val(), function(){
if(resultadoEmail["email"] != ""){
email.addClass("error");
emailInfo.text("Email ja cadastrado!");
emailInfo.addClass("error");
return false;
}
else{
email.removeClass("error");
emailInfo.text("Email OK");
emailInfo.removeClass("error");
return true;
}
}
}
}
//if it's NOT valid
else{
var valEmail = $("#email").val();
if(valEmail == ""){
email.addClass("error");
emailInfo.text("Favor digitar um email!");
emailInfo.addClass("error");
return false;
}
else{
email.addClass("error");
emailInfo.text("O email digitado e invalido");
emailInfo.addClass("error");
return false;
}
}
}
The PHP code that looks on the database for the data:
<?php
include "conecta.php";
$email = $_GET['email'];
$consulta = "SELECT * FROM usuarios WHERE email = '$email';";
$result = mysql_query($consulta);
$num = mysql_num_rows($result);
if($num == 0)
echo "var resultadoEmail = { 'email' : '' }";
else{
while($row = mysql_fetch_object($result)){
$email = $row -> email;
}
echo "var resultadoEmail = { 'email' : '$email' }";
}
?>
I'm getting the error Uncaught SyntaxError: Unexpected token } but can't find where is the problem.

First of all, I just want to tell you that you have a security risk in your code. This line :
$email = $_GET['email'];
$consulta = "SELECT * FROM usuarios WHERE email = '$email';";
allow a person to run sql against your database and retrieve data. This is know as sql injection. You should validate your email before doing your query at minimum.

use this
return true;
}
});
^^^ // you forgot this

Related

Validation for registration page in PHP

I have a registration page and I want to validate it. I have this code:
$msg = "";
$msg_3 = "";
if(isset($_POST['submit'])) {
$First_Name = ((isset($_POST['First_Name']))?sanitize($_POST['First_Name']):'');
$Last_Name = ((isset($_POST['Last_Name']))?sanitize($_POST['Last_Name']):'');
$email = ((isset($_POST['email']))?sanitize($_POST['email']):'');
$confirm_email = ((isset($_POST['confirm_email']))?sanitize($_POST['confirm_email']):'');
$mobile_number = ((isset($_POST['mobile_number']))?sanitize($_POST['mobile_number']):'');
$password = ((isset($_POST['password']))?sanitize($_POST['password']):'');
$confirm_password = ((isset($_POST['confirm_password']))?sanitize($_POST['confirm_password']):'');
$gender = ((isset($_POST['gender']))?sanitize($_POST['gender']):'');
$day = ((isset($_POST['day']))?sanitize($_POST['day']):'');
$month = ((isset($_POST['month']))?sanitize($_POST['month']):'');
$year = ((isset($_POST['year']))?sanitize($_POST['year']):'');
$insurance = ((isset($_POST['insurance']))?sanitize($_POST['insurance']):'');
$agree = ((isset($_POST['agree']))?sanitize($_POST['agree']):'');
$sql = "SELECT email, mobile_number FROM customers WHERE email ='$email' OR mobile_number ='$mobile_number'";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($email == $row['email']) {
$msg = "<span class='text-danger'>The email address you've entered is already associated with another account.
<br>Please sign in or enter a different email address. Please try again.</span>";
} if ($mobile_number == $row['mobile_number']) {
$msg_3 = "<span class='text-danger'>The mobile phone number you've entered is already associated with another account.
<br>Please sign in or enter a different number. Please try <br>again.</span>";
}
}
} else {
// Insert into database and send email
}
Now how could I validate each field if it is empty and print different messages under each field in this nested if and while. I'm getting confused.
If you will use same names in db as in form you could use something like this:
$keys = ['gender', 'email', 'mobile_number']; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($key) {
if (empty($row[$key])) {
$errors[] = "$key is required"
}
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[] = "please enter $key"
}
})
}
if you need to have more customized messages you might map keys to error text like:
$keys = ['gender' => ['equal' => 'your error message', 'empty' => 'empty msg'], 'email' => ['equal' => 'email validation error', 'empty' => 'error msg 2']]; //etc
$errors = [];
while ($row = $result->fetch_assoc()) {
array_walk($keys, function ($errorMsg, $key) {
if (isset($_POST[$key]) && $_POST[$key] == $row[$key]) {
$errors[$key] = $errorMsg['equal'];
}
if (empty($row[$key])) {
$errors[$key] = $errorMsq['empty'];
}
})
}
Do not repeat
Prevent SQL Injection
You can do something like this.
<?php
if(isset($_POST['submit'])) {
$errors = [];
function getPost($postIndex, $errorMessage = '') {
global $errors;
if (!empty( $_POST[$postIndex] )) {
$value = $_POST[$postIndex];
return $value;;
} else {
$errors[$postIndex] = $errorMessage;
return null;
}
}
function validateString($s) {
return htmlspecialchars(trim($s));
}
getPost('First_Name', 'Firstname Cannot Be Empty');
getPost('Last_Name', 'Lastname cannot be empty');
$email = getPost('email', 'Your Error Message');
getPost('confirm_email', 'Your Error Message');
$mobile_number = getPost('mobile_number', 'Your Error Message');
getPost('password', 'Your Error Message');
getPost('confirm_password', 'Your Error Message');
getPost('gender', 'Your Error Message');
getPost('day', 'Your Error Message');
getPost('month', 'Your Error Message');
getPost('year', 'Your Error Message');
getPost('insurance', 'Your Error Message');
getPost('agree', 'Your Error Message');
$stmt = $mysqli -> prepare('SELECT email, mobile_number FROM customers WHERE email =? OR mobile_number =?');
if (
$stmt &&
$stmt -> bind_param('ss', $email, $mobile_number) &&
$stmt -> execute() &&
$stmt -> store_result() &&
$stmt -> bind_result($dbEmail, $dbMobileNumber) &&
$stmt -> fetch()
) {
if ($email == $dbEmail) {
// email equal error message
} if ($mobile_number == $row['mobile_number']) {
// mobile number equal error message
}
}
if (count($errors)) {
echo "You have an error";
}
// or get the post index in your HTML form and show the error message there
// <?php isset($errors['firstName']) ? echo $errors['firstname'] : null;
}

How to verify any email with php

I am working with a form. Where user enters their email, I can validate the email through regex. But what I need is like this. After searching, I found a solution here. The as it checks the MX record of the email. But still it does not work for me fine, because when I gave a rough email like : ahhhhhhhhhhhhhhhhh#yahoo.com my form accepted it, and when I gave the same email on the other website, it rejected the email. It might be the problem with my logic I don't know, below is my code where I am verifying the email.
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL)) {
echo "email_prb";
} else{
$sl = "SELECT * FROM fb_data WHERE useremail = '$_email' OR fbappid = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO fb_data VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
Kindly Use mysqli or Pdo.. your code is vulnerable to sql injection, try to add mysql escape. but i have rewritten your PHP below without changing query.
Filter validate email will check for the correct email format, so you dont need checking for #. but if you filter the #example.com you need a custom filter for that.
<?php
if(isset($_GET["saveData"])){
$_appid = $_GET["appid"];
$_name = $_GET["name"];
$_email = $_GET["email"];
$_pass = $_GET["pass"];
$_applink = $_GET["applink"];
function domain_exists($email, $record = 'MX'){
list($user, $domain) = explode('#', $email);
return checkdnsrr($domain, $record);
}
if(!empty($_appid) && !empty($_name) && !empty($_email) && !empty($_pass) && !empty($_applink)){
if((!domain_exists($_email)) && (!filter_var($_email, FILTER_VALIDATE_EMAIL))) {
echo "email_prb";
} else{
$sl = "SELECT * FROM `fb_data` WHERE `useremail` = '$_email' OR `fbappid` = '$_appid' ";
$count = $con->query($sl);
if(mysqli_num_rows($count)>0){
echo "exists";
}else{
$in = "INSERT INTO `fb_data` VALUES(NULL,'$_name','$_email','$_pass','$_applink','$_appid',1,0)";
if ($con->query($in)) {
echo "Inserted";
}
}
}
} else{
echo "empty";
}
}
?>
on this part of your code
if(!domain_exists($_email) OR !filter_var($_email, FILTER_VALIDATE_EMAIL))
change the "OR" to ||. Like this
if(!domain_exists($_email) || !filter_var($_email, FILTER_VALIDATE_EMAIL))

PHP Script that checks if email exists in table [duplicate]

This question already has answers here:
How to check if a row exists in MySQL? (i.e. check if username or email exists in MySQL)
(4 answers)
Closed 7 years ago.
I'm making a PHP Newsletter script, I'm not very experienced in code, but I try my best to improve, I just need a few ideas in order to make this work.
function validate(){
if(isset($_POST['email'])){
$email = $_POST["email"];
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<br>Va rugam introduceti o adresa valida de email";
}else{
return 1;
}
}
}
function checkmail(){
if(validate()==1){
if(isset($_POST['email'])){
$email = $_POST['email'];
$sql = "SELECT * FROM subscribe WHERE email LIKE '$email'";
$connect = new mysqli("localhost", "root", "", "alexandru");
$result = mysqli_query($connect,$sql);
echo print_r($result);
}
}
}
I don't know how I can check the result of the query, I need some ideas, thanks
I have made this simple function which you can use.
function field_exists($field_name, $field_value, $table)
{
global $conn;
try
{
$s = $conn->prepare("SELECT * from $table where $field_name = :f_value");
$s->bindParam(':f_value', $field_value);
$s->execute();
if($s->rowCount() > 0)
{
return true;
}
else
{
return false;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}//function
Using this function, you can check any table for any value of the specified column.
So in your case, the $field_name would be email, $field_value would be $email and table would be subscribers.
Usage
if(field_exists("email", $email, "subscribers"))
{
//email exists
}
else
{
//email doesn't exist
}
The function would return true if this email in the table exists, and false if the email doesn't.
This code i use whithout oops concept in my practicle ithink it'll help
extract($_POST);
$qwe = "SELECT * FROM user_info where email= '$email'";
$result = mysqli_query($con, $qwe);
if (mysqli_fetch_row($result) >= 1) {
header("Location: userreg.php?err=msg");
}
else {
// query for what u want after check mail doesn't exist
}

Cant insert Data into my Mysql Database?

I need a help from this error i cant insert data into my database, can you see my codes, im newly in php so please help me for this. thank you for your helping and giving a good answer,
it always saying "an error eccurred while sending" it is based on my else condition
<?php
if(isset($_SESSION['username']))
{
$form = true;
$orfvp_destination = '';
$oreq_approver= '';
$oreq_noter = '';
$orfvp_duration = '';
$orfvp_purpose = '';
//to check if the form has been sent
if(isset($_POST['rfvp_destination'], $_POST['req_approver'], $_POST['req_noter'], $_POST['rfvp_duration'], $_POST['rfvp_purpose']))
{
$orfvp_destination = $_POST['rfvp_destination'];
$oreq_approver = $_POST['req_approver'];
$oreq_noter = $_POST['req_noter'];
$orfvp_duration = $_POST['rfvp_duration'];
$orfvp_purpose = $_POST['rfvp_purpose'];
//to remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$orfvp_destination = stripslashes($orfvp_destination);
$oreq_approver = stripslashes($oreq_approver);
$oreq_noter = stripslashes($oreq_noter);
$orfvp_duration = stripslashes($orfvp_duration);
$orfvp_purpose = stripslashes($orfvp_purpose);
}
//to check if all the fields are filled
if($_POST['rfvp_destination']!='' and $_POST['req_approver']!='' and $_POST['req_noter']!='' and $_POST['rfvp_duration']!='' and $_POST['rfvp_purpose']!='')
{
//to protect the variables
$rfvp_destination = mysql_real_escape_string($orfvp_destination);
$req_approver = mysql_real_escape_string($oreq_approver);
$req_noter = mysql_real_escape_string($oreq_noter);
$rfvp_duration = mysql_real_escape_string(nl2br(htmlentities($orfvp_duration, ENT_QUOTES, 'UTF-8')));
$rfvp_purpose = mysql_real_escape_string($orfvp_purpose);
//to check if the recipient exists
$dn1 = mysql_fetch_array(mysql_query('select count(user_id) as req_approver, user_id as req_approverid, (select count(*) from request) as npm from users where user_username="'.$req_approver.'"'));
$dn2 = mysql_fetch_array(mysql_query('select count(user_id) as req_noter, user_id as req_noterid, (select count(*) from request) as npm from users where user_username="'.$req_noter.'"'));
if($dn1['req_approver'] and $dn2['req_noter']==1)
{
//to check if the recipient is not the actual user
if($dn1['req_approverid']!=$_SESSION['userid'] and $dn2['req_noter']!=$_SESSION['userid'])
{
$id = $dn1['npm']+1 and $dn2['npm']+1;
//We send the message
if(mysql_query('insert into rfv (rfv_id, rfv_code, rfv_driver, rfv_vehicle)values("'.$id.'", "RFV2015-'.$id.'", "", "")')
and mysql_query('insert into rfv-p (rfv_code, rfvp_destination, rfvp_purpose, rfvp_duration)values("RFV2015-'.$id.'", "rfvp_destination", "rfvp_purpose", "rfvp_duration")')
and mysql_query('insert into request (req_code, req_date, req_status, req_dateneeded, req_requestor, req_approver, req_noter, form_id)values( "RFV2015-'.$id.'", NOW(), "Waiting for Approval", "'.$_POST['req_dateneeded'].'", "'.$_SESSION['userid'].'", "'.$dn1['req_approverid'].'","'.$dn2['req_noterid'].'", 2)'))
{
?>
<p style="color:red" align="center" >Request Successfully Created!</p>
<p style="color:red" align="center" >Home</p>
<?php
$form = false;
}
else
{
//Otherwise, we say that an error occured
$error = 'An error occurred while sending the message';
}
}
else
{
//Otherwise, we say the user cannot send a message to himself
$error = 'You cannot send a message to yourself.';
}
}
else
{
//Otherwise, we say the recipient does not exists
$error = 'The recipient does not exists.';
}
}
else
{
//Otherwise, we say a field is empty
$error = 'A field is empty. Please fill of the fields.';
}
}
elseif(isset($_GET['req_approver'], $_GET['req_noter']))
{
//We get the username for the recipient if available
$oreq_approver = $_GET['req_approver'];
$oreq_noter = $_GET['req_noter'];
}
if($form)
{
//We display a message if necessary
if(isset($error))
{
echo '<div class="message" align="center" style="color:red">'.$error.'</div>';
}
//We display the form
?>
In the above script 2 if are not closed. First one is if(isset($_SESSION['username'])) and second one is if($form). Close the curly bracket } at correct place and that should work as expected.

Codeigniter - Update email only if the email doesn't exist in the database

I have an update page for my users where they can edit their name, email and other info.
So far, they can edit everything. Including their email. They can enter an email that already exists in the database without any issue.
I have tried adding this form validation rule
$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|is_unique[users.email]');
But that doesn't help because it will ask the user to enter another email if they click the save button, even if they don't want to change their email.
I just want to make it so that when they click the save button, only update the email if the user has changed it AND check that the email doesn't exist in the database before saving.
I have tried doing this but no luck.
The code that I'm playing with:
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$uid = $this->session->userdata('uid');
//$query = $this->db->get('dayone_entries');
$query = $this->db->query('SELECT uid, email FROM users');
$sql = "UPDATE users SET first_name = '{$first_name}', last_name = '{$last_name}', email = '{$email}' WHERE uid = $uid LIMIT 1";
$this->db->query($sql);
if ($this->db->affected_rows() === 1) {
return true;
} else {
return false;
}
You can try the following code :
$this->form_validation->set_rules('email', 'lang:email', 'trim|required|valid_email|callback__is_unique_email[email]');
and the callback function should look like this :
public function _is_unique_email($value, $field){
$result = $this->db->where('uid !=', $this->session->userdata('uid'))
->where($field, $value)
->get('users')
->row_array();
if ($result) {
$this->form_validation->set_message('_is_unique_email', $this->lang->line('_is_unique_'));
return false;
}
return true;
}
Your Javascript file:
$("#form_id").validate({
rules: {
email: {
required: true,
email: true,
remote: {
type: "post",
url: "pathtocontroller/controller.php/checkEmail",
}
}
},
messages: {
email: {
required: "Please enter Email!",
email: "Please enter valid Email!",
remote: "Email already not available!"
}
}
Your Controller File:
function checkEmail() {
$userArr = $this->input->post();
$id = $this->session->userdata('id');//if you have stored id within session else pass it within remote function
if (isset($userArr["email"])) {
if ($id != '') {
$ext_cond = "id !='" . $id . "'";
}
echo $this->your_model_name->getUserValidation('your_email_field_name', $userArr['email'], $ext_cond);
exit;
}
exit;
}
Your Model:
public function getUserValidation($usertype = '', $value = '', $cond = '') {
if ($usertype != '' && $value != '') {
$this->db->select($usertype);
$this->db->from($this->main_table);
if ($cond != '') {
$this->db->where($cond);
}
if (is_array($usertype)) {
foreach ($usertype as $key => $type_value) {
$this->db->where($type_value, $value[$key]);
}
} else {
$this->db->where($usertype, $value);
}
$user_data = $this->db->get()->result_array();
// echo $this->db->last_query();exit;
if (is_array($user_data) && count($user_data) > 0) {
return "false";
} else {
return "true";
}
} else {
return "false";
}
}
use validate library : http://docs.jquery.com/Plugins/Validation/Methods/remote
your javascript :
$("#yourFormId").validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "checkmail.php",
type: "post"
}
}
},
messages: {
email: {
required: "Please Enter Email!",
email: "This is not a valid email!",
remote: "Email already in use!"
}
}
});
checkmail.php:
<?php
$registeredEmails = array('test1#test.com', 'test2#test.com', 'test3#test.com');
$requestedEmail = $_POST['email'];
if( in_array($requestedEmail, $registeredEmails) ){
echo 'false';
}
else{
echo 'true';
}
?>
if you use codeigniter means use checkmail.php as a controller function..
you can pass your $registeredEmails array values as $registeredEmails[] = "your query result which is in for loop".

Categories