javascript image preloading

Image Preloading with JavaScript

Now a days web visitor prefers to see fancy page designing .when designing most attractive web page ,it becomes must use lot of images ,back grounds ,animation effects.
When page becomes more attractive with lot of images, it takes time to load all the images and it consumes the user bandwidth.
Generally each embedded page elements like images, audio, video objects are loaded when browser makes HTTP request to server. When it comes to tri state buttons, mouse over image, loading large images, the user wait to see effects at first time. After loading first time browser will cache the image.

Image Object

So over come this first time loading of image we use JavaScript image object for loading.
We create an image object instance before web page body loaded, so the browser will make HTTP request before the required mouse over, image hover effect, tri state buttons.
Most advanced browser now a days use DOM, so it works on all browser.

CSS and Sprites

for javascript disabled browsers we can use css & sprite image preloading.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>image preload</title>
<script type="text/javascript">
function preload_images(){
	img_length=preload_images.arguments.length;
	for(var i=0;i<img_length;i++){
		src=preload_images.arguments[i];
		img=new Image();
		img.src=src; //here we make http request
	}
}
// we are calling the function there by making HTTP request for images before page body loads
//here we use function argument property for multiple images
//remember all the image paths can be absolute or relative
preload_images('myimg.gif','urimg.jpg');
</script>
</head>
<body>
</body>
</html>

download source code

image-preloading-javascript-source-code

protecting web contact forms from spam bots

Protecting web forms from spam bots using PHP

Spam bot is a program that submits the data to server by guessing form fields with html code.
For detailed article please refer my previous post.

Here some methods of preventing Spam bots that automatically submits.

  • Using captcha
  • Using random hidden field
  • Using hidden input text box.
  • Email header injecting.
  • Checking referrer page
  • Following basic rules

We can prevent the Spam bots with some basic rules
Prevent email harvesting on your web pages, see my previous post anti email harvesting.
Generally Spam bots looks for form tag and contained input, check box, radio boxes, option element (Hhhh all the form elements), fills their data with their spam data so we can take this as advantage, some spam bots stores this information and sends with proxy without resubmitting the web contact form, so we can prevent this type of technics.
Use deferent form fields than usually, like use ‘ xyz_nm’ instead ‘name’.Change the form field’s name in regular interval, like put ‘zmon_nm’ on ‘Monday’, ‘ztue_nm’ on ‘Tuesday’.
Use random named hidden input field with a default value is empty on every form submission like captcha, if the default value of the hidden field changed other than default, it is sure Spam.
Put one input text box element with random name and hide it with CSS style, since it won’t visible to general user, the default value could not changed, if any changes made to this value of input it is definitely Spam.
Don’t put email address in the form elements, instead put it in sever side variable.
Check for page referrer, however some server’s firewalls don’t allow this information, they strips the data.
Use captcha like methods or services that are available present , but this captcha has some inconvenience to the user.
Disabling or filtering HTML message in form elements, since maximum spam bots try to fill HTML data.
Make sure to access all the forms for login users and track down their messaging and ban certain user.
protect-web-form-from-spams-maheshcharicom

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php 
#function that validate the user email
function is_valid_email($email){
$eregpat="^[A-z][A-z0-9_-]+([.]([A-z0-9_-])+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$";
return eregi($eregpat,$email );
}
 
#function that validate user comments
function is_valid_comments($data){
return ($data=="");
}
#function that clean the user data againest 
#email header injection so we clean it
function safe_mail($data){
#clean non standerd alpha numeric and some special symbels
#clean email related headers like header,from,body,'cc','bcc',\r\n etc
$patterns=array('/[^a-zA-Z0-9\.-@_]/','from','header','body','CC','BCC');
return preg_replace($patterns,'',$data);
}
 
 
function send_mail($data){
#do what ever you want here with user data
#like storing into database or sending email to admin
}
 
#clean all data from user contact form and process this to store in mysql and sending email

function process_contactform(){
$data=array();
$data['name']=safe_mail($_POST['sfsf_name']);
$data['email']=safe_mail($_POST['jflsjls_email']);
$data['website']=safe_mail($_POST['kipmp_website']);
$data['comments']=safe_mail($_POST['comments_sfs']);
send_mail($data);
}
 
 
require_once('recaptchalib.php');
 
// Get a key from http://recaptcha.net/api/getkey
$publickey = "6LdVSQYAAAAAAFwb2919Sf8Uhcq3Z55bQc7d8Bx0";
$privatekey = "6LdVSQYAAAAAAIVT-VaJlea6WuOlLqJtt0UUK6xZ";
 
# the response from reCAPTCHA
$resp = null;
#error cacher
$errors = array();
 
if(isset($_POST['Submit'])){
# was there a reCAPTCHA response?
if (isset($_POST["recaptcha_response_field"])) {
        $resp = recaptcha_check_answer ($privatekey,
                                        $_SERVER["REMOTE_ADDR"],
                                        $_POST["recaptcha_challenge_field"],
                                        $_POST["recaptcha_response_field"]);
 
        if ($resp->is_valid) {
                echo "You got it!";
        } else {
                # set the error code so that we can display it
                $errors[] = $resp->error;
        }
}
 
#check the page that submits is belong to our domai or not
#remember some servers don't allow this data or don't have information
if(strpos('localhost', $_SERVER['HTTP_REFERER'])==false){
$errors[] ='This page can be prcessed from this domain only.';
}
 
#check email validation
if(isset($_POST['jflsjls_email']) and !is_valid_email($_POST['jflsjls_email'])){
$errors[]='Invalid email address.'; 
}
 
#check comment validation 
if(isset($_POST['comments_sfs']) and !is_valid_comments($_POST['comments_sfs'])){
$errors[]='Trying to email header injection.';
}
 
#check user is bot or not
if(isset($_POST['owjrj_ran']) and !$_POST['owjrj_ran']==''){
$errors[]='You are spam bot.';
}
 
#check user is bot or not
if(isset($_POST['mpmpm_rwrw']) and !$_POST['mpmpm_rwrw']==''){
$errors[]='You are spam bot.';
}
 
#check all errors and process contact form
if( isset($_POST['Submit']) and count($errors)==0){
process_contactform();
}
 
 
}
 
#if errors display
if(isset($_POST['Submit'])){
if(count($errors)>0){
echo '<ul class="errors" >';
foreach($errors as $k=>$v){
echo '<li>'.$v.'</li>';
}
echo '</ul>';
}
}
?>

HTML code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<html >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Contact Form</title>
</head>
<body>
 
<script type="text/javascript">
 
/*
This javascript form validation only for generel users.
the spam bots don't process this type javascript validation so we have to 
validate again on server side.
*/
function validate_form(){
 
var errors='';
 
var fm=document.contactform;
 
if(fm.jflsjls_email.value==''){
errors+='Email required.\n';
}
 
if( !(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(fm.jflsjls_email.value))){
errors+='Invalid email address.\n';
}
 
if(fm.comments_sfs==''){
errors+='Empty comments.\n';
}
 
if(errors!=""){
alert(errors);
return false;
}
return true;
}
</script>
<form action="" method="post" name="contactform" id="contactform" onsubmit="return validate_form();">
  <table width="500" border="1">
    <tr>
      <th colspan="2">Contact Me
        <script>
		//email obfuscation 
document.write("m"+"y"+"m"+"a"+"i"+"l"+" &#64;"+"y"+"o"+"u"+"d"+"o"+"m"+"a"+"i"+"n"+" &#46"+"c"+"o"+"m");
</script>      </th>
    </tr>
    <tr>
      <td width="295"> Name </td>
      <td width="288"><input name="sfsf_name" type="text" id="sfsf_name" />      </td>
    </tr>
    <tr>
      <td>Email: * </td>
      <td><input name="jflsjls_email" type="text" id="jflsjls_email" /></td>
    </tr>
    <tr>
      <td> Web Site </td>
      <td><input name="kipmp_website" type="text" id="kipmp_website" value="" /></td>
    </tr>
    <tr>
      <td colspan="2">
	  <!-- 
	  hidden field that real user can't see ,only spam bots can process
	  in some spam bots this hidden field don't change the value ,
	  they submit as it is
	   -->
	  <input name="owjrj_ran" type="hidden" id="owjrj_ran" />
	  <!--
	  to overcome we use text field that is hidden from real user.
	  but this field is precessed by spam bots.
	  it is simply .
	   -->
        <input name="mpmpm_rwrw" type="text" id="mpmpm_rwrw" style="display:none" value="" />
        Comments*</td>
    </tr>
    <tr>
      <td colspan="2"><textarea name="comments_sfs" cols="45" rows="5"></textarea></td>
    </tr>
    <tr>
      <td colspan="2" align="left">
	  <!-- 
	  recaptcha text area field
	  this is another guarented check.
	  but it is not user freindly 
	   -->
	  <?php echo recaptcha_get_html($publickey, $errors);?></td>
    </tr>
    <tr>
      <td colspan="2" align="center"><input type="submit" name="Submit" value="Submit" />
        <input type="reset" name="Submit2" value="Reset" /> 
        <small>* Required field </small></td>
    </tr>
  </table>
</form>
</body>
</html>

Download Source Code

web-contact-form-with-anti-spam-methods download link here

email obfuscation

protecting E-mail Address on web pages with php, javascript from E-mail spammers

E-mail Spam is flooding the Internet with many copies of the same message, in an attempt to force the message on people who would not otherwise choose to receive it.Most spam is Commercial advertising, often for dubious products, get-rich-quick schemes, or quasi-legal services. Spam costs the sender very little to send — most of the costs are paid for by the recipient or the carriers rather than by the sender.

How do they catch email address of users? Or how do they email harvesting?

There are many ways to get users email address but here we talk about only two ways.

From web pages:

Spammers have programs which spider through web pages, looking for email addresses, e.g. email addresses contained in mailto: HTML tags [those you can click on and get a mail window opened],a word contains @ symbol ,a word contains mailto:

From various web contact or enquiry forms.

Some sites request various details via forms, e.g. guest books & registrations forms.
Spammers can get email addresses from those either because the form becomes available
on the world wide web, or because the site sells / gives the emails list to others.
some spammers use weak security web forms on certain websites to protect web form from spammers please refer my post

Preventing E-mail harvesting on web pages

e-mail Address munging or e-mail Obfuscation

Address munging is the practice of disguising, or munging, to prevent it being automatically collected by spam bots.
Some examples are

  • no-one at example (dot) com
  • no-one@elpmaxe.com.invalid
  • moc.elpmaxe@eno-on
  • no-one@exampleREMOVEME.com.invalid
  • remove .invalid
  • no-one@exampleNOSPAM.com.invalid
  • n o – o n e @ e x a m p l e . c o m
  • no-one@example.com (as HTML)

Even though the email harvesting reduced in measurable amount, with this method the main user has to predict the original. Now days some spam bots also overcomes this method.

Using javascript

Most of the spam bots don’t execute the javascript and they use regular expression to catch the address.
So we can advance the method of munging with following examples

For static web pages e-mail Obfuscation

1
2
3
4
5
6
<script type="text/javascript">
var name = 'user';
var at = '@';
var domain = 'example.com';
document.write(name + at + domain);
</script>
1
2
3
4
<script>
document.write(‘m’+’y’+’m’+’a’+’i’+’l’+&#64;+’y’+’o’+’u’+’d’+’o’+’m’+’a’+’i’+’n’+&#46+’c’+’o’+’m’);
</script>
//In the above example we use html equivalent ASCII chars &#64 for  symbol and &#46 for ‘.’ Character.

For dynamic web pages with PHP server side language e-mail Obfuscation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function safe_asciimail($email){
$length=strlen($email);
	if($length==0)return '';
	$email=strtolower(trim($email));
	$email_array=str_split($email);
	$ascii_email_array=array();
	for( $i=0;$i<count($email_array);$i++){
		$c=$email_array[$i];
		$ascii_email_array[]='&#'.ord($c).';';
	}
return '<script> document.write("'.implode('',$ascii_email_array).'");</script>';
}
 
//We can call this method as follow 
//safe_asciimail(‘mymail@yourdomain.com’);

HTML window earthquake using javascript

Funny EarthQuake or Shake Effect of html window

With Javascript We can play with our own effects and animation.here we find one simple example of window shake effect.here we use basic window object and its moveby method.we already discussed about settimeout function in previous post.
In this example href attribute of HTML anchor to javascript functions start,stop.when we click link browser call the corresponding functions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<html>
<head>
<script>
var timer;
var movelength=10;
function start()
{
parent.moveBy(0,movelength)
parent.moveBy(0,-movelength)
parent.moveBy(movelength,0)
parent.moveBy(-movelength,0)
timer=setTimeout("start()",100)
}
function stop()
{
clearTimeout(timer)
}
</script>
</head>
<body>
<a href="javascript:start();">start</a>
<a href="javascript:stop();">stop</a>
</body>
</html>

Refreshing Page for regular interval with javascript

Refreshing the html page for regular interval time with javascript

One of my friend asked to refresh the HTML page in his project that changes the stock rates every one minutes.i gave him simple solution like
example:1

7
8
9
10
11
12
13
<script>
var timer;
function refreshmypage(){
document.location=document.location.href;
}
timer=setTimeout(refreshmypage,60*1000);
</script>

Add above script after your HTML body content.Here setTimeout function takes two arguments one for function handler and other time to call the function,the time is in milliseconds.so i set to 60* 1000 i.e 60 seconds.
Example :2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<script type="text/javascript">
function load()
{
setTimeout("refresh()", 2000)
}
function refresh(){
window.location.reload()
load()
}
</script>
</head>
<body onload="load()">
</body>
</html>

Above example also can be used.
There is a deference between two examples.Example1 adds new history in every reload and Example2 reloads the page without browser history. i.e if you use example 1 ,user can see each reload by clicking browser’s back button.