What function can be used to encode passwords for storage in the database

The md5() function creates a one-way encoding of the password.

Where is the data for a cookie stored?

Cookies are stored on the web user's hard drive.

How can we get second of the current time using date function?

$second = date("s");

php and pdf

 Documents and Pages

A PDF document is made up of a number of pages. Each page contains text and/or images.Put text onto
 the pages, and send the pages back to the browser when you're done.

 
 
<?php

require("../fpdf/fpdf.php"); // path to fpdf.php

$pdf = new FPDF(  );
$pdf->AddPage(  );
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello Out There!');
$pdf->Output(  );

?>
 follows the basic steps involved in creating a PDF document.

The cell concept in the FPDF Library is that of a rectangular area on the page that you can create and control.
 This cell can have a height, width, a border, and of course can contain text.
The basic syntax for the cell method is as follows:
Cell(float w [, float h [, string txt [, mixed border [, int ln [, 
string align [, int fill [, mixed link]]]]]]])

The first option is the width, then the height, then the text to be outputted, then border, then new line control, then its alignment, any fill colour for the text, and finally if you want the text to be an HTML link. So, for example, if we want to change our original example to have a border and be center
 aligned we would change the cell code to the following:
$pdf->Cell(90,10,'Hello Out There!',1,0,'C');

The cell method is used extensively while generating PDF documents with fpdf,

Demonstrating coordinates and line management

<?php
require("../fpdf/fpdf.php");

$pdf = new FPDF('P', 'in', 'Letter');
$pdf->AddPage(  );
$pdf->SetFont('Arial','B',24);
// Cell(W, H, 'text', Border, Return, 'Allign') - basic syntax
$pdf->Cell(0,0,'Top Left!',0,1,'L');
$pdf->Cell(6,0.5,'Top Right!',1,0,'R');
$pdf->ln(4.5);
$pdf->Cell(0,0,'This is the middle!',0,0,'C');
$pdf->ln(5.3);
$pdf->Cell(0,0,'Bottom Left!',0,0,'L');
$pdf->Cell(0,0,'Bottom Right!',0,0,'R');
$pdf->Output(  );
?>

Declaring a Class

To design your program or code library in an object-oriented fashion, you'll need to define your own classes, using the class keyword.
A class definition includes the class name and the properties and methods of the class. Class names are case-insensitive and must conform to the rules for PHP identifiers. The class name stdClass is reserved. Here's the syntax for a class definition:
 
 
class classname [ extends baseclass ]
    {
        [ var $property [ = value ]; ... ]

        [ function functionname (args) {
              // code
          }
          ...
        ]
    }
 
 

Declaring Methods

A method is a function defined inside a class. Although PHP imposes no special restrictions, most methods act only on data within the object in which the method resides. Method names beginning with two underscores (_ _) may be used in the future by PHP (and are currently used for the object serialization methods _ _sleep( ) and _ _wakeup( ), described later in this chapter, among others), so it's recommended that you do not begin your method names with this sequence.
Within a method, the $this variable contains a reference to the object on which the method was called. For instance, if you call $rasmus->birthday( ) inside the birthday( ) method, $this holds the same value as $rasmus. Methods use the $this variable to access the properties of the current object and to call other methods on that object.

Here's a simple class definition of the Person class that shows the $this variable in action:
class Person { var $name; function get_name ( ) { return $this->name; } function set_name ($new_name) { $this->name = $new_name; } }
 
 
As you can see, the get_name( ) and set_name( ) methods use $this to access and set the $name property of the current object.
To declare a method as a static method, use the static keyword. Inside of static methods the variable $this is not defined. For example:

class HTML_Stuff {
static function start_table( ) {
echo "<table border='1'>\n";
 } static function end_table ( ) {
echo "</table>\n";
}
}
HTML_Stuff::start_table( ); // print HTML table rows and columns HTML_Stuff::end_table( );


Declaring Properties

In the previous definition of the Person class, we explicitly declared the $name property. Property declarations are optional and are simply a courtesy to whoever maintains your program. It's good PHP style to declare your properties, but you can add new properties at any time.
Here's a version of the Person class that has an undeclared $name property:
    class Person {
        function get_name (  )
        {
            return $this->name;    }

        function set_name ($new_name) {
            $this->name = $new_name;
        }
    }

You can assign default values to properties, but those default values must be simple constants:
    var $name = 'J Doe';       // works
    var $age  = 0;             // works
    var $day  = 60*60*24;      // doesn't work

Using access modifiers, you can change the visibility of properties. Properties that are accessible outside the object's scope should be declared public; properties on an instance that can only be accessed by methods within the same class should be declared private.
 

Sorting One Array at a Time

PHP functions for sorting an array
Effect
Ascending
Descending
User-defined order
Sort array by values, then reassign indices starting with 0
sort( )
rsort( )
usort( )
Sort array by values
asort( )
arsort( )
uasort( )
Sort array by keys
ksort( )
krsort( )
uksort( )

The sort( ), rsort( ), and usort( ) functions are designed to work on indexed arrays because they assign new numeric keys to represent the ordering. They're useful when you need to answer questions such as, "What are the top 10 scores?" and "Who's the third person in alphabetical order?" The other sort functions can be used on indexed arrays, but you'll only be able to access the sorted ordering by using traversal functions such as foreach and next 

To sort names into ascending alphabetical order, you'd use this:
    $names = array('cath', 'angela', 'brad', 'dave');
    sort($names);                // $names is now 'angela', 'brad', 'cath', 'dave'

To get them in reverse alphabetic order, simply call rsort( ) instead of sort( ).
If you have an associative array mapping usernames to minutes of login time, you can use arsort( ) to display a table of the top three, as shown here:
    $logins = array('njt' => 415,
                    'kt'  => 492,
                    'rl'  => 652,
                    'jht' => 441,
                    'jj'  => 441,
                    'wt'  => 402);
    arsort($logins);
    $num_printed = 0;
    echo("<table>\n");
    foreach ($logins as $user => $time ) {
      echo("<tr><td>$user</td><td>$time</td></tr>\n");
      if (++$num_printed == 3) {
        break;                   // stop after three
      }
    }
    echo("</table>\n");
    <table>
    <tr><td>rl</td><td>652</td></tr>
    <tr><td>kt</td><td>492</td></tr>
    <tr><td>jht</td><td>441</td></tr>
    </table>

If you want that table displayed in ascending order by username, use ksort( ):
    ksort($logins);
    echo("<table>\n");
    foreach ($logins as $user => $time) {
      echo("<tr><td>$user</td><td>$time</td></tr>\n");
    }
    echo("</table>\n");
    <table>
    <tr><td>jht</td><td>441</td></tr>
    <tr><td>jj</td><td>441</td></tr>
    <tr><td>kt</td><td>492</td></tr>
    <tr><td>njt</td><td>415</td></tr>
    <tr><td>rl</td><td>652</td></tr>
    <tr><td>wt</td><td>402</td></tr>
    </table>

User-defined ordering requires that you provide a function that takes two values and returns a value that specifies the order of the two values in the sorted array. The function should return 1 if the first value is greater than the second, -1 if the first value is less than the second, and 0 if the values are the same for the purposes of your custom sort order.
 a program that lets you try the various sorting functions on the same data.

 

How to Read an RSS Feed With PHP

<?php
include("../includes/config.php");
include("../includes/dbcon.php");

$tt_res=mysql_query("SELECT *
FROM `rss_data`");

$num = mysql_num_rows($tt_res);
if($num!=0)
{
$tt="TRUNCATE TABLE `rss_data`";
mysql_query($tt);
}



//get the q parameter from URL
$q="yy";

//find out which feed was selected
if($q=="Google")
  {
  $xml=("http://news.google.co.in/news?pz=1&cf=all&ned=in&hl=en&topic=s&output=rss");
  }
elseif($q=="yy")
  {
  $xml=("http://in.news.yahoo.com/rss/cricket");
  }

$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);

//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;



//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=5; $i++)
  {
  $item_title=$x->item($i)->getElementsByTagName('title')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_link=$x->item($i)->getElementsByTagName('link')
  ->item(0)->childNodes->item(0)->nodeValue;
  $item_desc=$x->item($i)->getElementsByTagName('description')
  ->item(0)->childNodes->item(0)->nodeValue;
 
  $item_title1=addslashes($item_title);
   $item_desc1=addslashes($item_desc);
 
echo $kk="INSERT INTO `rss_data` (
`item_title` ,
`item_desc`
)
VALUES (
 '".$item_title1."', '".$item_desc1."'
)";

mysql_query($kk);


  }
?>

mysqli Fetch Methods

If you prefer different MySQL fetch methods, they're also in mysqli. Given the same query of SELECT username FROM users, these example functions all print the same results:
// Fetch numeric arrays:

while ($row = mysqli_fetch_row($result)) {

    print $row[0] . "\n";

}



// Alternative syntax:

while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {

    print $row[0] . "\n";

}



// Alternative associative array syntax:

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

    print $row['username'] . "\n";

}



// Both numeric and associative:

while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {

    print $row[0] . "\n";

    print $row['username'] . "\n";

}



// Fetch as "object"

while ($row = mysqli_fetch_object($result)) {

    print $row->username . "\n";

}

XML Extensions in PHP 5

SimpleXML
A new PHP 5-only extension that excels at parsing RSS files, REST results, and configuration data. If you know the document's format ahead of time, SimpleXML is the way to go. However, SimpleXML supports only a subset of the XML specification.

XPath
This extension allows you to query XML documents like you're searching a database, to find the subset of information that you need and eliminate the unnecessary portions.


 XSLT
A way to take XML documents and transform them into HTML or another output format. It uses XML-based stylesheets to define the templates. XSLT is easily shared among different applications, but has a quirky syntax.

 

  • Reading XML into a tree
  • Reading XML from a stream
  • Creating new XML documents
  • Searching XML with XPath
  • Changing XML into HTML or other output formats with XSLT
  • Validating XML to ensure it conforms to a specification



    Example XML address book
    <?xml version="1.0"?>
    
    <address-book>
    
        <person id="1">
    
            <!--Rasmus Lerdorf-->
    
            <firstname>Rasmus</firstname>
    
            <lastname>Lerdorf</lastname>
    
            <city>Sunnyvale</city>
    
            <state>CA</state>
    
            <email>rasmus@php.net</email>
    
        </person>
    
    
    
        <person id="2">
    
            <!--Zeev Suraski-->
    
            <firstname>Zeev</firstname>
    
            <lastname>Suraski</lastname>
    
            <city>Tel Aviv</city>
    
            <state></state>
    
            <email>zeev@php.net</email>
    
        </person>
    
    </address-book>
     
     
     



    $dom = new DOMDocument;
    
    $dom->preserveWhiteSpace = false;
    
    $dom->load('address-book.xml');
    
    
    
    $root = $dom->documentElement;
    
    
    
    foreach ($root->childNodes as $person) {
    
        process($person);
    
    }

     

    The childNodes attribute is not an array, but a DOMNodeList object. The item( ) method allows you to access individual items, and the length property tells you the number of items in the list.
    This code is equivalent to the foreach loop:
    $people = $root->childNodes;
    
    
    
    for ($i = 0; $i < $people->length; $i++) {
    
        process($people->item($i));
    
    }


Tips for Optimizing CSS

1. Replace inline style with type selectors to target multiple instances of identical
elements.
2. Use descendant selectors to avoid inline classes.
3. Group selectors with common declarations.
4. Group declarations with common selectors.
5. Combine common styles into shared classes.
6. Use inheritance to eliminate duplicate declarations.
7. Use CSS shorthand to abbreviate rules and colors.
8. Abbreviate long class and ID names.
9. Use CSS2 and CSS3.x techniques.
10. Replace JavaScript behavior with CSS techniques.
In addition, you can eliminate extraneous whitespace by removing tabs, comments,
and returns.


Web pages that use inline style pepper HTML code with unnecessary font and style
tags. This effectively hardcodes the presentation directly within the HTML. Unless
the style is used only once, it is more efficient to create a CSS rule and target all elements
of a certain kind with type selectors (i.e., p, ul, h2, etc.). For example, this:




<h2 style="font-size:1.2em;color:red;">Little red Corvette</h2>
<h2 style="font-size:1.2em;color:red;">Baby you're much too fast to embed</h2>
<h2 style="font-size:1.2em;color:red;">Little red Corvette</h2>
<h2 style="font-size:1.2em;color:red;">You need a love that's gonna last</h2>
becomes this, by abstracting the inline style to a block style:
<style type="text/css"><!--
#main h2{font-size:1.2em;color:red;}
--></style>
The corresponding HTML cleans up to this:
<div id="main">
<h2>Little red Corvette</h2>
<h2>Baby you're much too fast</h2>
<h2>Little red Corvette</h2>
<h2>You need a love that's gonna last</h2>
</div>
 

Note how clean the code becomes after you remove the inline styles. This CSS technique
also helps search engine optimization (SEO) by boosting keyword density and
prominence.