Thursday, August 26, 2010

Interchange values of two variables without using third variable

$a = 5;
$b = 3;
$a = $a*$b; //result $a = 5*3 = 15
$b = $a/$b; //result $b = 15/3 = 5
$a = $a/$b; //result $a = 15/5 = 3

Thursday, August 19, 2010

APACHE

Apache Bench marking:

How will you do the apache bench for 10 concurrent users?

ab -n 100 -c 10 http://localhost/projects/test.php > test1.txt &

some options:
-A auth-username:password
Supply BASIC Authentication credentials to the server. The username and password are separated by a single : and sent on the wire base64 encoded. The string is sent regardless of whether the server needs it (i.e., has sent an 401 authentication needed).
-c concurrency
Number of multiple requests to perform at a time. Default is one request at a time.
-C cookie-name=value
Add a Cookie: line to the request. The argument is typically in the form of a name=value pair. This field is repeatable.
-k
Enable the HTTP KeepAlive feature, i.e., perform multiple requests within one HTTP session. Default is no KeepAlive.
-n requests
Number of requests to perform for the benchmarking session. The default is to just perform a single request which usually leads to non-representative benchmarking results.
-p POST-file
File containing data to POST.
-t timelimit
Maximum number of seconds to spend for benchmarking. This implies a -n 50000 internally. Use this to benchmark the server within a fixed total amount of time. Per default there is no timelimit.



MYSQL

MySQL performance Tips

Avoid doing SQL queries within a loop.

MySQL

* MySQL is interpreted from right to left so you should put the most significant limiters as far to the right as possible.

* Only select fields you need, instead of selecting * (everything).

* Don't put things that changes very rarely in the database, instead put it in a global array in some include file.

* Use indexes on the columns in the WHERE clause and on the columns you want to ORDER BY.

* Indexes are great if you search the table alot, but it slows down insertion.

* Use the EXPLAIN command to analyze your indexes.

* If you only want one line as a result from the database you should always use LIMIT 1. This way mysql stops searching when it finds the first line instead of continuing through the whole database, only to find that there weren't any more lines that matched the query.

* If you use $line = mysql_fetch_array($result) you'll get two ways of accessing the columns, $line[0] and $line['columnname']. If you only use the $line['columnname'] you should use $line = mysql_fetch_assoc($result) instead, then there will not be any $line[int index] array.

* Sometimes mysql_free_result() end up wasting more memory than it saves. Check the difference with memory_get_usage().

* Don't ask the database for the same stuff over and over again, save the result.

* Use NOT NULL as default value as much as you can, it speeds up execution and saves one bit.

* Use datatypes that fits your data, not too large. For example, INT can hold values up to 4294967295 unsigned, which is often unnecessarily big. Use MEDIUMINT or SMALLINT where applicable.

* Make use of the default values, only insert values that differs from the default values to speed up the insertion.

Friday, August 13, 2010

Joomla Interview Questions

What is Joomla

Joomla! is a content management system platform for
publishing content on the World Wide Web and intranets as
well as a Model–view–controller (MVC) Web Application
Development framework.
---Joomla! came into being as the result of the fork of
Mambo by the development team on August 17, 2005.
---Open Source
---Customize modules
---Built-in modules & plugins
---Develop by PHP
---MySql Support
---Admin & User Section
---User Management
---Media Manager
---Language Manager
---Banner Management & many more...

What are Positions?
Site templates divides the "pages" displayed on a site into a series of positions, each with a different name.

You can view the location of positions in your default template from the administrator go to Site =>Preview=>Inline with Positions.

You can annotate your positions through the administrator (backend). Go to Site=>Template Manage=>Module Positions.

You can add or remove positions by modifying your template html.

You assign a module to a position using the module manager.

Modules=>Site Modules
On the left side of the page, on the third line, there is a drop down menu that lets you select the position.

Notes:
Modules that are not pubished will not display.
Modules can be assigned to unused positions (positions not in the template) if you want to have them published but not displayed in a position (for example, if you want to display a module in content).
Multiple modules may be assigned to the same position. They will be displayed in the order shown for modules in that position in the module manager.
If you want to display a module in more than one position, use the module manager to copy the module and assign the copy to the second position.

How do I change the favicon?

The joomla favicon is stored in the /images folder. The file is called favicon.ico. By definition a favicon must be 16x16 pixels.
If you wish to use your own favicon, rename the default joomla favicon.ico file and put your file with that name in the images directory.

Alternatively, you can change the favicon in the Joomla! global configuration Site tab (on the bottom).

Depending on your browser, you may not see the icon immediately. This is because the favicons are cached, which is why they can appear in your bookmark list. So, to see your favicon, you will need to clear your browser cache.

What are section, categories and content items?
Joomla! is a content management system. Sections and categories allow you to organize your content.

The basic structure is:
Sections include Categories.
Categories include content items.

Section A
Category A1
content items
Category A2
content items
Category A3
content items

Section B
Category B1
content items
Category B2
content items
Category B3
content items

Section C

Category C1
content items
Category C2
content items
Category C3
content items

The content items are what you would think of as web pages in a traditional html site.

Both section and category "pages" can be created to serve (more or less) as the home pages for the categories and sections, respectively.

Although it makes sense to organize your work into categories and sections, you do not need to show these to your users. Using your menus, you can link directly to sections, categories and content items. You can also select numerous options for the display of content associated with each type of link.

What determines what is shown on my frontpage?

Frontpage is a component that is part of the core of Joomla!, like the front page of a newspaper, it shows (usually) multiple pieces of content arranged in some way.

When you install Joomla! the front page component is by default set as the homepage of your site (that is it is the first link on your Main Menu) but front page does not have to be your "home" page.

What exactly appears on the front page and how it is laid out is controlled in two ways. First, if you open the menu link in your menu manager in the backend there are numerous parameters that control the number of items shown, the number of columns etc.

To control which items are shown you must also indicate that an item should be placed on the front page by editing the parameters for the content item. In the backend this will be indicated by a check mark in the front page column of the list of content items.

In addition, you can use the front page manager (in the content menu of the backend) to control the publication dates and other variables for content items that are on the front page.

How do I change the image(s) in my template?
One common template change is to use your own graphic/image. Simple graphics (not banners) are linked in the html file. Simply change the reference to the image of your choice in the html file of your template. In the adminsitrative interface do this by going to Site =>Template manager and then selecting your template. Click the icon for html.

Keep in mind that it if it is a different size than the original image this may change the appearance of the site in unexpected ways.

Additional information:

The images for a given template are generally located in this folder:
/templates/templatename/images (Substitute the name of the template you are using in place of "templatename").

A trick for finding the name of the image is to put your cursor over it and click right. Select view image. This will display the image and give its full url. Sometimes the images are background images. This is viewable in Firefox or you can look for the background tag in your page source.

How to upload an image:

There are many ways to upload images. Which one you use will depend on your host and server.
1. You can use an ftp client.
2. You can use a cpanel file manager.
3. You can use the media manager.
4. You can use various extensions that allow uploading, including joomlaexplorer and galleries.

How do I remove the page title from the front page of my site?
# First log into the administrative back end.
# On the top menu click "Menu"->"mainmenu"
# Click "Home".
# On the right side of the screen in the parameters section, locate the “Page Title” parameter that is next to the radio buttons “Show” and “Hide”.
# Click the “Hide” radio button.
# Click the “Save” button to make your change permanent.

How do I eliminate the pathway or breadcrumbs?

In this case the breadcrumb for that page would look like: "Home >> Books >> Pages >> New Page".

If you wish to eliminate the pathway entirely, edit your template html (index) file. Usually it will look like this:




If you wish to eliminate it on a specific page, such as just the home page, you can modify the template in this way:
New line:if($option != "" && $option != "com_frontpage")
New line:{
New line:?>
Existing:

Existing:
Existing:

New line:}
New line:?>
Understanding: The first line says that if the option in the url does not equal com_frontpage (!="com_frontpage") display the pathway. In php ! means not.

What are components?

Content elements or applications that are usually displayed in the center of the main content area of a template. This depends on the design of the template in use.
Components are core elements of Joomla!’s functionality. These core elements include Content, Banners, Contact, News Feeds, Polls and Web Links.
Members of the Joomla! community produce third party Joomla! components on a continuous basis.
They are freely available to download from http://extensions.joomla.org/ and a number of other web sites.

What are modules?

Modules extend the capabilities of Joomla! giving the software new functionality. Modules are small content items that can be displayed anywhere that your template allows it to be displayed by assigning them to positions and pages through the module manager in the administrative interface.
Modules are installed in the Admin Section. Joomla! modules may include: Main Menu, Top menu, Template Chooser, Polls, Newsflash, Hit Counter, etc.
Members of the Joomla! Community produce Joomla! modules on a continuous basis. Many are freely available at http://forge.joomla.org/ for download.


What is the difference between Joomla and Drupal?

Drupal use smarty template where as on the other hand
Joomla dose not

Joomla uses plugin and modules whereas Drupl has module only

In drupal php code can be written directly whereas in
Joomla you need to install plugin for php support

Drupal is SEO Friendly whereas in Joomla you need to buy a plugin.

Drupal use smarty where as Joomla use his own code format.

In Druapl we can create multiple website with single installation.


Joomla! Features:

Completely database driven site engines
*
News, products or services sections fully editable and manageable
*
Topics sections can be added to by contributing authors
*
Fully customizable layouts including left, center and right menu boxes
*
Browser upload of images to your own library for use anywhere in the site
*
Dynamic Forum/Poll/Voting booth for on-the-spot results
*
Runs on Linux, FreeBSD, MacOSX server, Solaris and AIX



What are some real world examples of what Joomla! can do?

Joomla is used all over the world to power Web sites of all shapes and sizes. For example:

* Corporate Web sites or portals
* Corporate intranets and extranets
* Online magazines, newspapers, and publications
* E-commerce and online reservations
* Government applications
* Small business Web sites
* Non-profit and organizational Web sites
* Community-based portals
* School and church Web sites
* Personal or family homepages

Thursday, August 12, 2010

HTML5 Video Tutorials

http://www.youtube.com/watch?v=siOHh0uzcuY&feature=player_embedded

Wednesday, August 11, 2010

Performance Tuning your website

1.Top Ten Web Performance Tuning Tips

Check for standards compliance by using Weblint or other HTML checking tools.

Content that conforms to the HTML 4.0 standard will load faster and work in every browser because the browser then knows what to expect. Note that Microsoft-based tools create content that does not even use the standard ASCII character set, but instead uses many proprietary Microsoft characters that will display in Netscape as question marks and can slow down rendering.

Minimize the use of JavaScript and style sheets.

JavaScript is a major source of incompatibility, browser hangs, and pop-up advertising. Style sheets require separate downloads before the page can be displayed. There are some nice features to both JavaScript and style sheets, but at a big cost. Life is better without them.


Turn off reverse DNS lookups in the Web server.

If left on, reverse DNS will log a client's machine name rather than IP address, but at a large performance cost. It is better left off. You can always run log analysis tools which look up the names later.
#

Try out a free analysis tool.

I've provided a free analysis tool at my Web site that can tell you whether or not your bottleneck is in DNS, or because of connection time or content size, or is on the server side. Work on improving the slowest part first.
#

Use simple servlets or CGI.

Use simple servlets, CGI, or your Web server's API rather than any distributed object schemes like CORBA or EJB. Distributed object schemes are intended to improve a programmer's code-writing productivity, but they do so at an unacceptable cost in performance for end-users.
#

Get more memory.

Your Web server, middleware, and database all will probably do better with more memory, if they still use their hard disks frequently. Hard disks are literally about a million times slower than memory, so you should buy more memory until the disks are phased out.
#

Index your database tables well.

Spectacular improvements are possible if you are inadvertently doing full-table scans on every hit of a particular URL. Indexes allow you to go directly to the data you need.
#

Make fewer database queries.

If you can cache content in your middleware or servlets, do it. Making connections to a database and using those database connections is typically a bottleneck for performance.
#

Look for packet loss and retransmission.

There are many network snooping and monitoring tools to help you do this. Intermittent slowness is often due to packets being lost or corrupted. This is because a time-out period needs to pass before the packet is retransmitted.

Ref: http://www.oreillynet.com/pub/a/javascript/2002/06/27/web_tuning.html

Wednesday, August 4, 2010

OOPS General

Overloading / Overriding:
Overloading is about creating multiple methods with the same name, but different signatures, in the same scope.

Overriding is about changing the behavior of a certain method in the child class from the way it is behaving in the parent class.

Abstraction:

Abstraction means to show only the necessary details to the client of the object.
Eg:
1) Do you know the inner details of the Monitor of your PC? What happen when you switch ON Monitor? Does this matter to you what is happening inside the Monitor? No Right, Important thing for you is weather Monitor is ON or NOT.

2) When you change the gear of your vehicle are you really concern about the inner details of your vehicle engine? No but what matter to you is that Gear must get changed that’s it!! This is abstraction; show only the details which matter to the user.

Tuesday, August 3, 2010

CodeIgniter


CodeIgniter Flow Diagram:



How do you get the current controller and method name of the URL?

echo $this->router->class;
echo $this->router->method;

Thumbnail Class:

/**
* PHP class for dynamically resizing, cropping, and rotating images for thumbnail purposes and either displaying them on-the-fly or saving them.
*
*/
class thumbnail_model extends Model {
/**
* Error message to display, if any
*
* @var string
*/
private $errmsg;
/**
* Whether or not there is an error
*
* @var boolean
*/
private $error;
/**
* Format of the image file
*
* @var string
*/
private $format;
/**
* File name and path of the image file
*
* @var string
*/
private $fileName;
/**
* Image meta data if any is available (jpeg/tiff) via the exif library
*
* @var array
*/
public $imageMeta;
/**
* Current dimensions of working image
*
* @var array
*/
private $currentDimensions;
/**
* New dimensions of working image
*
* @var array
*/
private $newDimensions;
/**
* Image resource for newly manipulated image
*
* @var resource
*/
private $newImage;
/**
* Image resource for image before previous manipulation
*
* @var resource
*/
private $oldImage;
/**
* Image resource for image being currently manipulated
*
* @var resource
*/
private $workingImage;
/**
* Percentage to resize image by
*
* @var int
*/
private $percent;
/**
* Maximum width of image during resize
*
* @var int
*/
private $maxWidth;
/**
* Maximum height of image during resize
*
* @var int
*/
private $maxHeight;

public $watermarkImageRequired = FALSE;

public $watermarkImage;

public $maxDimension;

/*
watermark white bg image path
@watermark_imagepath
*/
public $watermark_imagepath;

/**
* Class constructor
*
* @param string $fileName
* @return Thumbnail
*/

public function thumbnail($fileName) {

parent::Model();

//make sure the GD library is installed
if(!function_exists("gd_info")) {
echo 'You do not have the GD Library installed. This class requires the GD library to function properly.' . "\n";
exit;
}
//initialize variables
$this->errmsg = '';
$this->error = false;
$this->currentDimensions = array();
$this->newDimensions = array();
$this->fileName = $fileName;
$this->imageMeta = array();
$this->percent = 100;
$this->maxWidth = 220;
$this->maxHeight = 137;
$this->maxDimension = array(
'width' => 220,
'height' => 200
);
//check to see if file exists
if(!file_exists($this->fileName)) {
$this->errmsg = 'File not found';
$this->error = true;
}
//check to see if file is readable
elseif(!is_readable($this->fileName)) {
$this->errmsg = 'File is not readable';
$this->error = true;
}

//if there are no errors, determine the file format
if($this->error == false) {
//check if gif
if(stristr(strtolower($this->fileName),'.gif')) $this->format = 'GIF';
//check if jpg
elseif(stristr(strtolower($this->fileName),'.jpg') || stristr(strtolower($this->fileName),'.jpeg')) $this->format = 'JPG';
//check if png
elseif(stristr(strtolower($this->fileName),'.png')) $this->format = 'PNG';
//unknown file format
else {
$this->errmsg = 'Unknown file format';
$this->error = true;
}
}

//initialize resources if no errors
if($this->error == false) {
switch($this->format) {
case 'GIF':
$this->oldImage = ImageCreateFromGif($this->fileName);
break;
case 'JPG':
$this->oldImage = ImageCreateFromJpeg($this->fileName);
break;
case 'PNG':
$this->oldImage = ImageCreateFromPng($this->fileName);
break;
}

$size = GetImageSize($this->fileName);
$this->currentDimensions = array('width'=>$size[0],'height'=>$size[1]);
$this->newImage = $this->oldImage;
$this->gatherImageMeta();
}

if($this->error == true) {
$this->showErrorImage();
break;
}
}

/**
* Class destructor
*
*/
public function __destruct() {
if(is_resource($this->newImage)) @ImageDestroy($this->newImage);
if(is_resource($this->oldImage)) @ImageDestroy($this->oldImage);
if(is_resource($this->workingImage)) @ImageDestroy($this->workingImage);
}

/**
* Returns the current width of the image
*
* @return int
*/
private function getCurrentWidth() {
return $this->currentDimensions['width'];
}

/**
* Returns the current height of the image
*
* @return int
*/
private function getCurrentHeight() {
return $this->currentDimensions['height'];
}

/**
* Calculates new image width
*
* @param int $width
* @param int $height
* @return array
*/
private function calcWidth($width,$height) {
$newWp = (100 * $this->maxWidth) / $width;
$newHeight = ($height * $newWp) / 100;
return array('newWidth'=>intval($this->maxWidth),'newHeight'=>intval($newHeight));
}

/**
* Calculates new image height
*
* @param int $width
* @param int $height
* @return array
*/
private function calcHeight($width,$height) {
$newHp = (100 * $this->maxHeight) / $height;
$newWidth = ($width * $newHp) / 100;
return array('newWidth'=>intval($newWidth),'newHeight'=>intval($this->maxHeight));
}

/**
* Calculates new image size based on percentage
*
* @param int $width
* @param int $height
* @return array
*/
private function calcPercent($width,$height) {
$newWidth = ($width * $this->percent) / 100;
$newHeight = ($height * $this->percent) / 100;
return array('newWidth'=>intval($newWidth),'newHeight'=>intval($newHeight));
}

/**
* Calculates new image size based on width and height, while constraining to maxWidth and maxHeight
*
* @param int $width
* @param int $height
*/
private function calcImageSize($width,$height) {
$newSize = array('newWidth'=>$width,'newHeight'=>$height);

if($this->maxWidth > 0) {

$newSize = $this->calcWidth($width,$height);

if($this->maxHeight > 0 && $newSize['newHeight'] > $this->maxHeight) {
$newSize = $this->calcHeight($newSize['newWidth'],$newSize['newHeight']);
}

//$this->newDimensions = $newSize;
}

if($this->maxHeight > 0) {
$newSize = $this->calcHeight($width,$height);

if($this->maxWidth > 0 && $newSize['newWidth'] > $this->maxWidth) {
$newSize = $this->calcWidth($newSize['newWidth'],$newSize['newHeight']);
}

//$this->newDimensions = $newSize;
}
$this->newDimensions = $newSize;
}

/**
* Calculates new image size based percentage
*
* @param int $width
* @param int $height
*/
private function calcImageSizePercent($width,$height) {
if($this->percent > 0) {
$this->newDimensions = $this->calcPercent($width,$height);
}
}

/**
* Displays error image
*
*/
private function showErrorImage() {
header('Content-type: image/png');
$errImg = ImageCreate(220,25);
$bgColor = imagecolorallocate($errImg,0,0,0);
$fgColor1 = imagecolorallocate($errImg,255,255,255);
$fgColor2 = imagecolorallocate($errImg,255,0,0);
imagestring($errImg,3,6,6,'Error:',$fgColor2);
imagestring($errImg,3,55,6,$this->errmsg,$fgColor1);
imagepng($errImg);
imagedestroy($errImg);
}

/**
* Resizes image to maxWidth x maxHeight
*
* @param int $maxWidth
* @param int $maxHeight
*/
public function resize($maxWidth = 0, $maxHeight = 0, $bg='0xFFFFFF') {
$this->maxWidth = $maxWidth;
$this->maxHeight = $maxHeight;

$this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}

ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0,
0,
0,
0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}

/**
* Resizes the image by $percent percent
*
* @param int $percent
*/
public function resizePercent($percent = 0) {
$this->percent = $percent;

$this->calcImageSizePercent($this->currentDimensions['width'],$this->currentDimensions['height']);

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}

ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0,
0,
0,
0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}

/**
* Crops the image from calculated center in a square of $cropSize pixels
*
* @param int $cropSize
*/
public function cropFromCenter($cropSize) {
if($cropSize > $this->currentDimensions['width']) $cropSize = $this->currentDimensions['width'];
if($cropSize > $this->currentDimensions['height']) $cropSize = $this->currentDimensions['height'];

$cropX = intval(($this->currentDimensions['width'] - $cropSize) / 2);
$cropY = intval(($this->currentDimensions['height'] - $cropSize) / 2);

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($cropSize,$cropSize);
}
else {
$this->workingImage = ImageCreate($cropSize,$cropSize);
}

imagecopyresampled(
$this->workingImage,
$this->oldImage,
0,
0,
$cropX,
$cropY,
$cropSize,
$cropSize,
$cropSize,
$cropSize
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $cropSize;
$this->currentDimensions['height'] = $cropSize;
}

/**
* Advanced cropping function that crops an image using $startX and $startY as the upper-left hand corner.
*
* @param int $startX
* @param int $startY
* @param int $width
* @param int $height
*/
public function crop($startX,$startY,$width,$height) {
//make sure the cropped area is not greater than the size of the image
if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];
//make sure not starting outside the image
if(($startX + $width) > $this->currentDimensions['width']) $startX = ($this->currentDimensions['width'] - $width);
if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);
if($startX < 0) $startX = 0;
if($startY < 0) $startY = 0;

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($width,$height);
}
else {
$this->workingImage = ImageCreate($width,$height);
}

imagecopyresampled(
$this->workingImage,
$this->oldImage,
0,
0,
$startX,
$startY,
$width,
$height,
$width,
$height
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $width;
$this->currentDimensions['height'] = $height;
}

/**
* Outputs the image to the screen, or saves to $name if supplied. Quality of JPEG images can be controlled with the $quality variable
*
* @param int $quality
* @param string $name
*/
public function show($quality=100,$name = '') {

//-- apply white background image
if($this->watermarkImageRequired) {
if($this->watermark_imagepath != "")
$this->watermark($this->watermark_imagepath);
else
$this->watermark(base_url().'images/team_logo/teamlogo_bg.jpg');
}

switch($this->format) {
case 'GIF':
if($name != '') {
ImageGif($this->newImage,$name);
}
else {
header('Content-type: image/gif');
ImageGif($this->newImage);
}
break;
case 'JPG':
if($name != '') {
ImageJpeg($this->newImage,$name,$quality);
}
else {
header('Content-type: image/jpeg');
ImageJpeg($this->newImage,'',$quality);
}
break;
case 'PNG':
if($name != '') {
ImagePng($this->newImage,$name);
}
else {
header('Content-type: image/png');
ImagePng($this->newImage);
}
break;
}
}

/**
* Saves image as $name (can include file path), with quality of # percent if file is a jpeg
*
* @param string $name
* @param int $quality
*/
public function save($name,$quality=100) {
$this->show($quality,$name);
}

/**
* Creates Apple-style reflection under image, optionally adding a border to main image
*
* @param int $percent
* @param int $reflection
* @param int $white
* @param bool $border
* @param string $borderColor
*/
public function createReflection($percent,$reflection,$white,$border = true,$borderColor = '#a4a4a4') {
$width = $this->currentDimensions['width'];
$height = $this->currentDimensions['height'];

$reflectionHeight = intval($height * ($reflection / 100));
$newHeight = $height + $reflectionHeight;
$reflectedPart = $height * ($percent / 100);

$this->workingImage = ImageCreateTrueColor($width,$newHeight);

ImageAlphaBlending($this->workingImage,true);

$colorToPaint = ImageColorAllocateAlpha($this->workingImage,255,255,255,0);
ImageFilledRectangle($this->workingImage,0,0,$width,$newHeight,$colorToPaint);

imagecopyresampled(
$this->workingImage,
$this->newImage,
0,
0,
0,
$reflectedPart,
$width,
$reflectionHeight,
$width,
($height - $reflectedPart));
$this->imageFlipVertical();

imagecopy($this->workingImage,$this->newImage,0,0,0,0,$width,$height);

imagealphablending($this->workingImage,true);

for($i=0;$i<$reflectionHeight;$i++) {
$colorToPaint = imagecolorallocatealpha($this->workingImage,255,255,255,($i/$reflectionHeight*-1+1)*$white);
imagefilledrectangle($this->workingImage,0,$height+$i,$width,$height+$i,$colorToPaint);
}

if($border == true) {
$rgb = $this->hex2rgb($borderColor,false);
$colorToPaint = imagecolorallocate($this->workingImage,$rgb[0],$rgb[1],$rgb[2]);
imageline($this->workingImage,0,0,$width,0,$colorToPaint); //top line
imageline($this->workingImage,0,$height,$width,$height,$colorToPaint); //bottom line
imageline($this->workingImage,0,0,0,$height,$colorToPaint); //left line
imageline($this->workingImage,$width-1,0,$width-1,$height,$colorToPaint); //right line
}

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $width;
$this->currentDimensions['height'] = $newHeight;
}

/**
* Inverts working image, used by reflection function
*
*/
private function imageFlipVertical() {
$x_i = imagesx($this->workingImage);
$y_i = imagesy($this->workingImage);

for($x = 0; $x < $x_i; $x++) {
for($y = 0; $y < $y_i; $y++) {
imagecopy($this->workingImage,$this->workingImage,$x,$y_i - $y - 1, $x, $y, 1, 1);
}
}
}

/**
* Converts hexidecimal color value to rgb values and returns as array/string
*
* @param string $hex
* @param bool $asString
* @return array|string
*/
private function hex2rgb($hex, $asString = false) {
// strip off any leading #
if (0 === strpos($hex, '#')) {
$hex = substr($hex, 1);
} else if (0 === strpos($hex, '&H')) {
$hex = substr($hex, 2);
}

// break into hex 3-tuple
$cutpoint = ceil(strlen($hex) / 2)-1;
$rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

// convert each tuple to decimal
$rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
$rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
$rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
}

/**
* Reads selected exif meta data from jpg images and populates $this->imageMeta with appropriate values if found
*
*/
private function gatherImageMeta() {
//only attempt to retrieve info if exif exists
if(function_exists("exif_read_data") && $this->format == 'JPG') {
$imageData = exif_read_data($this->fileName);
if(isset($imageData['Make']))
$this->imageMeta['make'] = ucwords(strtolower($imageData['Make']));
if(isset($imageData['Model']))
$this->imageMeta['model'] = $imageData['Model'];
if(isset($imageData['COMPUTED']['ApertureFNumber'])) {
$this->imageMeta['aperture'] = $imageData['COMPUTED']['ApertureFNumber'];
$this->imageMeta['aperture'] = str_replace('/','',$this->imageMeta['aperture']);
}
if(isset($imageData['ExposureTime'])) {
$exposure = explode('/',$imageData['ExposureTime']);
$exposure = round($exposure[1]/$exposure[0],-1);
$this->imageMeta['exposure'] = '1/' . $exposure . ' second';
}
if(isset($imageData['Flash'])) {
if($imageData['Flash'] > 0) {
$this->imageMeta['flash'] = 'Yes';
}
else {
$this->imageMeta['flash'] = 'No';
}
}
if(isset($imageData['FocalLength'])) {
$focus = explode('/',$imageData['FocalLength']);
$this->imageMeta['focalLength'] = round($focus[0]/$focus[1],2) . ' mm';
}
if(isset($imageData['DateTime'])) {
$date = $imageData['DateTime'];
$date = explode(' ',$date);
$date = str_replace(':','-',$date[0]) . ' ' . $date[1];
$this->imageMeta['dateTaken'] = date('m/d/Y g:i A',strtotime($date));
}
}
}

/**
* Rotates image either 90 degrees clockwise or counter-clockwise
*
* @param string $direction
*/
public function rotateImage($direction = 'CW') {
if($direction == 'CW') {
$this->workingImage = imagerotate($this->workingImage,-90,0);
}
else {
$this->workingImage = imagerotate($this->workingImage,90,0);
}
$newWidth = $this->currentDimensions['height'];
$newHeight = $this->currentDimensions['width'];
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $newWidth;
$this->currentDimensions['height'] = $newHeight;
}


public function watermark($insertfile, $pos = 0, $transition = 100)
{
// 0 = middle
// 1 = top left
// 2 = top right
// 3 = bottom right
// 4 = bottom left
// 5 = top middle
// 6 = middle right
// 7 = bottom middle
// 8 = middle left
$this->watermarkImage = imagecreatefromjpeg($insertfile);
//$white = imagecolorallocate($insertfile_id, 255, 255, 255);
$pos = 0;

if (empty($this->workingImage)) {
$this->resizePercent(100);
}

/* if ($pos == "") {
$pos = 0;
} elseif ($pos > 8 ) { //|| $pos > $this->workingImage

}*/
$sourcefile_width = imageSX($this->watermarkImage);
$sourcefile_height = imageSY($this->watermarkImage);
$insertfile_width = imageSX($this->workingImage);
$insertfile_height = imageSY($this->workingImage);

//echo "
sourcefile_width = $sourcefile_width
sourcefile_height=$sourcefile_height
insertfile_width=$insertfile_width
insertfile_height=$insertfile_height";
// middle

$dest_x = ($sourcefile_width / 2) - ($insertfile_width / 2);
$dest_y = ($sourcefile_height / 2) - ($insertfile_height / 2);
//echo "
dest_x=$dest_x
dest_y=$dest_y ";exit;

// The main thing : merge the two pix
//imageCopyMerge($this->watermarkImage, $this->workingImage, $insertfile_width, $insertfile_height, 0, 0, $dest_x, $dest_y, $transition);
//orig
//imageCopyMerge($this->workingImage, $this->watermarkImage, $dest_x, $dest_y, 0, 0, $insertfile_width, $insertfile_height, $transition);
imageCopyMerge($this->watermarkImage, $this->workingImage, $dest_x, $dest_y, 0, 0, $insertfile_width, $insertfile_height, $transition);
$this->newImage = $this->watermarkImage;
}
}
?>

Sunday, August 1, 2010

MySQL Questions

InnoDB Table Space
Unlike MyISAM where data for individual tables is stored in their respective files, InnoDB stores data in a tablespace. By default, there is one single tablespace and data of all the databases is stored in one file. This file has data dictionary, tables, as well as indexes in it. There is a global parameter innodb_data_file_path that defines this tablespace file. It has a syntax like ibdata1:256M:autoextend, this means at the beginning a file of size 256 MB will be created and then whenever the data size exceeds this, the file will be auto-extended. The innodb_autoextend_increment variable defines in MB's that by how much each increment should be.

Let's see how well can we play around:

Inserts: Suppose you have too many inserts and InnoDB is extending the file too frequently. It makes sense to increase the value of innodb_autoextend_increment. Say we increase it to 16MB, then obviously the number of attempts to autoextend tablespace comes down by a factor of 2, hence performance. But beware before you take it too easy and increase the value too much. There is a big trap, we will come to it shortly.
Deletes: Here is the trap. You have a 10 GB tablespace (after too many autoextends), delete some 5 GB data (data + indexes) and think now the tablespace is 5 GB. Wrong, InnoDB doesn't have the notion of giving back space to the file system. Though, it will make sure to use the freed up space for further inserts. So, this method directly cannot be used to free disk space. So, in case you have data which you can get rid of, get rid of quickly before the next autoextend is done. One thing that can be done to reclaim space is to use OPTIMIZE TABLE frequently enough on tables that have high volume of inserts and deletes. But again remember, MySQL locks a table during the time OPTIMIZE TABLE is running. Another Gotcha, right? OPTIMIZE TABLE does several other things for which it makes sense to run it, though not that frequently. I will be posting a blog soon on it.
Separate Files per Table: InnoDB provides this option where data (data + indexes) for each table can be stored in a separate file through a global variable innodb_file_per_table. Though still a shared tablespace will be created for storing the likes of data dictionary et al. But still this approach makes sense as having data in small chunks (separate files) will improve the scope of managing them well and may increase performance in general.
Fixed Tablespace size: One way to work around with the tablespace file size problems is to fix the tablespace size (remove autoextend) to an extrapolated value. So, when you hit the limit, you know it is time to cleanup. This is not that viable with all the applications, as extrapolation is not always possible. And also it increases the complexity of the application, which then needs to take care of all such error conditions and not lose any data.
So, where does this end? You need to figure out what your data is, how critical it is, what all you want to do with it, what all you want your data to do. Then take some of the following steps.

Move to MyISAM: For all the tables (or even databases), for which you feel data is not that critical to have transactions et al, move them to MyISAM. So, for the problem we can't solve completely, we destroy the problem.
Separate Tablespace: Its a lot easier to maintain 10 small problems than a single big one.
Delete data/OPTIMIZE TABLE: Figure out how soon you can get rid of data. You actually don't need to delete data as it is. Transfer it to a MyISAM table, compress the file and archive it somewhere else and then delete it from the main table. Likewise there are many ways to do it. Run OPTIMIZE TABLE frequently enough so that it doesn't bother your reads and writes too much and also it doesn't take too much time to run.




MyISAM vs InnoDB?
The 2 major types of table storage engines for MySQL databases are InnoDB and MyISAM. To summarize the differences of features and performance,

InnoDB is newer while MyISAM is older.
InnoDB is more complex while MyISAM is simpler.
InnoDB is more strict in data integrity while MyISAM is loose.
InnoDB implements row-level lock for inserting and updating while MyISAM implements table-level lock.
InnoDB has transactions while MyISAM does not.
InnoDB has foreign keys and relationship contraints while MyISAM does not.
InnoDB has better crash recovery while MyISAM is poor at recovering data integrity at system crashes.
MyISAM has full-text search index while InnoDB has not.
In light of these differences, InnoDB and MyISAM have their unique advantages and disadvantages against each other. They each are more suitable in some scenarios than the other.

Advantages of InnoDB

InnoDB should be used where data integrity comes a priority because it inherently takes care of them by the help of relationship constraints and transactions.
Faster in write-intensive (inserts, updates) tables because it utilizes row-level locking and only hold up changes to the same row that’s being inserted or updated.
Disadvantages of InnoDB

Because InnoDB has to take care of the different relationships between tables, database administrator and scheme creators have to take more time in designing the data models which are more complex than those of MyISAM.
Consumes more system resources such as RAM. As a matter of fact, it is recommended by many that InnoDB engine be turned off if there’s no substantial need for it after installation of MySQL.
No full-text indexing.
Advantages of MyISAM

Simpler to design and create, thus better for beginners. No worries about the foreign relationships between tables.
Faster than InnoDB on the whole as a result of the simpler structure thus much less costs of server resources.
Full-text indexing.
Especially good for read-intensive (select) tables.
Disadvantages of MyISAM

No data integrity (e.g. relationship constraints) check, which then comes a responsibility and overhead of the database administrators and application developers.
Doesn’t support transactions which is essential in critical data applications such as that of banking.
Slower than InnoDB for tables that are frequently being inserted to or updated, because the entire table is locked for any insert or update.
The comparison is pretty straightforward. InnoDB is more suitable for data critical situations that require frequent inserts and updates. MyISAM, on the other hand, performs better with applications that don’t quite depend on the data integrity and mostly just select and display the data.




MyISAM
Let's start with MyISAM since it is the default engine with MySQL. MyISAM is based on the older but proven ISAM code but has been extended to be fully-featured while retaining the reliability. Data in MyISAM tables is split between three different files on the disk. One for the table format, another for the data, and lastly a third for the indexes.

The maximum number of rows supported amounts to somewhere around ~4.295E+09 and can have up to 64 indexed fields per table. Both of these limits can be greatly increased by compiling a special version of MySQL.

Text/Blob fields are able to be fully-indexed which is of great importance to search functions.

Much more technical information can be found on MySQL's MyISAM Manual Page.

InnoDB
InnoDB is relatively newer so the scene than MyISAM is so people are still weary about its use in environments than run fine under MyISAM. InnoDB is transaction-safe meaning data-integrity is maintained throughout the entire query process. InnoDB also provides row-locking, as opposed to table-locking, meaning while one query is busy updating or inserting a row, another query can update a different row at the same time. These features increase multi-user concurrency and performance.

Another great feature InnoDB boasts is the ability to use foreign-key constraints. FK constraints allows developers to ensure that inserted data referencing another table remains valid. For example, if you had an authors table and a books table and you wanted to insert a new book while referencing the author. The author would have to exist in the authors table before inserting them in the books table because a foreign key was specified in the books table. At the same time you would not be able to delete an author from the authors table if they had any entries associated with them in the books table. More on this in a later article...

Because of its row-locking feature InnoDB is said to thrive in high load environments. Its CPU efficiency is probably not matched by any other disk-based relational database engine.



Comparison
MyISAM in most cases will be faster than InnoDB for run of the mill sort of work. Selecting, updating and inserting are all very speedy under normal circumstances. It is the default engine chosen by the MySQL development team which speaks to its integrity, reliability, and performance.

InnoDB, or the OSX of the database-engine world, has emerged with some nifty features and created a niche for itself very quickly. Boasting features like row-level locking, transaction-safe queries, and relational table design are all very temping. The first two features really shine in a table that is constantly getting hammered like a logs, or search engine-type table. Since queries happen in the blink of an eye (faster actually) table-level locking(MyISAM) is sufficient in most other normal cases.

InnoDB recovers from a crash or other unexpected shutdown by replaying its logs. MyISAM must fully scan and repair or rebuild any indexes or possibly tables which had been updated but not fully flushed to disk.

Decision Matrix
Is your table is going to be inserted, deleted, and updated much much more than it is going to be selected?
InnoDB
If you need full-text search - MyISAM
If you prefer/require relational database design - InnoDB
Is disk-space or ram an issue? - MyISAM
In Doubt? - MyISAM
There is no winner.

REMEMBER! It's OK to mix table types in the same database! In fact it's recommended and frequently required. However, it is important to note that if you are having performance issues when joining the two types, try converting one to the other and see if that fixes it. This issue does not happen often but it has been reported.

1. How can we repair a MySQL table?

The syntex for repairing a mysql table is:

REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED

This command will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.

2. Give the syntax of GRANT commands?

The generic syntax for GRANT is as following

GRANT [rights] on [database] TO [username@hostname] IDENTIFIED BY [password]

Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

3. Give the syntax of REVOKE commands?

The generic syntax for revoke is as following

REVOKE [rights] on [database] FROM [username@hostname]

Now rights can be:
a) ALL privilages
b) Combination of CREATE, DROP, SELECT, INSERT, UPDATE and DELETE etc.

We can grant rights on all databse by usingh *.* or some specific database by database.* or a specific table by database.table_name.

4. What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, "Hello!" will be stored as "Hello! " in CHAR(10) column.

VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, "Hello!" will be stored as "Hello!" in VARCHAR(10) column.

How can we encrypt and decrypt a data present in a mysql table using mysql?

AES_ENCRYPT() and AES_DECRYPT()

5. How can I load data from a text file into a table?

The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:

a) Data must be delimited
b) Data fields must match table columns correctly

6. How can we change the data type of a column of a table?

This will change the data type of a column:

ALTER TABLE table_name CHANGE colm_name same_colm_name [new data type]


7. What is the difference between GROUP BY and ORDER BY in SQL?


To sort a result, use an ORDER BY clause.
The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).
ORDER BY [col1],[col2],...[coln]; Tells DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.
GROUP BY [col1],[col2],...[coln]; Tells DBMS to group (aggregate) results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average.


8. HOW CAN WE TAKE A BACKUP OF A MYSQL TABLE AND HOW CAN WE RESTORE IT?

Answer 1:
Create a full backup of your database: shell> mysqldump tab=/path/to/some/dir opt db_name
Or: shell> mysqlhotcopy db_name /path/to/some/dir

The full backup file is just a set of SQL statements, so restoring it is very easy:

shell> mysql "."Executed";


Answer 2:
To backup: BACKUP TABLE tbl_name TO /path/to/backup/directory
’ To restore: RESTORE TABLE tbl_name FROM /path/to/backup/directory


mysqldump: Dumping Table Structure and Data

Utility to dump a database or a collection of database for backup or for transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain SQL statements to create the table and/or populate the table.
-t, no-create-info
Don't write table creation information (the CREATE TABLE statement).
-d, no-data
Don't write any row information for the table. This is very useful if you just want to get a dump of the structure for a table!


9. What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side. Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted. Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.


10. Explain normalization concept?

The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).

First Normal Form
The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (making the field atomic).

Second Normal Form
Where the First Normal Form deals with redundancy of data across a horizontal row, Second Normal Form (or 2NF) deals with redundancy of data in vertical columns. As stated earlier, the normal forms are progressive, so to achieve Second Normal Form, your tables must already be in First Normal Form.

Third Normal Form
I have a confession to make; I do not often use Third Normal Form. In Third Normal Form we are looking for data in our tables that is not fully dependant on the primary key, but dependant on another value in the table


Show list of available users in mysql

select * from mysql.user;
or
desc mysql.user;

Image Manipulation : Water mark image creation

Water mark image creation


function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$font = 'arial.ttf';
$font_size = 10;
imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};


Ref: http://www.phpjabbers.com/phpexample.php?eid=20




Thumbnail with Watermark Image creation


/**
* PHP class for dynamically resizing, cropping, and rotating images for thumbnail purposes and either displaying them on-the-fly or saving them.
*
*/
class thumbnail_model extends Model {
/**
* Error message to display, if any
*
* @var string
*/
private $errmsg;
/**
* Whether or not there is an error
*
* @var boolean
*/
private $error;
/**
* Format of the image file
*
* @var string
*/
private $format;
/**
* File name and path of the image file
*
* @var string
*/
private $fileName;
/**
* Image meta data if any is available (jpeg/tiff) via the exif library
*
* @var array
*/
public $imageMeta;
/**
* Current dimensions of working image
*
* @var array
*/
private $currentDimensions;
/**
* New dimensions of working image
*
* @var array
*/
private $newDimensions;
/**
* Image resource for newly manipulated image
*
* @var resource
*/
private $newImage;
/**
* Image resource for image before previous manipulation
*
* @var resource
*/
private $oldImage;
/**
* Image resource for image being currently manipulated
*
* @var resource
*/
private $workingImage;
/**
* Percentage to resize image by
*
* @var int
*/
private $percent;
/**
* Maximum width of image during resize
*
* @var int
*/
private $maxWidth;
/**
* Maximum height of image during resize
*
* @var int
*/
private $maxHeight;

public $watermarkImageRequired = FALSE;

public $watermarkImage;

public $maxDimension;

/*
watermark white bg image path
@watermark_imagepath
*/
public $watermark_imagepath;

/**
* Class constructor
*
* @param string $fileName
* @return Thumbnail
*/

public function thumbnail($fileName) {

parent::Model();

//make sure the GD library is installed
if(!function_exists("gd_info")) {
echo 'You do not have the GD Library installed. This class requires the GD library to function properly.' . "\n";
exit;
}
//initialize variables
$this->errmsg = '';
$this->error = false;
$this->currentDimensions = array();
$this->newDimensions = array();
$this->fileName = $fileName;
$this->imageMeta = array();
$this->percent = 100;
$this->maxWidth = 220;
$this->maxHeight = 137;
$this->maxDimension = array(
'width' => 220,
'height' => 200
);
//check to see if file exists
if(!file_exists($this->fileName)) {
$this->errmsg = 'File not found';
$this->error = true;
}
//check to see if file is readable
elseif(!is_readable($this->fileName)) {
$this->errmsg = 'File is not readable';
$this->error = true;
}

//if there are no errors, determine the file format
if($this->error == false) {
//check if gif
if(stristr(strtolower($this->fileName),'.gif')) $this->format = 'GIF';
//check if jpg
elseif(stristr(strtolower($this->fileName),'.jpg') || stristr(strtolower($this->fileName),'.jpeg')) $this->format = 'JPG';
//check if png
elseif(stristr(strtolower($this->fileName),'.png')) $this->format = 'PNG';
//unknown file format
else {
$this->errmsg = 'Unknown file format';
$this->error = true;
}
}

//initialize resources if no errors
if($this->error == false) {
switch($this->format) {
case 'GIF':
$this->oldImage = ImageCreateFromGif($this->fileName);
break;
case 'JPG':
$this->oldImage = ImageCreateFromJpeg($this->fileName);
break;
case 'PNG':
$this->oldImage = ImageCreateFromPng($this->fileName);
break;
}

$size = GetImageSize($this->fileName);
$this->currentDimensions = array('width'=>$size[0],'height'=>$size[1]);
$this->newImage = $this->oldImage;
$this->gatherImageMeta();
}

if($this->error == true) {
$this->showErrorImage();
break;
}
}

/**
* Class destructor
*
*/
public function __destruct() {
if(is_resource($this->newImage)) @ImageDestroy($this->newImage);
if(is_resource($this->oldImage)) @ImageDestroy($this->oldImage);
if(is_resource($this->workingImage)) @ImageDestroy($this->workingImage);
}

/**
* Returns the current width of the image
*
* @return int
*/
private function getCurrentWidth() {
return $this->currentDimensions['width'];
}

/**
* Returns the current height of the image
*
* @return int
*/
private function getCurrentHeight() {
return $this->currentDimensions['height'];
}

/**
* Calculates new image width
*
* @param int $width
* @param int $height
* @return array
*/
private function calcWidth($width,$height) {
$newWp = (100 * $this->maxWidth) / $width;
$newHeight = ($height * $newWp) / 100;
return array('newWidth'=>intval($this->maxWidth),'newHeight'=>intval($newHeight));
}

/**
* Calculates new image height
*
* @param int $width
* @param int $height
* @return array
*/
private function calcHeight($width,$height) {
$newHp = (100 * $this->maxHeight) / $height;
$newWidth = ($width * $newHp) / 100;
return array('newWidth'=>intval($newWidth),'newHeight'=>intval($this->maxHeight));
}

/**
* Calculates new image size based on percentage
*
* @param int $width
* @param int $height
* @return array
*/
private function calcPercent($width,$height) {
$newWidth = ($width * $this->percent) / 100;
$newHeight = ($height * $this->percent) / 100;
return array('newWidth'=>intval($newWidth),'newHeight'=>intval($newHeight));
}

/**
* Calculates new image size based on width and height, while constraining to maxWidth and maxHeight
*
* @param int $width
* @param int $height
*/
private function calcImageSize($width,$height) {
$newSize = array('newWidth'=>$width,'newHeight'=>$height);

if($this->maxWidth > 0) {

$newSize = $this->calcWidth($width,$height);

if($this->maxHeight > 0 && $newSize['newHeight'] > $this->maxHeight) {
$newSize = $this->calcHeight($newSize['newWidth'],$newSize['newHeight']);
}

//$this->newDimensions = $newSize;
}

if($this->maxHeight > 0) {
$newSize = $this->calcHeight($width,$height);

if($this->maxWidth > 0 && $newSize['newWidth'] > $this->maxWidth) {
$newSize = $this->calcWidth($newSize['newWidth'],$newSize['newHeight']);
}

//$this->newDimensions = $newSize;
}
$this->newDimensions = $newSize;
}

/**
* Calculates new image size based percentage
*
* @param int $width
* @param int $height
*/
private function calcImageSizePercent($width,$height) {
if($this->percent > 0) {
$this->newDimensions = $this->calcPercent($width,$height);
}
}

/**
* Displays error image
*
*/
private function showErrorImage() {
header('Content-type: image/png');
$errImg = ImageCreate(220,25);
$bgColor = imagecolorallocate($errImg,0,0,0);
$fgColor1 = imagecolorallocate($errImg,255,255,255);
$fgColor2 = imagecolorallocate($errImg,255,0,0);
imagestring($errImg,3,6,6,'Error:',$fgColor2);
imagestring($errImg,3,55,6,$this->errmsg,$fgColor1);
imagepng($errImg);
imagedestroy($errImg);
}

/**
* Resizes image to maxWidth x maxHeight
*
* @param int $maxWidth
* @param int $maxHeight
*/
public function resize($maxWidth = 0, $maxHeight = 0, $bg='0xFFFFFF') {
$this->maxWidth = $maxWidth;
$this->maxHeight = $maxHeight;

$this->calcImageSize($this->currentDimensions['width'],$this->currentDimensions['height']);

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}

ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0,
0,
0,
0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}

/**
* Resizes the image by $percent percent
*
* @param int $percent
*/
public function resizePercent($percent = 0) {
$this->percent = $percent;

$this->calcImageSizePercent($this->currentDimensions['width'],$this->currentDimensions['height']);

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}
else {
$this->workingImage = ImageCreate($this->newDimensions['newWidth'],$this->newDimensions['newHeight']);
}

ImageCopyResampled(
$this->workingImage,
$this->oldImage,
0,
0,
0,
0,
$this->newDimensions['newWidth'],
$this->newDimensions['newHeight'],
$this->currentDimensions['width'],
$this->currentDimensions['height']
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $this->newDimensions['newWidth'];
$this->currentDimensions['height'] = $this->newDimensions['newHeight'];
}

/**
* Crops the image from calculated center in a square of $cropSize pixels
*
* @param int $cropSize
*/
public function cropFromCenter($cropSize) {
if($cropSize > $this->currentDimensions['width']) $cropSize = $this->currentDimensions['width'];
if($cropSize > $this->currentDimensions['height']) $cropSize = $this->currentDimensions['height'];

$cropX = intval(($this->currentDimensions['width'] - $cropSize) / 2);
$cropY = intval(($this->currentDimensions['height'] - $cropSize) / 2);

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($cropSize,$cropSize);
}
else {
$this->workingImage = ImageCreate($cropSize,$cropSize);
}

imagecopyresampled(
$this->workingImage,
$this->oldImage,
0,
0,
$cropX,
$cropY,
$cropSize,
$cropSize,
$cropSize,
$cropSize
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $cropSize;
$this->currentDimensions['height'] = $cropSize;
}

/**
* Advanced cropping function that crops an image using $startX and $startY as the upper-left hand corner.
*
* @param int $startX
* @param int $startY
* @param int $width
* @param int $height
*/
public function crop($startX,$startY,$width,$height) {
//make sure the cropped area is not greater than the size of the image
if($width > $this->currentDimensions['width']) $width = $this->currentDimensions['width'];
if($height > $this->currentDimensions['height']) $height = $this->currentDimensions['height'];
//make sure not starting outside the image
if(($startX + $width) > $this->currentDimensions['width']) $startX = ($this->currentDimensions['width'] - $width);
if(($startY + $height) > $this->currentDimensions['height']) $startY = ($this->currentDimensions['height'] - $height);
if($startX < 0) $startX = 0;
if($startY < 0) $startY = 0;

if(function_exists("ImageCreateTrueColor")) {
$this->workingImage = ImageCreateTrueColor($width,$height);
}
else {
$this->workingImage = ImageCreate($width,$height);
}

imagecopyresampled(
$this->workingImage,
$this->oldImage,
0,
0,
$startX,
$startY,
$width,
$height,
$width,
$height
);

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $width;
$this->currentDimensions['height'] = $height;
}

/**
* Outputs the image to the screen, or saves to $name if supplied. Quality of JPEG images can be controlled with the $quality variable
*
* @param int $quality
* @param string $name
*/
public function show($quality=100,$name = '') {

//-- apply white background image
if($this->watermarkImageRequired) {
if($this->watermark_imagepath != "")
$this->watermark($this->watermark_imagepath);
else
$this->watermark(base_url().'images/team_logo/teamlogo_bg.jpg');
}

switch($this->format) {
case 'GIF':
if($name != '') {
ImageGif($this->newImage,$name);
}
else {
header('Content-type: image/gif');
ImageGif($this->newImage);
}
break;
case 'JPG':
if($name != '') {
ImageJpeg($this->newImage,$name,$quality);
}
else {
header('Content-type: image/jpeg');
ImageJpeg($this->newImage,'',$quality);
}
break;
case 'PNG':
if($name != '') {
ImagePng($this->newImage,$name);
}
else {
header('Content-type: image/png');
ImagePng($this->newImage);
}
break;
}
}

/**
* Saves image as $name (can include file path), with quality of # percent if file is a jpeg
*
* @param string $name
* @param int $quality
*/
public function save($name,$quality=100) {
$this->show($quality,$name);
}

/**
* Creates Apple-style reflection under image, optionally adding a border to main image
*
* @param int $percent
* @param int $reflection
* @param int $white
* @param bool $border
* @param string $borderColor
*/
public function createReflection($percent,$reflection,$white,$border = true,$borderColor = '#a4a4a4') {
$width = $this->currentDimensions['width'];
$height = $this->currentDimensions['height'];

$reflectionHeight = intval($height * ($reflection / 100));
$newHeight = $height + $reflectionHeight;
$reflectedPart = $height * ($percent / 100);

$this->workingImage = ImageCreateTrueColor($width,$newHeight);

ImageAlphaBlending($this->workingImage,true);

$colorToPaint = ImageColorAllocateAlpha($this->workingImage,255,255,255,0);
ImageFilledRectangle($this->workingImage,0,0,$width,$newHeight,$colorToPaint);

imagecopyresampled(
$this->workingImage,
$this->newImage,
0,
0,
0,
$reflectedPart,
$width,
$reflectionHeight,
$width,
($height - $reflectedPart));
$this->imageFlipVertical();

imagecopy($this->workingImage,$this->newImage,0,0,0,0,$width,$height);

imagealphablending($this->workingImage,true);

for($i=0;$i<$reflectionHeight;$i++) {
$colorToPaint = imagecolorallocatealpha($this->workingImage,255,255,255,($i/$reflectionHeight*-1+1)*$white);
imagefilledrectangle($this->workingImage,0,$height+$i,$width,$height+$i,$colorToPaint);
}

if($border == true) {
$rgb = $this->hex2rgb($borderColor,false);
$colorToPaint = imagecolorallocate($this->workingImage,$rgb[0],$rgb[1],$rgb[2]);
imageline($this->workingImage,0,0,$width,0,$colorToPaint); //top line
imageline($this->workingImage,0,$height,$width,$height,$colorToPaint); //bottom line
imageline($this->workingImage,0,0,0,$height,$colorToPaint); //left line
imageline($this->workingImage,$width-1,0,$width-1,$height,$colorToPaint); //right line
}

$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $width;
$this->currentDimensions['height'] = $newHeight;
}

/**
* Inverts working image, used by reflection function
*
*/
private function imageFlipVertical() {
$x_i = imagesx($this->workingImage);
$y_i = imagesy($this->workingImage);

for($x = 0; $x < $x_i; $x++) {
for($y = 0; $y < $y_i; $y++) {
imagecopy($this->workingImage,$this->workingImage,$x,$y_i - $y - 1, $x, $y, 1, 1);
}
}
}

/**
* Converts hexidecimal color value to rgb values and returns as array/string
*
* @param string $hex
* @param bool $asString
* @return array|string
*/
private function hex2rgb($hex, $asString = false) {
// strip off any leading #
if (0 === strpos($hex, '#')) {
$hex = substr($hex, 1);
} else if (0 === strpos($hex, '&H')) {
$hex = substr($hex, 2);
}

// break into hex 3-tuple
$cutpoint = ceil(strlen($hex) / 2)-1;
$rgb = explode(':', wordwrap($hex, $cutpoint, ':', $cutpoint), 3);

// convert each tuple to decimal
$rgb[0] = (isset($rgb[0]) ? hexdec($rgb[0]) : 0);
$rgb[1] = (isset($rgb[1]) ? hexdec($rgb[1]) : 0);
$rgb[2] = (isset($rgb[2]) ? hexdec($rgb[2]) : 0);

return ($asString ? "{$rgb[0]} {$rgb[1]} {$rgb[2]}" : $rgb);
}

/**
* Reads selected exif meta data from jpg images and populates $this->imageMeta with appropriate values if found
*
*/
private function gatherImageMeta() {
//only attempt to retrieve info if exif exists
if(function_exists("exif_read_data") && $this->format == 'JPG') {
$imageData = exif_read_data($this->fileName);
if(isset($imageData['Make']))
$this->imageMeta['make'] = ucwords(strtolower($imageData['Make']));
if(isset($imageData['Model']))
$this->imageMeta['model'] = $imageData['Model'];
if(isset($imageData['COMPUTED']['ApertureFNumber'])) {
$this->imageMeta['aperture'] = $imageData['COMPUTED']['ApertureFNumber'];
$this->imageMeta['aperture'] = str_replace('/','',$this->imageMeta['aperture']);
}
if(isset($imageData['ExposureTime'])) {
$exposure = explode('/',$imageData['ExposureTime']);
$exposure = round($exposure[1]/$exposure[0],-1);
$this->imageMeta['exposure'] = '1/' . $exposure . ' second';
}
if(isset($imageData['Flash'])) {
if($imageData['Flash'] > 0) {
$this->imageMeta['flash'] = 'Yes';
}
else {
$this->imageMeta['flash'] = 'No';
}
}
if(isset($imageData['FocalLength'])) {
$focus = explode('/',$imageData['FocalLength']);
$this->imageMeta['focalLength'] = round($focus[0]/$focus[1],2) . ' mm';
}
if(isset($imageData['DateTime'])) {
$date = $imageData['DateTime'];
$date = explode(' ',$date);
$date = str_replace(':','-',$date[0]) . ' ' . $date[1];
$this->imageMeta['dateTaken'] = date('m/d/Y g:i A',strtotime($date));
}
}
}

/**
* Rotates image either 90 degrees clockwise or counter-clockwise
*
* @param string $direction
*/
public function rotateImage($direction = 'CW') {
if($direction == 'CW') {
$this->workingImage = imagerotate($this->workingImage,-90,0);
}
else {
$this->workingImage = imagerotate($this->workingImage,90,0);
}
$newWidth = $this->currentDimensions['height'];
$newHeight = $this->currentDimensions['width'];
$this->oldImage = $this->workingImage;
$this->newImage = $this->workingImage;
$this->currentDimensions['width'] = $newWidth;
$this->currentDimensions['height'] = $newHeight;
}


public function watermark($insertfile, $pos = 0, $transition = 100)
{
// 0 = middle
// 1 = top left
// 2 = top right
// 3 = bottom right
// 4 = bottom left
// 5 = top middle
// 6 = middle right
// 7 = bottom middle
// 8 = middle left
$this->watermarkImage = imagecreatefromjpeg($insertfile);
//$white = imagecolorallocate($insertfile_id, 255, 255, 255);
$pos = 0;

if (empty($this->workingImage)) {
$this->resizePercent(100);
}

/* if ($pos == "") {
$pos = 0;
} elseif ($pos > 8 ) { //|| $pos > $this->workingImage

}*/
$sourcefile_width = imageSX($this->watermarkImage);
$sourcefile_height = imageSY($this->watermarkImage);
$insertfile_width = imageSX($this->workingImage);
$insertfile_height = imageSY($this->workingImage);

//echo "
sourcefile_width = $sourcefile_width
sourcefile_height=$sourcefile_height
insertfile_width=$insertfile_width
insertfile_height=$insertfile_height";
// middle

$dest_x = ($sourcefile_width / 2) - ($insertfile_width / 2);
$dest_y = ($sourcefile_height / 2) - ($insertfile_height / 2);
//echo "
dest_x=$dest_x
dest_y=$dest_y ";exit;

// The main thing : merge the two pix
//imageCopyMerge($this->watermarkImage, $this->workingImage, $insertfile_width, $insertfile_height, 0, 0, $dest_x, $dest_y, $transition);
//orig
//imageCopyMerge($this->workingImage, $this->watermarkImage, $dest_x, $dest_y, 0, 0, $insertfile_width, $insertfile_height, $transition);
imageCopyMerge($this->watermarkImage, $this->workingImage, $dest_x, $dest_y, 0, 0, $insertfile_width, $insertfile_height, $transition);
$this->newImage = $this->watermarkImage;
}
}
?>

HTML, XHTML and CSS

Cascading Definition:
The cascade in CSS or cascading style sheets is the ability to have multiple styles from different sources merge together into one definitive style.



The benefits of CSS
Separation of content and presentation
Smaller webpage file sizes
Improved webpage download speed
Improved rendering speed
Streamlined maintenance
Changing presentation for different devices
Accessibility
Table-less layout
Customisation
Search engine optimisation


CSS Grouping
When several selectors share the same declarations, they may be grouped into a comma-separated list.

Example(s):

In this example, we condense three rules with identical declarations into one. Thus,

h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }

is equivalent to:

h1, h2, h3 { font-family: sans-serif }



Reverse a string in CSS?

<p style="direction: rtl; unicode-bidi: bidi-override;">
0C 88 65 36 5C 65 14 8D B5 3E 47 D9 20 11 9F 90
$lt;/p$gt;

**********************************
ROUNDED / CURVED CORNER USING CSS
**********************************
<style type="text/css">
.b1h, .b2h, .b3h, .b4h, .b2bh, .b3bh, .b4bh {
font-size:1px;
overflow:hidden;
display:block;
}
.b1h {
height:1px;
background:#aaa;
margin:0 5px;
}
.b2h, .b2bh {
height:1px;
background:#aaa;
border-right:2px solid #aaa;
border-left:2px solid #aaa;
margin:0 3px;
}
.b3h, .b3bh {
height:1px;
background:#aaa;
border-right:1px solid #aaa;
border-left:1px solid #aaa;
margin:0 2px;
}
.b4h, .b4bh {
height:2px;
background:#aaa;
border-right:1px solid #aaa;
border-left:1px solid #aaa;
margin:0 1px;
}
.b2bh, .b3bh, .b4bh {
background: #DED397;
}
.headh {
background: #aaa;
border-right:1px solid #aaa;
border-left:1px solid #aaa;
}
.headh h3 {
margin: 0px 10px 0px 10px;
padding-bottom: 3px;
}
.contenth {
background: #DED397;
border-right:1px solid #aaa;
border-left:1px solid #aaa;
}
.contenth div {
margin-left: 12px;
padding-top: 5px;
}
</style>
<b class="b1h"></b><b class="b2h"></b><b class="b3h"></b><b class="b4h"></b>
<div class="headh">
<h3>Proxy Management Tools</h3>
</div>
<div class="contenth">
<div>GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE CONTENTS GOES HERE</div>
</div>
<b class="b4bh"></b><b class="b3bh"></b><b class="b2bh"></b><b class="b1h"></b>
*************************************************************************************
1. Difference between Block level element and Inline Element.
Block Level:
a. Starting and ending with new line
b. It contains inline element as well.
Eg: Div, P tag

Inline Element:
a. Displaying content in the same line.
Eg: Span, <br> <strong>

2. What is CSS Grouping

-- By grouping CSS selectors that share the same declaration and declarations that share the same selector you can apply multiple declarations to multiple selectors to optimize your style sheets.
Eg:
body, th, td {font-size: 12px; font-family: arial, helvetica, sans-serif;}
dive#main, div#sidebar {
border:1px solid red;
}

3. What is Specificity
If you have two (or more) conflicting CSS rules that point to the same element, there are some basic rules that a browser follows to determine which one is most specific and therefore wins out.

4. How do u import external css into other css file? Is it possible?
Yes:
@import url('/css/typography.css');

5. CSS Hacking

6. Difference between positions

The position property is used to define whether an element is absolute, relative, static or fixed.

The value static is the default value for elements and renders the position in the normal order of things, as they appear in the HTML.

relative is much like static, but the element can be offset from its original position with the properties top, right, bottom and left.

absolute pulls an element out of the normal flow of the HTML and delivers it to a world all of its own. In this crazy little world, the absolute element can be placed anywhere on the page using top, right, bottom and left.

fixed behaves like absolute, but it will absolutely position an element in reference to the browser window as opposed to the web page, so, theoretically, fixed elements should stay exactly where they are on the screen even when the page is scrolled. Why theoretically? Why else - this works great in browsers such as Mozilla and Opera, but in IE it doesn't work at all.

7. Difference between id, name and class? tell about them priority levels?

8. CSS short hand
Shorthand properties allow you to specify a set of related CSS properties with a single property. They combine related properties into a shorthand form. In most cases, the browser sets a default value if you leave out an optional one. There are six shorthand properties in CSS:

* font
* background
* margin
* border
* padding
* list

The most commonly used properties are the font family of properties. With the font shorthand property you can turn this complete declaration:

p {
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: .9em;
line-height: 1.1em;
font-family: arial, helvetica, sans-serif;
}

Into this:

p {font: italic small-caps bold .9em/1.1 arial,helvetica,sans-serif;}

In most cases you'd specify just the size and face, like this:

p{font:.9em arial,helvetica,sans-serif;}


9. CSS Optimization

Use CSS to strip presentation out of your (X)HTML. To optimize your CSS group external files to minimize HTTP requests, remove whitespace, and use shorthand properties. Group common declarations, selectors, and CSS code in multiple classes to save space. Use the simplest selectors you can, high in the document tree and let them cascade. Be as vague and as abstract as possible in your CSS selectors.

* Embed or SSI abbreviated styles for maximum speed.
* Minimize HTTP requests by grouping external CSS files.
* Link to external style sheets site-wide to cache in.
* Layer style sheets for speed. Use cascading to combine linked, alternate, and imported style sheets to layer your presentation for older browsers and alternate media (print), and to save bandwidth.
* Group selectors with the same declarations and declarations with the same selectors.
* Use simple selectors high in the document tree to set global and element-wide styles (that is, type styles like body, h1, p, and dt).
* Use descendant selectors to get specific without class or id selectors.
* Take advantage of your inheritance - don't overspecify CSS; let it flow down the document tree.
* Use multiple classes to group common style declarations to save space.
* Use value replication on the border, padding, and margin properties.
* Use shorthand hex colors (such as #00f).
* Use shorthand properties to optimize your CSS (including font, background, margin, and border).
* Use short class and id names.
* Use shorthand hexadecimal colors or names, whichever is shorter.
* Use relative lengths for maximum flexibility.
* Remove whitespace.
* Cut the comments.

10. XSS - Cross side scripting


What is Cross Site Scripting? - XSS - The Underestimated Exploit

Cross Site Scripting (or XSS) is one of the most common application-layer web attacks. XSS commonly targets scripts embedded in a page which are executed on the client-side (in the user’s web browser) rather than on the server-side. XSS in itself is a threat which is brought about by the internet security weaknesses of client-side scripting languages, with HTML and JavaScript (others being VBScript, ActiveX, HTML, or Flash) as the prime culprits for this exploit. The concept of XSS is to manipulate client-side scripts of a web application to execute in the manner desired by the malicious user. Such a manipulation can embed a script in a page which can be executed every time the page is loaded, or whenever an associated event is performed.

A basic example of XSS is when a malicious user injects a script in a legitimate shopping site URL which in turn redirects a user to a fake but identical page. The malicious page would run a script to capture the cookie of the user browsing the shopping site, and that cookie gets sent to the malicious user who can now hijack the legitimate user’s session. Although no real hack has been performed against the shopping site, XSS has still exploited a scripting weakness in the page to snare a user and take command of his session. A trick which often is used to make malicious URLs less obvious is to have the XSS part of the URL encoded in HEX (or other encoding methods). This will look harmless to the user who recognizes the URL he is familiar with, and simply disregards and following ‘tricked’ code which would be encoded and therefore inconspicuous.


Types of selectors

There's a whole bunch of selectors but for our purposes, we can break it down into three types, of increasing importance:

1. Element selectors (and pseudo-element selectors) Eg. p {color:red;}
2. Class selectors (and attribute selectors) Eg. .myclass {color:red;}
3. ID selectors. Eg. #myid {color:red;}

When it comes to specificity, it just takes one class selector to override any style declared with just element selectors, and it takes just one ID selector to override any style declared with class and/or element selectors. Let's check out an absurd example:


<style type="text/css">
#contact b {color:blue;}
div.help b {color:green;}
body div p b { color:red; }
</style>
<body id="contact"><div class="help"><p><b>my example</b></p></div></body>


HTMl & CSS Important Reference:
http://www.htmldog.com/guides/cssbeginner/


** CSS SPECIFICITY IMPORTANT RULES **

CSS Specificity: An Overview

Click here to reference site:

1. Specificity determines, which CSS rule is applied by the browsers.
2. Specificity is usually the reason why your CSS-rules don’t apply to some elements, although you think they should.
3. Every selector has its place in the specificity hierarchy.
4. If two selectors apply to the same element, the one with higher specificity wins.
5. There are four distinct categories which define the specificity level of a given selector: inline styles, IDs, classes+attributes and elements.
6. You can understand specificity if you love Star Wars: CSS Specificity Wars.
7. You can understand specificity if you love poker: CSS Specificity for Poker Players
8. When selectors have an equal specificity value, the latest rule is the one that counts.
9. When selectors have an unequal specificity value, the more specific rule is the one that counts.
10. Rules with more specific selectors have a greater specificity.
11. The last rule defined overrides any previous, conflicting rules.
12. The embedded style sheet has a greater specificity than other rules.
13. ID selectors have a higher specificity than attribute selectors.
14. You should always try to use IDs to increase the specificity.
15. A class selector beats any number of element selectors.
16. The universal selector and inherited selectors have a specificity of 0, 0, 0, 0.
17. You can calculate CSS specificity with CSS Specificity Calculator.


** pseudo-class **

A pseudo-class is similar to a class in HTML, but it’s not specified explicitly in the markup. Some pseudo-classes are dynamic—they’re applied as a result of user interaction with the document.
A pseudo-class starts with a colon (:). No whitespace may appear between a type selector or universal selector and the colon, nor can whitespace appear after the colon.
Eg:
:link, :active, :visited