PHP Fastest way to get image width and height

Well, i am currently updating my WordPress plugin. I faced a problem in the past to retrieve image width to determine whether a particular image is require to resize. The problem here is that checking a particular image height and width is expensive job. In order to not impact the loading time of the site using my plugin, i forfeited the capability of resizing and resize the image regardless of the size. The plugin works fine since the resizing is doing it on the fly. However, problems arise when a smaller image is being resize and this is not a desirable result. Therefore, i would like to see whether there is a solution exist that can easily solve my problem.

Getting Image size using getImageSize()

Obviously, the task here is talking about PHP, we will look at the getImageSize() functionality exist within the naive php function. I personally was using this on the plugin to determine the size of the image. However, i immediately removed this after i notice the impact this functionality has caused on my site.

The reason? Remote image will need to be downloaded into your server and then it will be read locally by php. The pitfall here is the time used to download remotely to your server. If all your image is in your server and not somewhere else like in a CDN, this might not be a problem.

Better solutions

Well, the better solutions to get image quickly is to create your own script to retrieve the first few bytes of the file since the size of the image is located there. Credit goes to James @ zifiniti.com for the script below,

<?php
   function getimagesize($image_url){
    $handle = fopen ($image_url, "rb");
    $contents = ""; 
    if ($handle) {
    do {
        $count += 1;
        $data = fread($handle, 8192);
        if (strlen($data) == 0) {
            break;
       }   
    $contents .= $data;
    } while(true);
    } else { return false; }
    fclose ($handle);

    $im = ImageCreateFromString($contents);
    if (!$im) { return false; }
    $gis[0] = ImageSX($im);
    $gis[1] = ImageSY($im);
    // array member 3 is used below to keep with current getimagesize standards
    $gis[3] = "width={$gis[0]} height={$gis[1]}";
    ImageDestroy($im);
    return $gis;                                                                                                                                                       
   }   
}
?>

Assuming you have a large image file, this can really come in handle and reduce the time needed to load a site. But, its still slow! xD

200++ Photoshop Photo Effects

Have you ever wonder where is that photo effect tutorial you saw the other day and start searching all over the internet but couldn't find what you saw initially? Honestly, i have. That is why i throw them all into this article instead. But i also use these article to gain inspiration on what to do with my photo image. Sometimes we are like a lost bird when it comes to creative design. Hence, putting up links of images can really benefit myself and hopefully people who come across this article too.

Create a Powerful Mental Wave Explosion Effect

wave-explosion

Photo to Pencil Sketch Effect

pencil

Sin City Style Effect

sincity

How To Make Your Own Vector Portraits

vector

Tutorial: Good and Evil Photo Effect

evil

The Making of Mystic Effect

mystic

Transform A Person Into An Alien Effect

alien-photoshop

Reflective Bubbles Effect

3315027133_4f9e8c8241

Crack and Peel Effect

3315027243_4fcabe071f

Expressive Lighting Effect

aura-effect

Displacement Effect

awesome-effect

Vector Composite Effect from a Photo

blabus

Easy Watercolor Painting Effect

cartoon-effect

Twins Effect

clones

Apple Style Portrait Effect

coldplay

Compositing Effect

compositing

Dimension Effect

dimension

Blue Glow Dreamy Effect

dreamy

Ink Drops in Your Digital Compositions Effect

dropink

Super Slick Dusky Lighting Effect

earth effect

Electrifying Energy Beams Effect

electric

Eery-Eye Photo Effect

evil-eye-effect

Fairy Night Eye Effect

Fairy-Night

Fairy tale Effect

fairytale

Make your image look awesome with a few light effects

fewlights

Fire Lines Effect

firelines

Make Perfume Commercial

fragrance

Dirty Grunge Effect

grunge

Coloring Effect

guitar-girl

Photoshop Effect: Focus With Light

hand-light-effect

Speeding Car Effect

car-effect

The Maiden and Hummingbird Photo Manipulation

doll-effects

Design an Epic Fantasy Scene with Photoshop

fantasy-effects

Thermal Photo Effect

flame-effects

Create an Abstract Design with Curved Light Streaks

hand-effect

Dance Photo Effect

hip-hop-effect

Glowing Neon Effect

human-3d-effects

Fantasy Art Scene

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvc2lsZW50by5qcGc=

Sexy Model with Glowing Bubbles Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy8xMHN0ZXBzMi5qcGc=

Glamour model

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9hZG9iZXR1dG9yaWFsei5qcGc=

Create an Amazing A.I. Robot Woman in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9kZXNpZ25yZXZpdmVyLmpwZw==

Impressive Photo Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9waG90b3Nob3A4eC5qcGc=

Make Perfect Selection for Human Object by Utilising Channel Mask Technique in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2R2YXVsdC5qcGc=

Create a Realistic Break-Apart Effect with Debris Brushset in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2R2YXVsdDIuanBn

Create sexy cyborg Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2RlbHV4ZS5qcGc=

Create a Stylish Two-Tone Photo Montage Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2RmYW4uanBn

Design a Stylish Fashion Advert Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy9wc2RmYW4yLmpwZw==

Create a Divine Angel Montage Effect in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy90dXRvcmlhbDkyLmpwZw==

Text Image Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy90dXRvcmlhbHBhcmsuanBn

Dynamic Scene with a Fallen Angel Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9fZWZmZWN0cy90dXRzcGx1czMuanBn

Combine Photo Elements to Create a Surreal Photo Manipulation Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcGhvdG9zaG9wdHV0b3JpYWxzLnBuZw==

Fairy and Sunset Landscape Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHN3aXNoLmpwZw==

Photo Manipulation - Creating a Fantasy Scene

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHNkcm9ja3N0YXIuanBn

The Soft Sea Light

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHNkdG9wLmpwZw==

Awesome Fantasy Style Castle Scene Creation in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvcHNkdmF1bHQuanBn

Fantasy Photo Manipulation Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvdHV0c3BsdXM0LmpwZw==

Fantasy Creature in a Misty Landscape

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvdHV0c3BsdXMuanBn

Create an Out of Bounds Fantasy Illustration Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvdHV0c3BsdXMyLmpwZw==

Making of a Forest Magical Scene

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvMTBzdGVwcy5qcGc=

Making of Urban Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvY2dhcmVuYS5qcGc=

Create a Magic Crystal Ball

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWRvYmV0dXRvcmlhbHouanBn

Warth Best Life

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWRvYmV0dXRvcmlhbHoyLmpwZw==

Fantastic Tree

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWxmb2FydC5qcGc=

Magic lamp in the old room

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWxmb2FydDIuanBn

Fantastic Water Landscape

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvYWxmb2FydDMuanBn

Matte painting

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzLmpwZw==

Magic Book

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzMi5qcGc=

Serenity Prayer

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzMy5qcGc=

Galaxy Angel

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMvZXllc29udHV0b3JpYWxzNC5qcGc=

Badass Bling Effect in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2dvbWVkaWF6aW5lLmpwZw==

Flying Girl in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2FiZHV6ZWVkby5qcGc=

Really cool Eclipse Effect in Photosho

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2FiZHV6ZWVkbzIuanBn

X-MEN movie poster

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2Fkb2JldHV0b3JpYWx6LmpwZw==

How to create a stylish mad lady in photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2Jlc3RwaG90b3Nob3B0dXRvcmlhbHMuanBn

Fantasy light effects in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2RpZ2l0YWxhcnRzb25saW5lMi5qcGc=

Lighting effects in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2RpZ2l0YWxhcnRzb25saW5lMy5qcGc=

Make incredible surreal images

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL2RpZ2l0YWxhcnRzb25saW5lNC5qcGc=

Dazzling Dance Photo Manipulation Effect

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3Bob3Rvc2hvcHR1dG9yaWFscy5wbmc=

Light and Glow Effect In Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3NlY29uZHBpY3R1cmUuanBn

Energize Your Graphics with Abstract Energy Lines

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3R1dG9yaWFsOS5qcGc=

Ps Advanced Splatter Effect Tutorial

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyL3R1dGNhbmR5LmpwZw==

Lighting Effect in Photoshop

L2hvbWUzL3BzZGVsdXhlL3B1YmxpY19odG1sL2ltYWdlcy9zdG9yaWVzL3dlYnR1dHMyLzEwc3RlcHMuanBn

Creative Photoshop Animal King Photo Manipulation Tutorial

anime-king-effects

Robotic Frog

frog

How to Create a Flying Land Illustration On Fire

knight-story-effects

Watercolor Effect

light-girl-effects

Alien Invasion

invasion-effects

Creating Energy Spheres

light-beam

Seriously Cool Photoshop Explosion Effect

light-effect

Lightning from hand

lighting-effects

Adding Light Streaks Effect To A Photo

lights

How To Make Circle Pixels Effect

lines-effect

Giving A Mafia-Look Effect

mafia

Design an Awesome Space Dancer Scene Effect

magic-effects

The Little Mermaid Photo Effect

mermaid

Design a wolf howling at the moon effect

midnight-effects

Light Effect On A Model

modern-effect

How To Turn Your Photo Into Movie-Like Effect

movie-effect

Dynamic Lightning Effect

building

Dark Art Picture Style Effect

night-effect

The Ocean Girl Photo Effect

ocean

How To Make Digital Photos Look Like Lomo Photography Effect

old-effects

Age Progression

old-lady-effect

Creating an Abstract Watercolor Effect

painting-effects

Fiery Photoshop Space Explosion Effect

planet-effect

Add Realistic Rainbow Effect To A Photo

ranbow-effect

Fantastic Disintegration Effect

rawr-effects

Realistic Water Reflection Effect

reflect-effect

Grunge Photo Edges Effect

shouting-effects

Add A Sparkle Trail Effect To A Photo

sparkle

How to Place a Use lighting effects to make photos sparkle

sparkle02

Creating Light Motion Trails & Glowing Sparks Effect

sparks

Christmas Fairy Magic Effect

star-effects

Bringing A Stone Statue To Life Effect

state-effects

How to Turn Humdrum Photos into Cinematic Portraits

storm-effects

Colorful Picture Style Effect

strong-impression

Realistic Tattoos Effect

tatoo-effect

Cool Halftone Effect

text-effect

How to make a Typographic, Retro, Space Face Effect

topology-effect

Photo Editing / Retouching

tragic

How to Apply Textures to Uneven Surfaces

tree-effects

Create a fantasy illustration in Photoshop

unicorn-effects

Urban-Style Piece Of Artwork

urban

Watchmen Effect

watchman-effects

Make an Apple Coldplay Style Ad in Photoshop

welcome-effect

Zombie Effect

zombie-effect

Halftone Dots And Linear Light

3315027899_4deff3e472

Beautiful Lady Effect

3315027947_3b5fe05642

Mosaic, Fill A Photo With Photos Effect

3315028177_dfda4429b6

Creating A Rocking Silhouette

3315028369_d29730bbd1

Make Photos More Suggestive

3315028409_7f18db32d7

Adding Reflections To Sunglasses Effect

3315028555_e6cf210930

Devil's Eye Effect

3315854678_0ee80c73ea

Fantasy Art

3315855042_3dd0fdbdb2

Retro Comic Book Effect

comic-effect

Water effect photo montage

wave

Vibrant Image Effect Using Photoshop

dance-effect

Ghost Effect

ghost

Dramatic gritty effect

Dramatic-gritty-effect

Photo to Illustration Effect

photo-to-illustrator

Turn A Photo Into A Collage Of Polaroids In Photoshop

Collage-Polaroids-Photoshop

Instant Photo To Oil Painting Action

Instant-Photo-To-Oil-Painting-Action

Photo to sketch Effect

soft-contrast-2

Pop Art Silkscreen Effect

pop-art-silkscreen-350

The Louis Daguerre Effect

daguerre-photo-effect-final

Cubism Effect

cubic-effect

Cross-Processing Effect

cross-effect

Create an Illustrated Look From a Photograph

photo-to-drawing

Super mysterious lighting effects for your image

sun-effect

HDR Effect Tutorial

HDR-tutorial

FAKE MODEL PHOTOGRAPHY EFFECT

fake-photography-effect

Photo to stencil Effect

Photo-to-stencil

Transform your Photos into a Beautiful Mosaic

picture-mosaic-14

Panoramas on Steroids Effect

panographyfeature

Pop Art Effect

Pop-Art

Filtering Out Colours

filter-color

City Globe Effect

city-global

Vintage photo effect

Vintage-photo-effect

Selective Sepia Effect

Selective-Sepia

Photoshop Rain Effect

photoshop-rain

Soft Glow Effects

slow-glow-effect

Charcoal Effect

charcoal-drawing-photoshop

High-Key B&W Portrait Effect

high-key01

Horror Film Effect

Horror-Film-Effect

Snow Effect

Snow-effect

HDR - High Dynamic Range Photography

HDR

English Tea can Painting Effect

English-Tea-can-Painting

Realistic Spotlight Effect in Photoshop

Realistic-Spotlight-Effect-Photoshop

Better negative effect

negative-effect

Dave Hill Look Effect

dave-hill-photoshop

Frosted Pixels Effect

Frosted-Pixels

Darklight Photomanipulation

Darklight-Photomanipulation

Blue Print Effect

blue-print-effect

PIXEL STRETCH EFFECT

pixel-stretch

OLD MOVIE EFFECT

old-movie

REALISTIC FOG & MIST EFFECT

realistic-fog-mist-effect

The Night Vision Thing Effect

night-vision-2

A Realist Painting Effect

realistic-painting

Hot & Fiery Photo Effect

Hot-Fiery-Photo-Effect

Trippy Colors Photo effect Tutorial

trippy_color_effect_preview

Digital Painting with Light

Digital-Painting-Light

Displacement Water Effect

Displacement-Water-effect

Creating a 3D effect with image editing software

3d-pop-out

India Movie Look

movie-look

Faking Depth Of Field Effect

Depth_Of_Field

Infrared Photo Effect

infraned-effect

Blurry TV Effect

blurry-tv-effect

PUZZLE PATTERN EFFECT

puzzle-effect

Face painting on cracked wall Tutorial

Face-on-Cracked-wall

Create photo mosaics effect

photo-mosaics

Bourne Ultimatum Color and Motion Blur Effect

Bourne-Ultimatum-Color-and-Motion-Blur

Cast Light From A Window Effect

window-light-effect

Stylized paint effect

Stylized-paint-effect

Night shooting effect

Night-shooting-effect

Give Your Photos a Color Ink Sketch Effect

Color-Ink-Sketch-Effect

Wicked Blast Effect

Wicked-Blast

Fix Perspective Effect

fix-perspective

Sharpen with Edge Mask

sharpen-edge

Making Your Subject Pop Out Of A Photo

photo-pop-out

Telling Stories With Shadows

superman

Digital Pixel Effect

digital-pixel

Tearing A Photo To Reveal Another

tear-effect

Worn, Torn Photo Edges Effect In Photoshop

photoshop-worn-torn-photo-edges

image-hard-light

Mirror Image Effect In Photoshop

photoshop-mirror-image-effect

Placing An Image Inside Of Another In Photoshop

tv-image

Create A Starry Sky In Photoshop

starry-sky

Photo Into a Beautiful Painting

tutorial-how-to-turn-a-photo-into-a-beautiful-painting-in-photoshop

 

Summery

Finally, this article has ended (after 200 tutorial i lost count). This really eats a lot of my time but i think it is worthwhile since i can refer back to it every single time and won't find myself in 'where's that tutorial again' situation. Nonetheless, if any of you are using this too, please throw in more photoshop photo effect tutorial that can benefit us all. Enjoy 🙂

17 JavaScript Form Validation Snippets

Last week i wrote 25 form validation for PHP. I find useful to have more layer of defend as JavaScript might malfunction or disable and cause your validation to fail but the form is still being passed on to our server. Nonetheless, JavaScript validation does provide certain level of restriction and protection for any web application. Especially when web is evolving quickly in this period of time. We are required to validate any data from our user to prevent any harm that can cause damage to our application and businesses. These JavaScript form validation snippets are needed in every form validation and repeating searching for them is unnecessary and slow down development processes. Therefore, you might want to bookmark these snippets for your future needs

Email Validation

Email validation is the most basic validation that any web application would have.

function isEmail(elem, helperMsg){
	var regexp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(regexp.test(elem.value)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var email = document.getElementById('ham_email');
if(isEmail(email, "Invalid Email Format")){
//proceed..
}

URL Validation

URL validation helps to validate whether a particular string is a valid url format.

function isUrl(elem, helperMsg) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	if(regexp.test(elem.value.toLowerCase())){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var link = document.getElementById('ham_link');
if(isUrl(link, "Invalid link")){
//proceed..
}

Username Validation

This function help us validate whether a username contain valid character and length. It accept any underscore, alphabets and numbers within 5-25 characters.

function isValidUsername(elem, msg) {
	var regx = /^[A-Za-z0-9_]{5,25}$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

You can add additional symbols or change the length of the validation easily by alter the regular expression.

In order to use this, we pass in an object and an alert value if it fail.

var username = document.getElementById('username');
if(isValidUsername(username, "Invalid character found on username!")){
//proceed...
}

Password Validation

Here is a simple password strength validation that check the following criteria.

  1. Passwords will contain at least 1 upper case letter
  2. Passwords will contain at least 1 lower case letter
  3. Passwords will contain at least 1 number or special character
  4. Passwords will contain at least 8 characters in length
  5. Password maximum length should not be arbitrarily limited
function isStrongPassword(elem, msg) {
	var regx = /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var password = document.getElementById('password');
if(isStrongPassword(password, "Your password fail the basic strength test. \n1. Passwords will contain at least 1 upper case letter\n2. Passwords will contain at least 1 lower case letter\n3. Passwords will contain at least 1 number or special character\n4. Passwords will contain at least 8 characters in length\n5. Password maximum length should not be arbitrarily limited\n")){
//proceed..
}

Numeric Validation

This validate whether a given string contain a valid numeric value which include both negative value and decimal ones.

function isNumeric(elem, helperMsg){
	var numericExpression = /^[-]?\d*\.?\d*$/;
	if(elem.value.toString().match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var price = document.getElementById('price');
if(isNumeric(price, "Invalid value found")){
//proceed...
}

Text Empty Validation

In every form validation, there is always a need to check whether a particular text box is empty.

function isEmpty(elem, helperMsg){
	if(elem.value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var name = document.getElementById('ham_company');
if(!isEmpty(name, "Please give us your name")){
//proceed...
}

Radio Box Validation

We can determine whether a radio box has been selected using this function.

function hasSelected(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

Drop Down Validation

We also check whether a particular drop down box has its value selected with the following function.
In order to use this, we pass in an object and an alert value if it fail.

var radio = document.getElementById('radio');
if(hasSelected(radio, Please select your gender")){
//proceed...
}
function isSelected(elem, helperMsg){
	if(elem.options[elem.selectedIndex].value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var month = document.getElementById('ham_month');
if(isSelected(month, "Please select a month")){
//proceed...
}

Check Box Validation

We can perform check box validation to see whether a particular check box has been selected through this function.

function hasChecked(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var checkbox= document. getElementsByName('checkbox');
if(checkPhone(checkbox, "Please tick one of the check box")){
//proceed...
}

Phone Validation

This function will validate the following criteria phone number.

  • phone:
    339-4248
    339-42-48
    339 42 48
    339 4248
    3394248
    (095) #phone#
    (095)#phone#
    +7 (095) #phone#
    +7 (095)#phone#
    +7(095) #phone#
    +7(095)#phone#
function checkPhone(elem, msg)
{
	var str = elem.value;
	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
	if (str.match(phone2)) {
   		return true;
 	} else {
 		alert(helperMsg);
		elem.focus();
		return false;
 	}
}

In order to use this, we pass in an object and an alert value if it fail.

var phonenumber = document.getElementById('phonenumber');
if(checkPhone(phonenumber, "Invalid Phone Number")){
//proceed...
}

File Extension Validation

This function validate whether a particular upload string contains a valid extension.

function isAllowedFileExtension(elem, helperMsg){
	var alphaExp = /.*\.(gif)|(jpeg)|(jpg)|(png)$/;
	if(elem.value != "")
	{
		if(elem.value.toLowerCase().match(alphaExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	else
		return true;
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var upload = document.getElementById('ham_upload');
if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only")){
//proceed...
}

IP Validation

Sometimes there is a need to validate whether a particular IP address is valid using JavaScript.

function isValidIPAddress(elem, msg) {
   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   ipaddr = elem.value.toLowerCase();
   if (re.test(ipaddr)) {
      var parts = ipaddr.split(".");
      if (parseInt(parseFloat(parts[0])) == 0) { return false; }
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) > 255) { return false; }
      }
      return true;
   } else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var ip= document.getElementById('ip');
if(isValidIPAddress(ip, "Invalid IP Address")){
//proceed...
}

US Social Security Number Validation

Testing US Social security number can be done with the below function.

function isValidSSN(elem, msg) {
	var value = elem.value.toLowerCase();
	var tmp = false;
    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
    if (!re.test(value)) { tmp = true; }
    var temp = value;
    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
    if (temp.substring(0, 3) == "000") { tmp = true; }
    if (temp.substring(3, 5) == "00") { tmp = true; }
    if (temp.substring(5, 9) == "0000") { tmp = true; }

	if(tmp){
		alert(helperMsg);
		elem.focus();
		return false;
	}else
    return true;
}

In order to use this, we pass in an object and an alert value if it fail.

var ssn = document.getElementById('ssn');
if(isValidSSN(ssn, "Invalid US Social Security Number")){
//proceed...
}

US Zip Code Validation

We can valid US zip code using the following function.

function isValidZipCode(elem, msg) {
   var re = /^\d{5}([\-]\d{4})?$/;
   var value = elem.value.toLowerCase();
   if(re.test(value)){
		return true;
   }else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var zip= document.getElementById('zip');
if(isValidSSN(zip, "Invalid US Zip Code")){
//proceed...
}

Date Validation

This function validate date with a given format.

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || _
      (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else _
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else _
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else _
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

You will use the function this way,

if (!isValidDate(myDateString, "DMY")) { alert("The date is not in the correct format."); }

Time Validation

This function validate time such as

  1. 02:25AM
  2. 00:23PM
  3. 23:45PM
  4. 11:23
  5. etc.
function isValidTime(value) {
   var hasMeridian = false;
   var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [aApP][mM]?)?$/;
   if (!re.test(value)) { return false; }
   if (value.toLowerCase().indexOf("p") != -1) { hasMeridian = true; }
   if (value.toLowerCase().indexOf("a") != -1) { hasMeridian = true; }
   var values = value.split(":");
   if ( (parseFloat(values[0]) < 0) || (parseFloat(values[0]) > 23) ) { return false; }
   if (hasMeridian) {
      if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) ) { return false; }
   }
   if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { return false; }
   if (values.length > 2) {
      if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { return false; }
   }
   return true;
}

Credit Card Validation

This function validate whether a given string format is similar to a credit card type.

function isValidCreditCard(type, ccnum) {
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}

Summary

Usually i will use these code in such a way to validate my form. I find it neat and tidy.

form.onsubmit = validation;
var validation = function(){
	var name = document.getElementById('ham_company');
	var email = document.getElementById('ham_email');
	var link = document.getElementById('ham_link');
	var description = document.getElementById('ham_desc');
	var banner = document.getElementById('ham_banner');
	var month = document.getElementById('ham_month');
	var url = document.getElementById('ham_url');
	var upload = document.getElementById('ham_upload');
	var quiz = document.getElementById('ham_quiz');
	if(isEmail(email, "Invalid Email Format"))
		if(isUrl(link, "Invalid link"))
			if(OneNotEmpty(url, upload, "Either image url or upload must be perform!"))
				if(isAllowedFileExtension(url, "Please provide an image with Gif, Png or Jpg extension Only"))
					if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only"))
						if(isSelected(month, "Please select a month"))
							if(isSelected(banner, "Please select a banner"))
								if(NotEmpty(quiz, "Please answer the quiz"))
									if(NotEmpty(name, "Please give us your name"))
									{
										return true;
									}

	return false;
}

On the other hand, you can always brings up new form validation snippets to share with me in this article. I will love to know 🙂

Inline, Internal or External CSS Style Print First?

It is a common thing for most web beginners to wonder which style will the browser print first when we declare multiple style. Although i have explain previous on the order priority of CSS, i forgotten about the importance of inline, internal and external CSS style that both designers and developers might wonder when they started on web.

Inline CSS

The inline CSS also refer as embedded style is usually mark as the highest priority over internal or external style. An inline style has the highest priority among others but the style can only be apply to an individual element. Here's an example

<div style='height:200px;width:200px;text-align:center;'>Click me!</div>

Inline style may be convenient to write but maintenance work will definitely kill you one day.

External CSS

The external CSS which the style is usually placed on an external file will usually have the lowest priority over these three type.

<link rel="stylesheet" type="text/css" href="http:/hungred.com/external.css">

Nonetheless, sometimes external CSS can have higher priority over the internal CSS in some circumstances.

Internal CSS

Internal CSS are definition declare inside of the HTML document with the style tag,

<style type='text/css'>
div{
height:200px;
width:200px;
text-align:center;
}
</style>

Internal CSS usually have the second highest priority among them. However, it will lose its priority if the external stylesheet declaration is placed at after the internal CSS. Hence,

<link rel="stylesheet" type="text/css" href="http:/hungred.com/external.css">
<style type='text/css'>
div{
height:200px;
width:200px;
text-align:center;
}
</style>

the internal CSS is after the external CSS. Therefore, the internal CSS has a higher priority. On the other hand,

<style type='text/css'>
div{
height:200px;
width:200px;
text-align:center;
}
</style>
<link rel="stylesheet" type="text/css" href="http:/hungred.com/external.css">

when the external CSS is after the internal CSS, the external CSS will have a higher priority.

Priority Sequences

Hence, we can produce a priority sequences of how CSS prioritize our CSS types.

  1. User Style
  2. Inline Style (inside HTML tag)
  3. Internal Style (usually on the HTML head section)
  4. External Style
  5. Browser Default Style

User style (the style that user define for your website) have the highest priority over all other types but as a developer or designer we should only worry about the priority given on inline, internal and external style. Nonetheless, it is also important to know that using !important will also mean that user style priority is overwrite by the HIGHEST priority (which is style declare with !important). That is also the reason why we should try to avoid the use of !important as a developer or designer to avoid any usability problem and utilize order priority in CSS.

Summary

Once we understand how order priority work in CSS, we can easily figure out how CSS cascade all our different styles into one. But one last thing to take note of. The order priority in this link only apply to internal and external style. Hence, if both internal and external have the same exact style definition which order priority in this link will CSS take as the highest priority. The answer lays in this article where we explain on the internal CSS section.

Best way to log details. Database or file log?

Unlike many articles in Hungred Dot Com where i share valuable web development information with my readers, this article is something that required everyone to debate on. Every system will require a logging system (unless it is a crappy system). Regardless is transaction log, result log, database log, error log and etc., there is always a need have a quick, secure and reliable log to store these information for any further investigation. And logging details usually fall into file or database category. We need to look at three important thing to consider a media to log our details. There are performance, security and reliability. Let me elaborate the importance of each point.

Log Performance

Performance, performance performance! This is something we all want to know about. Whether file base log or database log is better? We will be looking at long run where our log gets really huge! Delay and performance problem might arise and which media will be more resistance against such problem. Another good thing to consider between these two media is the extra cost of HTTP request comparing to a read and write and the problem of delay arise from huge size. We won't want to consider the alternative media only after the problem appear don't we?

Log Security

Another thing that every hacker will be interested with is the log file. Valuable information is being stored in our log file and it is necessary to consider how secure can either media gives us. Log file may even carry sensitive details of our customers which was log by our program. Hence, considering the security risk of having plain text and a database is important to prevent security hole in our system environment. Each media will have its own way to further secure its media but which is better?

Log Reliability

Why we bother to have a log file if it is unreliable. This is necessary for a system that is required to keep track of a system that handle important transaction. An unreliable log might miss a log due to various reason such as manual query termination, file lock, database down during logging and etc. It is necessary to have all our log in order to capture important incidents.

Other log criteria

Scalability and flexibility is another thing some of you might want to mention. Migration of server and ease of searching etc. is also points that is important for us to consider as a log that cannot find its detail is consider a useless log.

Database Logging

Performance wise, database might be slower when log amount is small. But once the log amount became a huge amount, database based logging might really be much faster. The problem i can see is that it will fight with other urgent query which has higher priority to be executed and table locking. This is usually resolve by using MySQL Insert Delay operation. Another issue will be latency which cause the delay o of the logging operation. In term of searching database logging surely have the upper hand. Security of the log depends solely on the security of the server and database. There might be risk of SQL injection but usually this should be taken care of by the developers.

In term of reliability, using insert delay will risk the chances of our log getting lost especially if the system is a very active one. In a very busy system every few millisecond time interval there will be additional query that makes the database super busy until the insert delay log are pile up and have to wait till the database is quiet to be active. Hence, any accident such my sql die or forcefully terminated, the log query are gone. Furthermore, additional overhead to delay such insert will degrade MySQL performance by a little.

Log file

Log file is the simplest way to achieve a logging system. Its basically just a few lines of code (depend how paranoid logger are you).  While the greatest advantage is its simplicity, the worst problem of file based logging is searching. Most developers who move to file based logging end up not relaying on logs. But usually this can be overcome with some formatting and regular expression. Performance wise, it should be directly opposite a database logging where smaller size will be better and larger it gets worst. Nonetheless,  theoretically both should be the same in term of opening and closing of file regardless of size. It should be solve easily by utilizing buffer. In term of security, file based logging usually uses plain text file. Knowing the name of the log file is equivalence to exposing to the public (especially open source apps). But this is usually resolve using file permission setting.

Unlike database logging, file based logging doesn't required a call to the database. Hence, everything is done by the server scripting language you are using and operation is complete regardless of whether the connection is down(as long as the request pass from client to server is complete).

The other more critical part to choose file based logging is the problem of file locking where only one person is allowed to open the log file at one time. Hence, in a active system this might really post a big problem where logging is done intensively. The most expensive part in file based logging should be searching. Hence, regular expression can be really handy (or pain in the ass).

Summary

Some uses both file based logging and database logging with a little help from a external batch program. But it really depends on the need and required of your logging system. But my job here is done; I have started the fire. Now its time to heat it up. 😀