kreoton web development

Archive for the ‘Coding’ Category

XX ways to improve your PHP scripts execution time

Tuesday, February 12th, 2008

1. Many same kind of articles says that ‘require_once is expensive’. Ok we know that but what to do? Here is some ways how to include your php files not using ‘require_once’:

  • a) If you need to include object class file check if class not exists and then include:
  • <?php
    	if (!class_exists('testClass'))
    		require '../testClass.php';
    ?>
  • b) If you including simple script or template, define something in included file then check if it is not defined and then include it.
  • <?php
    //include.php
    define('INCLUDE', 1);
    #code ...
    ?>
    <?php
    //script where include file should be included
    if (!defined('INCLUDE'))
    	require 'include.php';
    ?>

2. If you can do not call functions in loop. Top programmers mistake is calling count() or sizeof() functions in for() loop. How to fix this you can find in every ‘XX ways to optimise your PHP code’ articles, but do not do like this:

<?php
	for ($i=0; $i<count($somearray); $i)
	{
		#code
	}
?>

You can fix this code like this:

<?php
	$counter = count($somearray);
	for ($i=0; $i<$counter; $i++)
	{
		#code
	}
?>

Or like this:

<?php
	for ($i=0, $counter = count($somearray); $i<$counter; $i++)
	{
		#code
	}
?>

Not only count() or sizeof() slows your code, I can say that every function called in loop slows yor script. Take a look at example bellow:

<?php
 
function build_home_path ()
{
	$sql = "SELECT value FROM settings WHERE key = 'path' LIMIT 1";
	$res = mysql_query($sql);
	$row = mysql_fetch_assoc($res);
	return $row['value'];
}
 
//build menu
$menu_items = array('home'=>'Home Page', 'about'=>'About Page');
foreach ($menu_items as $path => $title)
{
	echo '<li><a href="'.build_home_path().'/'.$path.'">'.$title.'</a></li>';
}
 
?>

How you see this code is absolutly good, and works fine, but can it be a little more faster? Yes it can be just look at build_home_path() function call. Function build_home_path() is called every loop interation, thats no good because it do just one thing it gets home path ( like http://www.kreoton.net/). Here is solution how to fix it:

<?php
//we can rewrite our loop contents in this way
$menu_items = array('home'=>'Home Page', 'about'=>'About Page');
$home_path = build_home_path();
foreach ($menu_items as $path => $title)
{
	echo '<li><a href="'.$home_path.$path.'">'.$title.'</a></li>';
}
?>

Thats all for this time come back for part 2.

Faster web development with free tools

Friday, December 7th, 2007

Web Server

You don’t really need a web hosting to start coding or designing your new project. You can run simple web server on your own machine. There many software to run server on your machine like:

  • EasyPHP - for small web projects or testing simple scripts (only Windows)
  • XAMPP - you can do with this anything that you can do with real web server (Windows, Mac, Linux and Solaris)
  • WAMP - another server for small projects.

I recommend to install XAMPP this one is best and would fit all your needs.

HTML/PHP editor

There are a lot of editors free to download from internet. I tried many of them:

  • Notepad++ - very popular text editor, with many add ons
  • PSPad - great editor for HTML PHP, there is FTP support and many other features
  • Intype - this is free analog of popular Mac OS text editor TextMate for windows

And many more other my recommendation is Intype, this editor is really has big power for coding.

Mini programs

These mini but powerful programs can help you a lot making design for your new web project.

  • Pixie - use this tool to pick up colors from any location of your screen just point your mouse pointer on any screen element and hit Ctrl+Alt+C and paste color code direct to CSS or PhotoShop
  • JRuler - want to measure on the screen then you need JRuler, with this tool you can measure everything on your screen or web browser

Testing your project

It is good to test your project design on all popular web browsers. Firefox and Opera is free for download. Internet Explorer is already on MS Windows, but there are two versions of Internet Explorer how to test project in both 7 and 6 (and even older) you would need multiple IE’s on your machine.

If you know more great free tools feel free to write of them in comments.

PHP form validation class

Tuesday, June 12th, 2007

Are you bored to write long script to validate you user input? If yes I coded a user input validation PHP class. It’s very flexible and easy to use. This class can validate user e-mail, homepage url, text and other input formats.

Class features:

  • validate and return entered one word (perfect for username and password validation, you can write custom regex for allowed chars, by default it allows only letters);
  • validate and return entered text (may return formated text, strips tags or changes special HTML characters like <, >, & and others to character codes);
  • validate and return integer number input;
  • validate and return float number input;
  • validate and return email input;
  • validate and return www address input;
  • validate and return password and password confirm match input;
  • every form field may have required option;
  • for every form field you may write custom error message;

Example of using validation class:

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
 
<?php
require('validate.class.php');
$VD = new validate();
 
if ($_POST['form_submit'])
{
 
	$VD->validate_data('username', $_POST['username'], array(
			'isOneWord'=>array(
				'min_chars'=>5,
				'max_chars'=>20,
				'regex'=>"/^[a-zA-Z0-9_\.]{1,}$/",
				'required'=>true)
				),
			'Username not valid'
		);
 
	$VD->validate_data('password', $_POST['password'], array(
			'isOneWord'=>array(
				'min_chars'=>6,
				'max_chars'=>15,
				'regex'=>"/^[a-zA-Z0-9_\.]{1,}$/",
				'required'=>true)
				),
			'Password not valid'
		);
	$VD->validate_data('email', $_POST['email'], array(
			'isEmail'=>array(
				'required'=>true)
				),
			'Email not valid'
		);
	$VD->validate_data('details', $_POST['details'], array(
			'isText'=>array(
				'strip'=>true,
				'required'=>true)
				),
			'Details not valid'
		);
	$VD->validate_data('age', $_POST['age'], array(
			'isInteger'=>array(
				'required'=>true
			)),
			'You must fill in your age');
 
	if (count($VD->errors) > 0)
	{
		echo 'Please fix following errors:';
		foreach ($VD->errors as $error)
		{
			echo $error.'<br />';
		}
	}
	else
	{
		$link = mysql_connect($host, $user, $pass);
		mysql_select_db($name, $link);
 
		mysql_query("INSERT INTO users VALUES (
			'".$VD->return['username']."', 
			'".md5($VD->return['password'])."', 
			'".$VD->return['email']."', 
			'".$VD->return['details']."', 
			".$VD->return['age']."
		)");
	}
}
 
?>

Download form validation class

More secure PHP image upload class tutorial

Friday, June 8th, 2007

In the internet are many php image upload tutorials, but most of them are not so secure. In this tutorial i try to teach you how to write not very complex but secure image upload class. First of all we should define class ant it variables:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
class image_upload
{
	var $tmp_image;
	var $max_file_size = 100000;
	var $max_width = 800;
	var $max_height = 600;
	var $allow_types = array(
'image/jpeg', 
'image/png', 
'image/gif'
);
var $errors;
}
?>

For variables $max_file_size, $max_width, $max_height and $allow_types I assigned default values. There are two more variables its $errors for error printing and $tmp_image for $_FILES[’xxxx’] global variable.

Now then we have defined class and variables we can make some standard functions for image upload class. First we need to know if given file is really image so we use function exif_imagetype() witch reads firs file bytes and returns true if file is image else it returns false. (Note: exif_imagetype() function will work only if module exif is installed in server.)

1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
function is_image ()
{
	if (exif_imagetype($this->tmp_image['tmp_name']))
	{
		$this->errors[] = 'Uploaded file is not image';
		return true;
	}
	else
	{
		return false;
	}
}

To check uploaded image type (mime type) i use next function. It searches for uploaded image type in $allow_types types array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function is_type ()
{
	if (in_array($this->tmp_image['type'], 
$this->allow_types))
	{
		return true;
	}
	else
	{
		$this->errors[] = 'Image type is 
not acceptable';
		return false;
	}
}

Next I check if image is suitable size:

1
2
3
4
5
6
7
8
9
10
11
12
function is_size ()
{
	if ($this->tmp_image['type'] <= $this->max_file_size)
	{
		return true;
	}
	else
	{
		$this->errors[] = 'Image file size is too big';
		return false;
	}
}

To check image dimensions I call getimagesize() function it returns array with image parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function is_dimensions ()
{
	$size = getimagesize($this->tmp_image['tmp_name']);
	$width = $size[0];
	$height = $size[1];
	if ($width <= $this->max_width && 
$height <= $this->max_height)
	{
		return true;
	}
	else
	{
		$this->errors[] = 'Image is too height 
or too width';
		return false;
	}
}

Finally I wrote image upload function it has two parameters $dest – upload destination and $safe for safe image upload witch by default is false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function upload_image ($dest, $safe=false)
{
	if ($safe)
	{
		$status = true;
 
		$status = $this->is_image();
		$status = $this->is_type();
		$status = $this->is_size();
		$status = $this->is_dimensions();
 
		return ($status)?move_uploaded_file(
$this->tmp_image['tmp_name'], $dest)
:false;
	}
	else
	{
		return move_uploaded_file(
$this->tmp_image['tmp_name'], $dest);
	}
}

Now class is ready for use. For class test I wrote a simle script.

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
<?php
 
include('upload.class.php');
 
$IM = new image_upload();
 
if ($_FILES['photo'])
{
	$IM->tmp_image = $_FILES['photo'];
 
	if ($IM->upload_image($_SERVER['DOCUMENT_ROOT'].
'/tnimg/'.$IM->tmp_image['name'], true))
	{
		echo 'Image uploaded';
	}
	else
	{
		foreach ($IM->errors as $error)
		{
			echo $error.'<br />';
		}
	}
}
 
?>
<form method="post" enctype="multipart/form-data" action="">
	<label for="photo">Photo file</label>
	<input type="file" name="photo" />
	<input type="submit" name="submit" value="Upload" />
</form>

Digg.com style pagination function

Tuesday, June 5th, 2007

I introduce nice Digg.com style pagination function. This pagination function is very flexible and easy to implement in all kind of scripts. All you have to do is to set current page parameter, total pages parameter and pagination format. I will give you an example:

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
<?
//include paginate funtion
include('paginate.php');
 
//get total pages number
$total = $db['result']['total_pages'];
 
//get curent page
$page = $_GET['p'];
 
//formate pagination layout
 
$format_pg = array (
	'start_tag'	=> '<ul>',
	'close_tag'	=> '</ul>',
	'a_open'	=> '<li>',
	'a_close'	=> '</li>',
	'a_curent'	=> ' style="color:red"',
	'url_q'		=> '?p=%d',
	'lang_next'	=> 'NEXT',
	'lang_previous'	=> 'PREVIOUS',
	'a_space'	=> '...',					
	);
 
//finaly print pagination
 
echo paginate($page, $total, $format_pg);
 
?>

Paginate function is free. To download paginate function hit following link:

Download paginate Rate it On HotScripts.com