You Are Here Home

jQuery UI Dialog And The Enter - Return Key Problem

This is another post for my ‘Annoying Stuff’ collection and this one is very, so very annoying…

The problem is that jQuery UI, supports forms in dialogs but the problem is that a user can’t hit ‘Enter’ to submit the form, it will break everything, a user has to actually hit the ‘Submit’ (or whatever) button manually. This make the whole thing completely useless unless you make some changes that are basically tweaking the internals of jQuery UI, which is ugly and can break if they change things around but sadly this is the only solution for now.

Assuming that you use the same syntax jQuery UI suggests to create your form, the fix is something like this:

$('.dialog').find('input').keypress(function(e) {
	if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
		$(this).parent().parent().parent().parent().find('.ui-dialog-buttonpane').find('button:first').click(); /* Assuming the first one is the action button */
		return false;

You might have to modify it a tiny bit, if that’s the case, you most likely have to change the part $(’.dialog’) so that it selects the right container that wraps the form…

Comments (0)   Filed under: Annoying Stuff, JavaScript, Programming, Web Design, Web Development, jQuery   Posted by: Codehead on February 18, 2010

document.getElementById On All Browsers - Cross browser getElementById

Here is a little JavaScript function that gets an object according to it’s id and it’s cross browser.

   * Get an object, this function is cross browser
   * Usage: 
   * var object = get_object(element_id);
   * @Author Hamid Alipour
  function get_object(id) {
   var object = null;
   if (document.layers) {   
    object = document.layers[id];
   } else if (document.all) {
    object = document.all[id];
   } else if (document.getElementById) {
    object = document.getElementById(id);
   return object;
Comments (0)   Filed under: JavaScript, Web Browsers, Web Development   Posted by: Codehead on February 8, 2010

Script For Counting Number Of Lines Of Code In Your Website; Composite Design Pattern

This is another thread from our forums which we are closing down soon.

This script will count the number of lines in all of your source files recursively. Just place it in any folder and point your browser to it and it will count all the lines including sub directories.

It might run out of memory if your application is huge and your PHP memory limit is low. For me, it counted 97,000 lines in our last project with no problems.

You also have an option to exclude file extensions and directories.

The other thing about this script is that it is a great little example of composite design pattern in action; every directory is an object that will count all the lines (in the files) in it and asks it’s sub directories to do the same, then the sub directories also repeat the same process.

	 * Counts the lines of code in this folder and all sub folders
	 * You may not sell this script our remove these header comments
	 * @author Hamid Alipour,
	define('SHOW_DETAILS', true);
	class Folder {
		var $name;
		var $path;
		var $folders;
		var $files;
		var $exclude_extensions;
		var $exclude_files;
		var $exclude_folders;
		function Folder($path) {
			$this -> path 		= $path;
			$this -> name		= array_pop( array_filter( explode(DIRECTORY_SEPARATOR, $path) ) );
			$this -> folders 	= array();
			$this -> files		= array();
			$this -> exclude_extensions = array('gif', 'jpg', 'jpeg', 'png', 'tft', 'bmp', 'rest-of-the-file-extensions-to-exclude');
			$this -> exclude_files 	    = array('count_lines.php', 'rest-of-the-files-to-exclude');
			$this -> exclude_folders 	 = array('_private', '_vti_bin', '_vti_cnf', '_vti_log', '_vti_pvt', '_vti_txt', 'rest-of-the-folders-to-exclude');
		function count_lines() {
			if( defined('SHOW_DETAILS') ) echo "/Folder: {$this -> path}...\n";
			$total_lines = 0;
			$this -> get_contents();
			foreach($this -> files as $file) {
				if( in_array($file -> ext, $this -> exclude_extensions) || in_array($file -> name, $this -> exclude_files) ) {
					if( defined('SHOW_DETAILS') ) echo "#---Skipping File: {$file -> name};\n";
				$total_lines += $file -> get_num_lines();
			foreach($this -> folders as $folder) {
				if( in_array($folder -> name, $this -> exclude_folders) ) {
					if( defined('SHOW_DETAILS') ) echo "#Skipping Folder: {$folder -> name};\n";
				$total_lines += $folder -> count_lines();
			if( defined('SHOW_DETAILS') ) echo "\Total lines in {$this -> name}: $total_lines;\n\n";
			return $total_lines;
		function get_contents() {
			$contents = $this -> _get_contents();
			foreach($contents as $key => $value) {
				if( $value['type'] == 'Folder' ) {
					$this -> folders[] = new Folder($value['item']);
				} else {
					$this -> files[]   = new File  ($value['item']);
		function _get_contents() {		
			$folder = $this -> path;
			if( !is_dir($folder) ) { 
				return array();
			$return_array = array();
			$count		  = 0;
			if( $dh = opendir($folder) ) {
				while( ($file = readdir($dh)) !== false ) {
					if( $file == '.' || $file == '..' ) continue;													
					$return_array[$count]['item']	= $folder .$file .(is_dir($folder .$file) ? DIRECTORY_SEPARATOR : '');
					$return_array[$count]['type']	= is_dir($folder .$file) ? 'Folder' : 'File';
			return $return_array;
	} // Class
	class File {
		var $name;
		var $path;
		var $ext;
		function File($path) {
			$this -> path = $path;
			$this -> name = basename($path);			
			$this -> ext  = array_pop( explode('.', $this -> name) );
		function get_num_lines() {
			$count_lines = count(file($this -> path));
			if( defined('SHOW_DETAILS') ) echo "|---File: {$this -> name}, lines: $count_lines;\n";
			return $count_lines;
	} // Class
	$path_to_here = dirname(__FILE__) .DIRECTORY_SEPARATOR;
	$folder 		  = new Folder($path_to_here);
	echo 'Total lines of code: ' .$folder -> count_lines() ."\n\n";
Comments (0)   Filed under: Design Patterns, Fun, PHP, Programming, Web Development   Posted by: Codehead on

Some Fun Stuff

1 - Did you know that there were only 300 years of peace on Earth in total?

2 - GPS satellites have atomic clocks that tick at around a few billion times per second, did you know that their clocks tick a little faster than the clocks on earth? This is what Albert Einstein predicted, clocks that are closer to a strong source of gravity tick slower!!!!

3 - Did you know that an unknown flying object followed Apollo 11 along it’s way to the moon? If you don’t believe me, listen to Buzz Aldrin talking about it:

4 - Did you know that there are 100,000 little machines inside each of our cells?

5 - Did you know that some people who we thought that were in vegetative state are actually aware but can’t communicate?

Comments (0)   Filed under: Fun, General   Posted by: Codehead on February 6, 2010

onMouseOut fix on nested elements - JavaScript

When you have nested elements and you add an onMouseOut event handler to the parent element, browsers trigger onMouseOut event when mouse pointer hovers it’s child elements.
While this is a standard behaviour, for one project I needed to write a code to override this behaviour.
With this code, when you mouse over the child elements, onMouseOut event will be ignored.

You can download this code here:

You can test it here:

This code is cross browser and here is how to use it:

<script language="javascript" type="text/javascript" src="fixOnMouseOut.js"> </script>
<div onMouseOut="fixOnMouseOut(this, event, 'JavaScript Code');"> 
   So many child elements
Comments (0)   Filed under: JavaScript, Web Design, Web Development   Posted by: Codehead on February 3, 2010

PHP MySQL Web Development Security Tips - 14 tips you should know when developing with PHP and MySQL

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

PHP MySQL Web Development Security Tips - 14 tips you should know when developing with PHP and MySQL

I read about many of these points in books and tutorials but I was rather lazy to think about many of them initially learned some of these lessons the hard way. Fortunately I didn’t lose any major data over security issues with PHP MySQL, but my suggestion to everyone who is new to PHP is to read these tips and apply them *before* you end up with a big mess.

1. Do not trust user input
If you are expecting an integer call intval() (or use cast) or if you don’t expect a username to have a dash (-) in it, check it with strstr() and prompt the user that this username is not valid.

Here is an example:

$post_id = intval($_GET['post_id']);
mysql_query("SELECT * FROM post WHERE id = $post_id");

Now $post_id will be an integer for sure :)

2. Validate user input on the server side
If you are validating user input with JavaScript, be sure to do it on the server side too, because for bypassing your JavaScript validation a user just needs to turn their JavaScript off.
JavaScript validation is only good to reduce the server load.

3. Do not use user input directly in your SQL queries
Use mysql_real_escape_string() to escape the user input. recommends this function: (well a little different)

  function escape($values) {
   if(is_array($values)) {
    $values = array_map('escape', $values);
   } else {    
    /* Quote if not integer */
    if ( !is_numeric($values) || $values{0} == '0' ) {
     $values = "'" .mysql_real_escape_string($values) . "'";
   return $values;    

Then you can use it like this:

$username = escape($_POST['username']);
mysql_query("SELECT * FROM user WHERE username = $username"); /* escape() will also adds quotes to strings automatically */

4. In your SQL queries don’t put integers in quotes
For example $id is suppose to be an integer:

$id = "0; DELETE FROM users"; 
$id = mysql_real_escape_string($id); // 0; DELETE FROM users -  mysql_real_escape_string doesn't escape ;
mysql_query("SELECT * FROM users WHERE id='$id'");

Note that, using intval() would fix the problem here.

5. Always escape the output
This will prevent XSS (Cross Site Scripting) attacks, imagine you receive and save some data from a user and you want to display this data on a web page later (maybe his/her bio or username) and the user puts this bit of code in the input field along with his bio:


If you display the raw user input on a web page this will be very ugly, it can even be worse if a user inputs this code instead:


With this, an attacker can steal cookies from whoever visits that certain page (containing bio etc.) and this includes session cookies with session IDs in them so the attacker can hijack your users’ sessions and appear to be logged in as other users.

When displaying user input on a page use htmlentities($user_bio, ENT_QUOTES, ‘UTF-8′);

6. When uploading files, validate the file mime type
If you are expecting images, make sure the file you are receiving is an image or it might be a PHP script that can run on your server and does whatever damage you can imagine.

One quick way is to check the file extension:

$valid_extensions = array('jpg', 'gif', 'png'); // ...
$file_name  = basename($_FILES['userfile']['name']);
$_file_name = explode('.', $file_name);
$ext        = $_file_name[ count($_file_name) - 1 ];
if( !in_array($ext, $valid_extensions) ) {
 /* This file is invalid */

Note that validating extension is a very simple way, and not the best way, to validate file uploads but it’s effective;
simply because unless you have set your server to interpret .jpg files as PHP scripts then you are fine.

7. If you are using 3rd party code libraries, be sure to keep them up to date
If you are using code libraries like Smarty or ADODB etc. be sure to always download the latest version.

8. Give your database users just enough permissions
If a database user is never going to drop tables, then when creating that user don’t give it drop table permissions, normally just SELECT, UPDATE, DELETE, INSERT should be enough.

9. Do not allow hosts other than localhost to connect to your database
If you need to, add only that particular host or IP as necessary but never, ever let everyone connect to your database server.

10. Your library file extensions should be PHP
.inc files will be written to the browser just like text files (unless your server is setup to interpret them as PHP scripts), users will be able to see your messy code (kidding:)) and possibly find exploits or see your passwords etc.
Have extensions like or have a .htaccess file in your extension (templates, libs etc.) folders with this one line:

deny from all

11. Have register globals off or define your variables first
Register globals can be very dangerous, consider this bit of code:

if( user_logged_in() ) {
 $auth = true;
if( $auth ) {
 /* Do some admin stuff */

Now with register globals on an attacker can view this page like this and bypass your authentication:

If you have registered globals on and you can’t turn it off for some reason you can fix these issues by defining your variables first:

$auth = false;
if( user_logged_in() ) {
 $auth = true;
if( $auth ) {
 /* Do some admin stuff */

Defining your variables first is a good programming practice that I suggest you follow anyway.

12. Keep PHP itself up to date
Just take a look at [url][/url] and see release announcements and note how many security issues they fix on every release to understand why this is important.

13. Read security books
Always find new books about PHP security to read; you can start by reading the 4th book in the Learning PHP Post, which is one of the best books on PHP security and the author is a member of the PHP team so he knows the internals very well.

14. Contribute to this list :)
Feel free to reply to this thread and add to this list, it will be helpful for everyone!


Comments (1)   Filed under: PHP, Programming, Web Development   Posted by: Codehead on February 2, 2010

Learning PHP - best PHP books

We are closing down our forums, it’s time to move on, but we are keeping some important threads, here are the AJAX tutorials…

Learning PHP - best PHP books

PHP and MySQL Web Development (4th Edition) (Developer’s Library) (Hardcover)
by, Luke Welling and Laura Thomson

This book is one of the best books on PHP and MySQL. It starts with introductions to PHP and MySQL and then shows you how to write common applications from scratch using these technologies. You will learn how to write a shopping cart, a content management system (CMS), a web based email service, a mailing list manager, a forum application, and more.
Some other useful topics covered in this book are:
How to run an E-Commerce site, Session management, user login and registration, generating images and PDF documents on the fly with PHP, using network protocols with PHP, Object Oriented Programming (OOP), regular expressions, etc.

Advanced PHP Programming
by, George Schlossnagle

This book will teach you advanced techniques required to make a large scale web application (web site), there are many advanced topics covered in this book such as:
Various caching techniques using PHP, unit testing, good API design, interacting with remote services, Object Oriented Programming (OOP) through design patterns, Session handling, and more.

PHP|Architect’s Guide to PHP Design Patterns
by, Jason E. Sweat

This book covers many of the Design Patterns that are common in developing websites and is one of the first PHP Design Patterns books. Code samples are in PHP4 and PHP5.
The book covers 16 different design patterns including:
The ValueObject Pattern, The Factory Pattern, The Singleton Pattern, The Registry Pattern, The MockObject Pattern, The Strategy Pattern, The Model-View-Controller Pattern, and many more.

PHP|Architect’s Guide to PHP Security
by, Ilia Alshanetsky

This book will teach you how to make secure and reliable web applications, the author is one of the contributors to PHP programming language core.
Topics covered are: Input validation, Cross-Site Scripting (XSS) attacks prevention, Command Injection attacks prevention, SQL Injection attacks prevention, Code injection attacks prevention, and more.
This is a MUST read book for PHP developers.

Mastering Regular Expressions (3rd Edition)
by, Jeffrey E F Friedl

This book is the best book on Regular Expressions. If you’re having trouble learning Regular Expressions,this book will help you grasp the concept and master them.
Plus, the 3rd edition has an entire chapter dedicated to PHP.

Comments (0)   Filed under: PHP, Programming, Web Development   Posted by: Codehead on

I Know Which Tablet I Want

OK, if you are an Apple fan, don’t be mad at me, I like Apple but I don’t like the spooky-dishonesty stuff…

To be honest, some Apple fans are kind of scary, have you ever seen their comments on YouTube or elsewhere? It’s like Apple is their religion and Steve Jobs is their profit, no wonder… :)

Anyways, things like this bother me a lot:

1 - Showing that the device supports Flash in the ads when in reality it doesn’t, do you realise someone big in that company said “Let’s make it look like it supports Flash in the ads!”???

2 - Steve Jobs said that they designed the A4 chip “right here at Apple” but in reality it is a ARM Cortex chip!!!!

On the other hand, there is going to be a very, very interesting product out soon, it’s HP Slate, the name is kind of lame but it will be running a full version of Windows 7 and under the hood, it has a NVIDIA Tegra 2, which is a very cool chip; it has dual ARM Cortex 1GHz CPUs!

I have a big laptop for work, but I have a little one that I carry around EVERYWHERE with me and it’s very handy, for watching videos and stuff other than work. I was hoping that the iPad could replace that but it didn’t turn out to be that way, HP Slate on the other hand, will do exactly that.

Sorry Apple…

Comments (0)   Filed under: Apple, Fun, General, Operating Systems, Technology   Posted by: Codehead on January 30, 2010

I Want An iPad - NOT!

Ignore my last post, the more I know about it, the more problems I have with this pretty device…

Here are my mail reasons:

1 - It doesn’t have the OSX, the OS is like the one on iPhone.
2 - No multitasking support.
3 - No Flash support!!!!
4 - No camera.

It’s basically a giant iPhone with less features!!

Sadly, Apple got it wrong this time. I also noticed that Steve Jobs wasn’t very excited when he introduced it, it wasn’t like the iPhone keynote, maybe he wasn’t very pleased with it either.

It’s too bad…

Comments (0)   Filed under: Apple, Fun, General   Posted by: Codehead on January 29, 2010

I Want An iPad

I’m not an apple customer, I’ve been thinking about switching to Mac for a while but that requires Mac based software for our work so I’m not ready yet.

But seeing Steve Jobs introduce the iPad, we’ve decided we each want one!

I love everything about this device, I don’t know who will buy a Netbook or a Kindle, or at least I wouldn’t…

There are some things that I like to see on this device, one is a complete Mac-like OS (rather than iPhone) although I know it’s OS 10 already but it would be really nice to have that. The other thing is a camera but I will buy one regardless of these features.

The only thing that disappoints me about this device is that, I have to wait 2-3 months for it to come out, I will write more as soon as I have it.

Comments (0)   Filed under: Apple, Fun, General, Operating Systems   Posted by: Codehead on January 28, 2010
Older Posts »