Blog

Newest Post
Blog Archives
Blog Categories

Portfolio

3D Models
Banners
Brochures
Business Cards
Custom Programming
Environments
Flash Projects
Game Design
Image Altering
Web Design

About

Resume
Recommendation Letters

Contact

May 10, 2010

Prevent Spam without Captcha

Filed under: JavaScript,The Coding World — admin @ 7:13 pm

The following will show you how to prevent spam without the use of those annoying captcha images. I use javascript, which according to W3C, approximately 95% of the people browsing the web have it enabled. The odds of one of your visitors having it disabled is slim. If it does concern you however, you could always place a notice to turn on javascript before using the form or you could always use another method, just place the other method in <noscript> </noscript> tags.

Below is how you could prevent spam with simple javascript.

TESTED IN THE LATEST BROWSERS: Internet Explorer 8.x, Firefox 3.x, Chrome 4.x, Safari 4.x

 

Step 1: Create a separate javascript file and link to it in the <head> section of your page. I will call my file “formvalidation.js” and I will link to it from my form page “form.html”.

Example of the “head” section of “form.html”:

  <head>
    <script language="JavaScript" src="formvalidation.js" type="text/javascript"></script> 
  </head>
  <body>
  Your form would be here.
  </body>

 

Step 2: Remove the form’s action=”" attribute

Some Spam bots will submit directly to the form’s source, this step prevents that.

Example of the form’s attributes:

 
  <form name="exampleform" method="POST" id="exampleform">

 

Step 3: Add some simple requirements to our form. I will use first name and last name.

Example:

<input type="hidden" id="req_id" name="req_id[]" value="first_name">
<input type="hidden" id="req_id" name="req_id[]" value="last_name">

 

Step 4: Add a hidden field called “human” and set its value to “0″. We will change this value once we determine a human is filling out the form.

Example:

<input type="hidden" id="human" name="human" value="0">

 

Step 5: On one of your required fields, add a javascript function to call once something is typed into it. This verifies that a human is filling out the form. I will place it on the “Last Name” field.

<input type="text" name="last_name" id="last_name" onchange="validateHuman('exampleform');" />

 

Step 6: Make the form submit button execute a javascript function that will check all the required fields, verify that a human submitted the form, and then submit the form for processing.

Example:

<input type="button" name="Submit" value="Submit" onclick="submitForm('exampleform');" />

 

Step 7: Add the following Javascript to your Javascript file “formvalidation.js”. These two javascript functions, “validateHuman” and “submitForm” will do all the work of preventing spam.

validateHuman – changes the “human” form element to another number once a person has typed into your required field.

submitForm
– validates the required form elements have been filled in, checks to see the value of “human” has changed, and then submits the form for processing.

View Code JAVASCRIPT
 
function submitForm(frm){
 
  //Check is the visitor's browser supports the javascript function
  if (document.forms[frm]) {
    //START function executed
 
	//we will now check to see if all required fields were filled in
    var error = '';
 
	if(document.forms[frm].elements['req_id'] != null || document.forms[frm].elements['req_id'] != '') {
        //store all of the required fields into "reqs"
		var reqs=document.forms[frm].elements['req_id[]'];
        //count the number of required fields
		var nbr_fields = reqs.length;
        //set a variable "req" to make sure all the "reqs" stay true
		var req = true;
		//loop through all the required fields, making sure they are not blank
		for(var i=0;i<nbr_fields;i++){
		  if(document.forms[frm].elements[reqs[i].value].value.length <= 0){
		   //the field is blank
		   req = false;
		   //list what field has been left blank to inform the user
		   if (reqs[i].value == 'first_name') error += "\n - First Name";
		   if (reqs[i].value == 'last_name') error += "\n - Last Name";
          }
        }
 
        //if all required fields are filled in
		//and the "human" form element has changed
		//submit the form
		if(req==true && document.forms[frm].elements['human'].value == '42'){
            document.forms[frm].action = "http://somewebsite.com/submit.php";
			document.forms[frm].submit();
            return true;
        } else {
          alert('Opps, it looks like some fields are blank:\n'+error);
          return false;
        }
        return false
     }
 
    //END function executed
  } else { 
    //START the browser does not support the function
    alert('Your browser lacks the capabilities required to run this script!\n\nPlease call 555-555-5555 and we will gladly take your information over the phone.');
    //END the browser does not support the function
  }
 
}
 
function validateHuman(frm){
	document.forms[frm].elements['human'].value = "42";
}

That’s it! Your form should now prevent spam bots from submitting directly to it. Below is just a total picture of how “form.html” will look according to this demo.

Example of form.html:

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Example Form</title>
<script language="JavaScript" src="formvalidation.js" type="text/javascript"></script>
</head>
 
<body>
 
<form name="exampleform" id="exampleform" action="submit.php" method="POST">
<input type="hidden" id="req_id" name="req_id[]" value="first_name">
<input type="hidden" id="req_id" name="req_id[]" value="last_name">
<input type="hidden" id="human" name="human" value="0">
First Name: <input type="text" name="first_name" id="first_name" /><br />
Last Name: <input type="text" name="last_name" id="last_name" onchange="validateHuman('exampleform');" /><br />
<input type="button" name="Submit" value="Submit" onclick="submit_form('exampleform');" />
</form>
 
 
</body>
</html>

November 12, 2009

Use PHP to proportionally scale an image

Filed under: PHP,The Coding World — admin @ 3:06 pm

I wrote the following function to proportionally scale images that I was pulling from a directory.

 
function img_size($img,$alt) {
 
  list($width,$height) = getimagesize($img);
 
  $maxwidth = 140; //set max width here
 
  if ($width > $maxwidth) {
	$i = $width - $maxwidth;
	$x = $width - $i;
	$percent = $maxwidth/$width;
  }
  else
  {
    $x = $width;
    $percent = 1;
  }
 
  $y = $percent * $height;
 
  $img_src = '<img src="'.$img.'" width="'.$x.'" height="'.$y.'" alt="'.$alt.'" border="0" />';
 
  return $img_src;
}
 
echo img_size('http://somesite.com/image.jpg', 'some alt text'); 
//result <img src="http://somesite.com/image.jpg" width="140" height="(proportionate to 140)" alt="(alt)" border="0">

November 4, 2009

MySQL, UPDATE data into a database using CONCAT()

Filed under: The Coding World — admin @ 2:46 pm

To insert data into a MySQL database while preserving the already existing data, you will just concatenate your new data to the end of your existing data.

Below is an example of how to do it using the column “changelog” which is used to keep track of changes made to the row/record.

View Code MYSQL
UPDATE table1 SET changelog=CONCAT(changelog,"new data") WHERE id='idnumber'

If you would like the data that you are entering to appear at the beginning of the existing data, simply flip the concatenation, example:

View Code MYSQL
UPDATE table1 SET changelog=CONCAT("new data",changelog) WHERE id='idnumber'

November 3, 2009

MySQL DELETE with a Max() Subquery

Filed under: The Coding World — admin @ 4:50 pm

Here is another nifty way to use a Subquery when deleting a record from your MySQL table.

View Code MYSQL
DELETE FROM table1 WHERE id = '1' && saleid='345' 
	                  && slot = (SELECT MAX(slot) FROM table1)

MySQL INSERT with a Max()+1 Subquery

Filed under: The Coding World — admin @ 4:47 pm

This was a pain in my ass to figure out so I figured I would post it here in case anyone else needs to insert a record using a Max()+1 Subquery.

I only use the Max()+1 Subquery when the value you want to increase is not the primary key.

View Code MYSQL
INSERT INTO table (row1, row2, row3)
    SELECT 1 + COALESCE((SELECT MAX(row1) FROM table), 0), 'value2', 'value3'

October 22, 2009

Latitude and Longitude of a location using Javascript and Google

Filed under: JavaScript,The Coding World — admin @ 2:54 pm

The following Javascript will help you acquire the latitude and longitude of a location (using an address, zip code, or city).

Note: You will need to have a Google API key which is domain specific.

Place the following code in the <head> section:

View Code JAVASCRIPT
var geocoder;
geocoder = new GClientGeocoder();
 
function submitForm() {
  var address = document.getElementById("address").value + ", " + document.getElementById("city").value + ", " + document.getElementById("state").value + ", " + document.getElementById("zip").value;
  geocoder.getLocations(address, getCoords);
}
 
function getCoords(response) {
  if (!response || response.Status.code != 200) {
    alert("Unable to Create Lat and Lng for plotting.");
  } else {
    place = response.Placemark[0];
    var lat = place.Point.coordinates[1];
	var lng = place.Point.coordinates[0];
  }
 alert("Lat:"+lat+" - Lng:"+lng);
}

Here is the HTML that was used to pass the data:

Address: <input id="address" name="address" type="text" />
 
City: <input id="city" name="city" type="text" />
 
State: <input id="state" name="state" type="text" />
 
Zip: <input id="zip" name="zip" type="text" />
 
<input onclick="submitForm();" type="button" value="Submit" />

Latitude and Longitude of a location using PHP and Google

Filed under: PHP,The Coding World — admin @ 12:55 pm

The following PHP code will help you acquire the latitude and longitude of a location (using an address, zip code, or city).

Note: Your will be required to have your own domain specific Google API key.

if ($_POST['address']) {
 
$key = ' '; //you will need yo use your own domain specific API key
 
$address = stripslashes($_POST['address']);
 
$addressurl = urlencode($address);
 
$location = file("http://maps.google.com/maps/geo?q=".$addressurl."&amp;output=csv&amp;key=".$key);
 
list ($stat,$acc,$lat,$lng) = explode(",",$location[0]);
 
echo "LAT:".$lat." - LNG:".$lng;
 
}

Below is the HTML code which used a form to submit the address to the above PHP.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>;" method="post">
<input name="address" type="text" />
<input type="submit" value="Submit" />
</form>

February 9, 2009

Format Phone Number Fields with PHP

Filed under: PHP,The Coding World — admin @ 1:39 pm

Below is a function I wrote to take a phone number entered by a user and convert it into a desired format. The one shown below is 555-555-5555.

function phn_numb($numb) {
if (!is_numeric(substr($numb, 0, 1)) &amp;&amp; !is_numeric(substr($numb, 1, 1))) { return $numb; }
 
$chars = array(' ', '(', ')', '-', '.');
$numb = str_replace($chars, "", $numb);
if (strlen($numb) &gt; 10) {
//you must dial "1" before dialing this number
$numb = substr($numb, 0, 1).'-'.substr($numb, 1, 3).'-'.substr($numb, 4, 3).'-'.substr($numb, 7, 4);
}
else
{
$numb = substr($numb, 0, 3).'-'.substr($numb, 3, 3).'-'.substr($numb, 5, 4);
}
 
return $numb;
}

Therefore to see it in action:

$phonenumber = 2345678901;
 
echo phn_num($phonenumber);
 
//the resulting echo would be 234-567-8901

August 5, 2008

Javascript broke with multiple line variables from PHP

Filed under: JavaScript,PHP,The Coding World — admin @ 7:26 am

I have several sites where I use a pop up table to display information if the user rolls over and image. Example, if the user wants to view notes on a certain client, they can roll over a little “note” image to view the notes about the client pulled from a SQL database. The code I use for a message may be:

View Code JAVASCRIPT
note[0] = new Array("","<?php echo $message; ?>;");

That would work if $message was all one line. But as with all notes fields, you can never determine when the person entering data hits “Enter”. If the person did hit enter, your javascript would be broke and it would look like this in the source code.

View Code JAVASCRIPT
note[0] = new Array("","This is the start of the note field. I hit enter after this sentence twice.
 
Then I started typeing again");

This broke the Javascript. To fix this you can just swap the hidden special characters with a html line break.

Working code:

View Code JAVASCRIPT
note[0] = new Array("","<?php echo str_replace("\r\n","<br>;", $message); ?>;");

This would return:

View Code JAVASCRIPT
note[0] = new Array("","This is the start of the note field. I hit enter after this sentence twice<br><br>;Then I started typeing again");

July 18, 2008

Page Forwarding using Meta Tag

Filed under: The Coding World — admin @ 11:22 am

This code goes in the <Header> along with all other Meta info.

<meta http-equiv="REFRESH" content="0; url=page.php">
Next Page »
© - Digital Epiphany Designs, Online Portfolio for Web Design, Custom Programming, Grapic Design and Game Design.