My PHP username validation with Ajax duplicates my html page inside of html div(this is for showing ajax error) element. I tried some solutions and google it bu can't find anything else for solution. Maybe the problem is about the $_POST but I also separated them in php (all the inputs validation).
Here is PHP code
<?php
if(isset($_POST['username'])){
//username validation
$username = $_POST['username'];
if (! $user->isValidUsername($username)){
$infoun[] = 'Your username has at least 6 alphanumeric characters';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['username'])){
$errorun[] = 'This username is already in use';
}
}
}
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn[] = 'Your name must be alphabetical characters';
}
}
if(isset($_POST['password'])){
if (strlen($_POST['password']) < 6){
$warningpw[] = 'Your password must be at least 6 characters long';
}
}
if(isset($_POST['email'])){
//email validation
$email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
if (! filter_var($email, FILTER_VALIDATE_EMAIL)){
$warningm[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if (! empty($row['email'])){
$errorm[] = 'This email is already in use';
}
}
}
?>
Here is Javascript
<script type="text/javascript">
$(document).ready(function(){
$("#username").keyup(function(event){
event.preventDefault();
var username = $(this).val().trim();
if(username.length >= 3){
$.ajax({
url: 'register.php',
type: 'post',
data: {username:username},
success: function(response){
// Show response
$("#uname_response").html(response);
}
});
}else{
$("#uname_response").html("");
}
});
});
</script>
<input type="text" name="username" id="username" class="form-control form-control-user" placeholder="Kullanıcı Adınız" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="2" required>
<div id="uname_response" ></div>
Here is the screenshot:
form duplicate screenshot
The only code in your PHP file should be within the <?php ?> tags. You need to seperate your PHP code into another file.
Related
My ajax code:
$('#name').keyup(function() {
var usercheck = $(this).val();
$('#nameAvailability').html('<img src="../SPR/assets/img/loading.gif" width="300" />'); //this part is working
$.post("../SPR/backend/username_availability_check.php", {user_name: usercheck} ,
function(data)
{
if (data.status == true)
{
$('#nameAvailability').parent('div').removeClass('has-error').addClass('has-success');
} else {
$('#nameAvailability').parent('div').removeClass('has-success').addClass('has-error');
}
$('#nameAvailability').html(data.msg); // not working
} ,'json');
});
My php code:
<?php
require("connection.php");
if(isset($_POST['user_name']) && $_POST['user_name'] != '')
{
$response = array();
$username = mysqli_real_escape_string($conn,$_POST['user_name']);
echo $username;
$sql = "select username from users where users.username='".$username."'";
$res = mysqli_query($conn, $sql);
$count = mysqli_num_rows($res);
if($count > 0)
{
$response['status'] = false;
$response['msg'] = 'Username already exists.';
}
else if(strlen($username) < 6 || strlen($username) > 15){
$response['status'] = false;
$response['msg'] = 'Username must be 6 to 15 characters';
}
else if (!preg_match("/^[a-zA-Z1-9]+$/", $username))
{
$response['status'] = false;
$response['msg'] = 'Use alphanumeric characters only.';
}
else
{
$response['status'] = true;
$response['msg'] = 'Username is available.';
}
echo json_encode($response);
echo $response;
}
?>
I have used session_start() in my index.php where user inputs his username in the input field with id 'name'
I have checked the given php code by running it individually by passing a custom username from the database and it works fine. So probably there's something wrong with the ajax code.
It is impossible to tell what your clientside code does based on what is posted here.
But in general, for debugging and to check if your serverside code works, do this:
Make a simple form, that POSTS to your PHP script.
<form action="whateveryourphpcodeisnamed.php" METHOD="POST">
<INPUT TYPE="TEXT" NAME="user_name">
<INPUT TYPE="SUBMIT" VALUE="TEST THE USERNAME">
</FORM>
And see what it says back to you.
Be sure to activate error_reporting during development.
I have registration module and I already done so far the validation of all fields(fields are: name, email, username and password),check if the email and username is already existing.
And trying to add a suggestion if the username is already existing. I am done in adding a prefix in the username but having a problem to pass the variable to javascript and display it in my view
This is my Controller
$get_username = clean_data($_POST['username']);
$where = array(
"username" => $get_username
);
$check_username = $this->Crud_model->count_result('username','users',$where);
if($check_username > 0)
{
$fetch_username = $this->Crud_model->user_exists('users',$where);
$last_username = strrev((int)strrev($fetch_username)); // returns last numeric value of username
if($last_username){
$count = count($last_username);//counts number of digit
$str = substr($username, 0, -($count));;// subtract numeric value from last of username
}
$newstr = $last_username+1;
$username= $get_username.$newstr;
echo json_encode("existing");
// echo "var username = ". json_encode($username).";";
}
else
{
$insert_user = array(
'first_name' => clean_data(ucwords($_POST['first_name'])),
'last_name' => clean_data(ucwords($_POST['last_name'])),
'profile_picture' => "profile-picture.jpg",
'username' => $get_username,
'email' => $_POST['email'],
'password' => hash_password($_POST['password']),
'status' => 1,
);
$this->Crud_model->insert('users',$insert_user);
echo json_encode("success");
}
this is My javascript with ajax
$(document).ready(function(){
$("#registration-form").on('submit',function(e){
$.ajax({
url: base_url+"formsubmit/new_form_submit",
type: "POST",
data: $(this).serialize(),
success:function(data)
{
var result = JSON.parse(data);
if(result === "success")
{
$("h5").html("");
success_message("#success-message-new-account","Create Successful!");
window.setTimeout(function(){location.href=base_url},2000);
}
else if(result === "existing")
{
$("h5").html("");
success_message("#existing-message-account","You may use!".$username);
// window.setTimeout(function(){location.href=base_url},2000);
}
else{
$("#first_name_error").html(result.first_name_error);
$("#last_name_error").html(result.last_name_error);
$("#username_error").html(result.username_error);
$("#email_error").html(result.email_error);
$("#password_error").html(result.password_error);
}
},
error: function(data) {
alert('error');
}
})
e.preventDefault();
})
})
This is my My View
<div id="existing-message-account"></div>
<div class="wrap-input100 validate-input">
<input class="input100" type="text" name="first_name" id="first_name">
<span class="label-input100">First</span>
</div>
<div class="wrap-input100 validate-input">
<input class="input100" type="text" name="last_name" id="last_name">
<span class="label-input100">Last</span>
</div>
After the user fill up the registration form. It will be process in my javascript, now it will be check if the username registered is already existing or not. if it is not then it will be save in my table. If it is existing then it will add a number prefix.
Example
In my table users. I have existing username abcd, if the user register abcd then there would be a message "Username is already taken, you may use abcd1"
Question: How do I pass the variable $username into my javascript?
NOTE: I tried this approach, changing echo json_encode("existing"); into this echo json_encode($username). My javascript else if(result === $username)... The message will not work anymore.
Hope this will help you :
For the existing status record do like this :
$data['username'] = $username;
$data['status'] = 'existing';
echo json_encode($data);
exit;
For the success status record return like this
$data['username'] = $username;
$data['status'] = 'success';
echo json_encode($data);
exit;
Your ajax success part should have code like this :
var result = JSON.parse(data);
if(result.status === "success")
{
$("h5").html("");
success_message("#success-message-new-account","Create Successful!");
window.setTimeout(function(){location.href=base_url},2000);
}
else if(result.status === "existing")
{
$("h5").html("");
success_message("#existing-message-account","You may use!" + result.username);
// window.setTimeout(function(){location.href=base_url},2000);
}
i have a little problem here with jQuery.
i have made a submit form with this following code :
<form class="form-inline" id="newslatter" role="form" >
<select name="city" id='city' class="form-control">
<option value="<?=$id?>">Singapore</option>
</select>
<input type="email" class="form-control" name="email" id="email" placeholder="<?=$this->lang->line('footer_enter_email')?>" value="<?=(isset($json)?$json["email"]:"")?>">
<label id="emptyemail" style="color:indianred"><?php echo form_error('email'); ?></label>
<button type="submit" class="btn btn-success input"><?=$this->lang->line('footer_signup_now')?></button>
</form>
<div id="register_complete" style="display: none;color:whitesmoke;">
<p align="center">Congratulations, You have been added to our Newsletter
Thank you for your registration. From now on you will receive updates about exclusive offers in your city.</p>
</div>
and this is my jQuery :
<script type="text/javascript">
function validateEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("#newslatter").submit(function(e){
e.preventDefault();
var email= $("#email").val();
var city=$("#city").val();
var something_wrong="";
var agreement = $('#agreement input[type="checkbox"]').is(":checked");
if(email.length == 0){
$("#emptyemail").html("Please fill in Email field");
$("#email").focus();
something_wrong=true;
}else if(!validateEmail(email)){
$("#emptyemail").html("insert valid email address!");
something_wrong=true;
}else{ $("#emptyemail").html(""); something_wrong=false; }
if(agreement == false ){
$("#notagree").html("You should read and accept Terms and conditions and Privacy Policy");
something_wrong=true;
}else{ $("#notagree").html(""); something_wrong=false;}
if( something_wrong == true) return false;
jQuery.ajax({
type: "POST",
url: "ajax/newslatter",
dataType: 'json',
data: {pcity:city,pemail:email},
success: function(res) {
if (res)
{
if(res.message != "success"){
$("#emptyemail").html(res.message);
return false;
}else{
$("#newslatter").hide();
$("#register_complete").show();
}
}
}
});
return false;
});
and this is my ajax controller:
Function newslatter(){
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
}
and here is the following model for ajax :
Function m_check_email($email){
$sql="SELECT `email` FROM `uhd_newslatter` WHERE `email` = '$email'";
$query=$this->db->query($sql)->row_array();
return $query;
}
Function m_insert_newslatter($city,$email){
$sql="INSERT INTO `uhd_newslatter` (`singapore_address_id` , `email`) VALUES ($city,'$email')";
$this->db->query($sql);
}
those are all my code. my problems are :
if i submit data, data send into my database, but after that there is nothing happening in my view, actually if submit process is success there will be show my success message, and all my submit form will be hide
and, if i use the same email, if i submit it, it should be show a message that i put it ajax controller. but data isn't input to database.
guys can you help me whats wrong on my code?
sorry if i have so many part of code (:
In your ajax writen dataType:'json', but in your controller there is json_encode($yourdata); that will be read in success ajax. Because of that, your success is not executed.
jQuery.ajax({
type: "POST",
url: "ajax/newslatter",
dataType: 'json',
data: {pcity:city,pemail:email},
success: function(res) { //controller has to make json_encode($data); for product res value.
if (res)
{
if(res.message != "success"){
$("#emptyemail").html(res.message);
return false;
}else{
$("#newslatter").hide();
$("#register_complete").show();
}
}
}
});
Your controller need to be added echo json_encode($data);
Function newslatter(){
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
echo json_encode($data);//add this line
}
Please update your newsletter function with this code:
function newslatter(){
$data =array();
$city_id=$this->input->post('pcity',true);
$email = $this->input->post("pemail",true);
$query= $this->ajax_m->m_check_email($email);
if(strlen($email)==0){
$data["message"]= "Please fill in Email field";
}else{
if($query != null){
$data["message"]= "E-mail already registered";
}else{
$this->ajax_m->m_insert_newslatter($city_id,$email);
$data["message"]= "success";
}
}
return json_encode($data);
}
I have a login script that should return 'success' or 'failure' respectively, but it adds many spaces before the result, in the console it shows tha value as "<tons of space> success". This is the PHP for the login script:
public function login() {
global $dbc, $layout;
if(!isset($_SESSION['uid'])){
if(isset($_POST['submit'])){
$username = mysqli_real_escape_string($dbc, trim($_POST['email']));
$password = mysqli_real_escape_string($dbc, trim($_POST['password']));
if(!empty($username) && !empty($password)){
$query = "SELECT uid, email, username, password, hash FROM users WHERE email = '$username' AND password = SHA('$password') AND activated = '1'";
$data = mysqli_query($dbc, $query);
if((mysqli_num_rows($data) === 1)){
$row = mysqli_fetch_array($data);
$_SESSION['uid'] = $row['uid'];
$_SESSION['username'] = $row['username'];
$_SERVER['REMOTE_ADDR'] = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : $_SERVER["REMOTE_ADDR"];
$ip = $_SERVER['REMOTE_ADDR'];
$user = $row['uid'];
$query = "UPDATE users SET ip = '$ip' WHERE uid = '$user' ";
mysqli_query($dbc, $query);
setcookie("ID", $row['uid'], time()+3600*24);
setcookie("IP", $ip, time()+3600*24);
setcookie("HASH", $row['hash'], time()+3600*24);
echo 'success';
exit();
} else {
//$error = '<div class="shadowbar">It seems we have run into a problem... Either your username or password are incorrect or you haven\'t activated your account yet.</div>' ;
//return $error;
$err = 'failure';
echo($err);
exit();
}
} else {
//$error = '<div class="shadowbar">You must enter both your username AND password.</div>';
//return $error;
$err = "{\"result\":\"failure\"}";
echo json_encode($err);
exit();
}
}
} else {
echo '{"result":"success"}';
exit();
}
return $error;
}
and the form and JS
<div class="shadowbar"><form id="login" method="post" action="/doLogin">
<div id="alert"></div>
<fieldset>
<legend>Log In</legend>
<div class="input-group">
<span class="input-group-addon">E-Mail</span>
<input type="email" class="form-control" name="email" value="" /><br />
</div>
<div class="input-group">
<span class="input-group-addon">Password</span>
<input type="password" class="form-control" name="password" />
</div>
</fieldset>
<input type="submit" class="btn btn-primary" value="Log In" name="submit" />
</form></div>
$(function login() {
$("#login").validate({ // initialize the plugin
// any other options,
onkeyup: false,
rules: {
email: {
required: true,
email: true
},
password: {
required: true
}
}
});
$('form').ajaxForm({
beforeSend: function() {
return $("#login").valid();
},
success : function(result) {
console.log(result);
if(result == " success"){
window.location = "/index.php";
}else if(result == " failure"){
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
}
});
});
but the result always has a lot of spaces for some reason. I'm new to JS, so if this is common, I don't already know.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
define("CCore", true);
session_start();
//Load files...
require_once('include/scripts/settings.php');
require_once('include/scripts/version.php');
require('include/scripts/core.class.php');
require('include/scripts/nbbc_main.php');
$parser = new BBCode;
$core = new core;
$admin = new admin;
require_once('include/scripts/layout.php');
require_once('include/scripts/page.php');
//Set Variables...
global $dbc, $parser, $layout, $main, $settings, $core;
$page = new pageGeneration;
$page->Generate();
?>
this is my index, and anything before the page is generated and login() is called, is in there.
I suppose you are using Ajax calls. I had the same problem, but it my case the result hadn't contain spaces, it was returned in new line. The problem was that my script which was requested by Ajax, contained "new line" character before the PHP script. Search your script file for spaces before PHP script starting with <?php //code... If you had included some scripts in the script which returns success note, search them as well.
I dont know if it matters but your
if(result == " success"){ // <<<<<< Here is a Problem maybe
window.location = "/index.php";
}else if(result == " failure"){ // <<<<<< Here is a Problem maybe
$("#alert").html("<div class='alert alert-warning'>Either you're username or password are incorrect, or you've not activated your account.</div>");
//$("#alert").show();
}
compares your result from the server which is i.e. "success" with " success". There is space too much.
EDIT:: I dont get ether why you jumps between the response format. Sometimes you echo "success" which is plain and good with your if condition but sometimes you return json encodes strings.
These Responses you can't just compare with plain text. These Responses you have to Parse into a JSON Object. Then you could compare with:
if (parsedJSONobject.result == "success"){}
The comments on the question are most probably correct: the spaces are being (again, probably, nobody can know for sure without reading the whole source) echoed by PHP included before this. For example, if you do:
<?php
// there's a space before the previous line
you'd get that space in the output.
What you can do is a bit of a hack, you include a header, for example:
header('Content-Type: text/html');
just before your success output, this will (yet again, probably) output something like:
Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23
(note the "output started" part) and now you know where to start looking.
HTH.
My account was suspended because of SPAM several times and my host provider told me to check my website security. May be my forms are not secured enough. Do you think that this form can be used to send spam?
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
html:
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
php:
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
Many thanks!
Your form would actually be not safe against bots, because you dont got any captcha or something.
2 Options for you:
Captcha
Captcha -> you got something to fill in -> you probably know this!:)
https://www.google.com/recaptcha
Honeypot
Honeypot means, you are adding hidden fields in your form. And if those hidden fields have changed - you know that a BOT has entered content in your form. Aswell, this is better than Captchas, because your User doesnt has to fill in a Captcha
I would prefer Honeypot, because I don't like forms, where i have to fill in a Captcha once or even twice, when I failed or the captcha wasnt readable.
http://haacked.com/archive/2007/09/11/honeypot-captcha.aspx/
I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.
another option is what I did is to use a hide field and put the time stamp on it and then compare to the time stamp on the PHP side, if it was faster than 15 seconds (depends on how big or small is your forms) that was a bot...
Taking clue from the suggestions above, I am just putting a ready code for you to use.
HTML
<form id="form" method="post" name="form" action="send.php">
<input id="name" type="text" name="name"/>
<input id="company" type="text" name="company"/>
<input id="email" type="text" name="email"/>
<input id="checkbot" type="hidden" name="timestamp" value="" />
<input id="phone" type="text" name="phone"/>
<input id="location" type="text" name="location"/>
<textarea name="message" id="message" rows="10"></textarea>
<input class="submit" type="submit" value="send" name="submit"></input>
</form>
Javascript
<script type="text/javascript">
$(document).ready(function () {
/*Set current time on the hidden field.*/
$('#checkbot').val($.now());
$('#form').ajaxForm({
beforeSubmit: validate
});
function validate(formData, jqForm, options) {
var name = $('input[name=name]').fieldValue();
var email = $('input[name=email]').fieldValue();
var company = $('input[name=company]').fieldValue();
var location = $('input[name=location]').fieldValue();
var phone = $('input[name=phone]').fieldValue();
var message = $('textarea[name=message]').fieldValue();
if (!name[0]) {
alert('Please enter your name');
return false;
}
if (!company[0]) {
alert('Please enter the name of your organization');
return false;
}
if (!email[0]) {
alert('Please enter your e-mail address');
return false;
}
if (!phone[0]) {
alert('Please enter your phone number');
return false;
}
if (!location[0]) {
alert('Please enter your location');
return false;
}
if (!message[0]) {
alert('Please enter your message');
return false;
}
else {
$("#form").fadeOut(1000, function () {
$(this).html("<img src='note.png' style='position: relative;margin: 0 auto;width: 500px;left: 20px;top: 30px;'/>").fadeIn(2000);
});
var message = $('textarea[name=message]').val('');
var name = $('input[name=name]').val('');
var email = $('input[name=email]').val('');
var phone = $('input[name=phone]').val('');
var company = $('input[name=company]').val('');
var location = $('input[name=location]').val('');
}
}
});
</script>
PHP
<?php
if($_POST){
$email = $_POST['email'];
$name = $_POST ['name'];
$company = $_POST ['company'];
$phone = $_POST ['phone'];
$location = $_POST ['location'];
$message = $_POST ['message'];
$checkbot = $_POST['timestamp'];
$time_diff = time() - $checkbot;
//If Time difference is less than 15 sec it's a bot
if($time_diff < 15){
exit;
}
// response hash
$ajaxresponse = array('type'=>'', 'message'=>'');
try {
// do some sort of data validations, very simple example below
$all_fields = array('name', 'email', 'message');
filter_var($email, FILTER_VALIDATE_EMAIL);
foreach($all_fields as $field){
if(empty($_POST[$field])){
throw new Exception('Required field "'.ucfirst($field).'" missing input.');
}
}
// ok, if field validations are ok
// now Send Email, ect.
// let's assume everything is ok, setup successful response
$subject = "Someone has contacted you";
//get todays date
$todayis = date("l, F j, Y, g:i a") ;
$message = " $todayis \n
Attention: \n\n
Please see the message below: \n\n
Email Address: $email \n\n
Organization: $company \n\n
Phone: $phone \n\n
Location: $location \n\n
Name: $name \n\n
Message: $message \n\n
";
$from = "From: $email\r\n";
//put your email address here
mail("...#yahoo.com", $subject, $message, $from);
//prep json response
$ajaxresponse['type'] = 'success';
$ajaxresponse['message'] = 'Thank You! Will be in touch soon';
} catch(Exception $e){
$ajaxresponse['type'] = 'error';
$ajaxresponse['message'] = $e->getMessage();
}
// now we are ready to turn this hash into JSON
print json_encode($ajaxresponse);
exit;
}
?>
In theory it can be used to send spam, because there are only checks if fields have values and as long the fields have a value, it does not care whether the input was human or a bot. You could improve the security by adding captcha codes (http://www.captcha.net/), to validate if an individual filling in your form is a human.
Try using this Spam Checker.
Useful program written in Java which looks up for spam IP Addresses using DNS lookups. Hope so it helps.