Sunday, April 1, 2012

Cookies In PHP



A cookie is a small text file in which a website can store different information. Cookies are saved on the user's hard drive and not on the server.
Most cookies expire (delete themselves) after a predetermined time period, which can range from one minute to several years. But the user can also identify and delete any cookies on his/her computer.
Most browsers, such as Microsoft Internet Explorer, Mozilla Firefox and Google Chrome, can be configured to let the user choose whether or not he/she will accept a cookie. But then, why not just say no to all cookies? It is possible. But many websites would not work as intended without cookies, since cookies in many contexts are used to improve the usability and functionality of the website.

How is information stored in a cookie?

It's easy to set or modify a cookie in PHP with setcookie. In the first example, we will create a cookie and set the value.
First, you need a name for the cookie. In this example we will use the name "HTMLTest". Next, you set the value of the cookie like this:

 <?php 

 // Setting the cookie
 setcookie("HTMLTest", "This is a test cookie");   

 ?>

 
By default, a cookie is kept untill the browser is closed, but it can easily be modified by adding another parameter setting the expiry time:


 <?php 

 // Setting the cookie
 setcookie("Name", "C. Wing, time()+3600);   
 setcookie("Interests", "plane spotting", time()+3600); 
 
 ?>



"Time()+3600" specified that the cookie should expire in 3600 seconds (60 minutes) from now.
In the example above, we stored information about a user's name and interests. This information can, for example, be useful to target the website specifically for the individual visitor.

How do you retrieve the value of a cookie?

To get the value of the cookie, $_COOKIE is used. For example, if we need the information from the example above, we do it like this:


 <?php 

 // Retrieve values from the cookie
 $strName = $_COOKIE["Name"];   
 $strInterest = $_COOKIE["Interest"];
  
 // Write to the client
 echo "<p>" . strName . "</p>"   
 echo "<p>Your interest is . " strInterest . "</p>"
 
 ?>

Who can read the cookie?

By default, a cookie can be read at the same second-level domain (e.g.  prog-teach.blogspot.com ) as it was created. But by using the parameters domain and path, you can put further restrictions on the cookie using the following syntax:


setcookie(name, value, expiration time, path, domain);

 
Let us look at an example:
 
 <?php
 
 // Setting the cookie: name, value, expiration time, path, domain
 setcookie("Name", "C. Wing", time()+60*60*24*365, "/tutorials/php/", "www.prog-teach.blogspot.com");   
 ?>
In the example above, we set a cookie called "Name" with the value "C. Wing." The cookie expires after one year (60 seconds * 60 minutes * 24 hours * 365 days) and can be read only by sites located in the directory "/tutorials/php/" on the (sub-)domain .

Example of a cookie

We can try to save a sample cookie on your computer and then see how it looks.
The following code sets the cookie:


 <?php 

 // Setting the cookie
 setcookie("HTMLTest", "This text is in a cookie!", time()+60*60*24, "/tutorials/php/", "www.html.net");   
  
 // Write the information to the client
 echo $_COOKIE ["HTMLTest"];    

 ?>

 

Arrays In PHP



An array is a set of indexed elements where each has its own, unique identification number.
Sound confusing? It's actually not that complicated.
Imagine a list of words separated by commas. It is called a comma-separated list, and it could, for example, look like this:

apples, pears, bananas, oranges, lemons

 
Then try to imagine dividing the list at each comma. Next, give each section a unique identification number .

What you see is an array. We can, for example, name the array "fruits". The idea is that we can access the array with a number and get a value back, like this:
fruits(0) = apples
fruits(1) = pears
fruits(2) = bananas
fruits(3) = oranges
fruits(4) = lemons
This is the idea behind arrays. Let us try to use it in practice.

How do you use an array?

We will continue with the fruit example. Step by step, we will make it work as a real array. First, we set a variable equal to the list of fruits:


 <?php

 $fruitlist = "apples, pears, bananas, oranges, lemons";
 
 ?>

 
 
Next, we use the function explode to split the list at each comma:


 <?php
  
 $fruitlist = "apples, pears, bananas, oranges, lemons";
  
 $arrFruits = explode(",", $fruitlist);

 ?>

 
 
Voila! "$arrFruits" is now an array!
Notice that we called the function explode with two arguments:
  1. the list that should be split
  2. and the delimiter - i.e., the character used to split (in this case a comma) - in quotation marks: ",".
Here we use a comma as a delimiter, but you can use any character or word as a delimiter.
Let us try to comment the script and put it into a PHP page:


 <html>
 <head>
 <title>Array</title>
 </head>
 <body>

 <?php
 
 // Comma separated list
 $fruitlist = "apples, pears, bananas, oranges, lemons";
  
 // Create an array by splitting the list (with comma as delimiter)
 $arrFruits = explode(",", $fruitlist);
  
    // Write the values from our array
    echo "<p>The list of fruits:</p>";
  
    echo "<ul>";
    echo "<li>" . $arrFruits[0] . "</li>";
    echo "<li>" . $arrFruits[1] . "</li>";
    echo "<li>" . $arrFruits[2] . "</li>";
    echo "<li>" . $arrFruits[3] . "</li>";
    echo "<li>" . $arrFruits[4] . "</li>";
    echo "</ul>";

 ?>

 </body>
 </html>

Loop through an array

 Now we will look at how you can loop through an array.
When you know how many elements an array contains, it is not a problem defining the loop. You simply start with 0 and let the loop continue to the number of items available. In the example with the fruits, you would loop through the array like this:


 <html>
 <head>
 <title>Array</title>

 </head>
 <body>

 <?php
 
 // Comma separated list
 $fruitlist = "apples, pears, bananas, oranges, lemons";
  
 // Create an array by splitting the list (with a comma as delimiter)
 $arrFruits = explode (",", $fruitlist);
  
    echo "<p>The list of fruits:</p>";
    echo "<ul>";
  
    // Loop through the array $arrFruits
    for ($x=0; $x<=4; $x++) {
       echo "<li>" . $arrFruits[$x] . "</li>";
    }
  
    echo "</ul>";

 ?>
  
 </body>
 </html>

How to find the size of an array

But what if we add another fruit to the list? Then our array will contain one element more - which will get the identification number 5. Do you see the problem? Then we need to change the loop, so it runs from 0 to 5, or else not all of the elements will be included.
Wouldn't it be nice if we automatically could find out how many elements an array contains?
That's exactly what we can do with the function foreach. Now we can make a loop that works regardless of the number of elements:


 <?php
    foreach ($arrFruits as $x) {
       echo $x;
    }
 ?>

 
This loop will work regardless of how many or few elements the array contains.

Another example

Below is another example of how you can use an array to write the name of the month:


 <html>
 <head>
 <title>Array</title>

 </head>
 <body>
 
 <?php
 // Creates array with each month.
 // Creates array with the months. Note the comma before January - because there is no month with the number 0
 $arrMonths = array("","January","February","March","April","May","June","July","August","September","October","November","December");
  
 // Call the array with the number of the month - write to the client
 echo $arrMonths[date("n")];
 ?>

 </body>
 </html>

 

Meta Function



array get_meta_tags ( string $filename [, bool $use_include_path = false ] )

Opens filename and parses it line by line for <meta> tags in the file. The parsing stops at </head>.

Parameters

filename
The path to the HTML file, as a string. This can be a local file or an URL.
Example #1 What get_meta_tags() parses
<meta name="author" content="name">
<meta name="keywords" content="php documentation">
<meta name="DESCRIPTION" content="a php manual">
<meta name="geo.position" content="49.33;-86.59">
</head> <!-- parsing stops here -->
(pay attention to line endings - PHP uses a native function to parse the input, so a Mac file won't work on Unix).
use_include_path
Setting use_include_path to TRUE will result in PHP trying to open the file along the standard include path as per the include_path directive. This is used for local files, not URLs.

 Return Values

Returns an array with all the parsed meta tags.
The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned.

Examples

Example #1 What get_meta_tags() returns

<?php// Assuming the above tags are at www.example.com$tags get_meta_tags('http://www.example.com/');// Notice how the keys are all lowercase now, and
// how . was replaced by _ in the key.
echo $tags['author']; // nameecho $tags['keywords']; // php documentationecho $tags['description']; // a php manualecho $tags['geo_position']; // 49.33;-86.59?>




Example #2 What get_meta_tags() returns
<?phpfunction get_meta_data($content)
{
$content = strtolower($content);
$content = preg_replace("'<style[^>]*>.*</style>'siU",'',$content); // strip js
$content = preg_replace("'<script[^>]*>.*</script>'siU",'',$content); // strip css
$split = explode("\n",$content);
foreach (
$split as $k => $v)
{
if (
strpos(' '.$v,'<meta')) {
preg_match_all("/<meta[^>]+(http\-equiv|name)=\"([^\"]*)\"[^>]" . "+content=\"([^\"]*)\"[^>]*>/i",$v, $split_content[],PREG_PATTERN_ORDER);;
}
}
return
$split_content;
}
?>



Example #3 What get_meta_tags() returns


<?php/*
** Extracts and formats meta tag content
*/
function get_meta_data($url, $searchkey='') {
$data = get_meta_tags($url); // get the meta data in an array
foreach($data as $key => $value) {
if(
mb_detect_encoding($value, 'UTF-8, ISO-8859-1', true) != 'ISO-8859-1') { // check whether the content is UTF-8 or ISO-8859-1
$value = utf8_decode($value); // if UTF-8 decode it
}
$value = strtr($value, get_html_translation_table(HTML_ENTITIES)); // mask the content
if($searchkey != '') { // if only one meta tag is in demand e.g. 'description'
if($key == $searchkey) {
$str = $value; // just return the value
}
} else {
// all meta tags
$pattern = '/ |,/i'; // ' ' or ','
$array = preg_split($pattern, $value, -1, PREG_SPLIT_NO_EMPTY); // split it in an array, so we have the count of words
$str .= '<p><span style="display:block;color:#000000;font-weight:bold;">' . $key . ' <span style="font-weight:normal;">(' . count($array) . ' words | ' . strlen($value) . ' chars)</span></span>' . $value . '</p>'; // format data with count of words and chars
}
}
return
$str;
}
$content .= get_meta_data("http://www.example.com/");/*
output looks like this:

description (23 words | 167 chars)
SELFHTML 8.1.2 - Die bekannte Dokumentation zu HTML, JavaScript und CGI/Perl - Tutorial und Referenz, mit etlichen Zusatztips zu Design, Grafik, Projektverwaltung usw.

keywords (13 words | 119 chars)
SELFHTML, HTML, Dynamic HTML, JavaScript, CGI, Perl, Grafik, WWW-Seiten, Web-Seiten, Hilfe, Dokumentation, Beschreibung

etc.

*/
$content .= get_meta_data("http://www.example.com/", "description");
?>

Var "GET" In PHP



$HTTP_GET_VARS contains the same initial information, but is not a superglobal. (Note that 
$HTTP_GET_VARS and $_GET are different variables and that PHP handles them as such)

Example #1 $_GET example

<?phpecho 'Hello ' htmlspecialchars($_GET["name"]) . '!';?>

Assuming the user entered http://example.com/?name=Hannes
The above example will output something similar to:
Hello Hannes! 

Your first step in XML , Introduction




The following points explain the purpose of XML. 

  • XML stands for EXtensible Markup Language
  • XML is a markup language much like HTML.
  • XML was designed to describe data.
  • XML tags are not predefined in XML. You must define your own tags.
  • XML uses a DTD (Document Type Definition) to describe the data.
  • XML with a DTD is designed to be self describing.

The Latest Specifications on XML which are released from W3C Working Group can be viewed here. 

It is important to understand that XML is not a replacement for HTML. The main purpose of HTML is the Format the Data that is presented through Browser. For Displaying data on Handheld Devices WML is used. The purpose of XML is not to Format the Data to be displayed. It's mostly used to store and transfer data and to describe the data. It is device or Language independent and can be used for Transmitting Data to any device. The Parser (Or the Program which is capable of understanding the Tags and returning the Text in a Valid Format) on the corresponding Device will help in displaying the data in required format.

You can define your own tags in XML file. The way these tags will be interpreted will depend on the program which is going to get this XML file. The data embedded within these tags will be used according to logic implemented in the secondary program which is going to get this XML as Feed. This point will be more clear hen we start explaining you about how to use the Parsers in next few pages.

What is JQUERY ?




jQuery is an amazing JavaScript library that makes it easy to create wonderful web effects in just a few lines of code. As the website says:”
“jQuery is a JavaScript library that takes this motto to heart: Writing JavaScript code should be fun. jQuery achieves this goal by taking common, repetitive, tasks, stripping out all the unnecessary markup, and leaving them short, smart and understandable.”
Maybe you are thinking… “Why I would need another JavaScript library”? Just give a try and you will see how simple and powerful it is even if you have already used Moo.fx, Scriptaculous, TW-SACK or Prototype.

Why I should use jQuery?

Simple. In just one glance at the source code of a page using jQuery you’ll see how easy it is to use, how much it accomplishes in so few lines of code, and how graceful it is.
My mind was opened one day when I stumbled across some code written with jQuery. I was flipping through the RSS feeds and reading my daily dose of web design blogs when I came across an example of JavaScript loveliness that used jQuery. Truth be told, the code on that site had some browser related bugs… but the concept was something I hadn’t seen before.

What about the code?

The code looked almost simple. Like nothing I had seen before. It made sense.
I started reading through the documentation and was amazed to see how much could be done with so little extra code.

When you can use jQuery?

You should use jQuery when you need:
  • A small library that gives you powerful control over the Document Object Model
  • With very little effort or work on your part
Or
  • Quick access to AJAX
  • Without a lot of bloat (overhead - wasted code)
  • And some basic animation effects to spice things up
But…
If you need super fancy effects for animation, drag and drop, and super smooth animation then you’ll probably want to use Prototype and one of the many great library created to enhance the effects.

What Is CSS ?




CSS is an acronym for Cascading Style Sheets.

What can I do with CSS?

CSS is a style language that defines layout of HTML documents. For example, CSS covers fonts, colours, margins, lines, height, width, background images, advanced positions and many other things. Just wait and see!

HTML can be (mis-)used to add layout to websites. But CSS offers more options and is more accurate and sophisticated. CSS is supported by all browsers today.

After only a few lessons of this tutorial you will be able to make your own style sheets using CSS to give your website a new great look.

What is the difference between CSS and HTML?

HTML is used to structure content. CSS is used for formatting structured content.

Okay, it sounds a bit technical and confusing. But please continue reading. It will all make sense to you soon.
Back in the good old days when Madonna was a virgin and a guy called Tim Berners Lee invented the World Wide Web, the language HTML was only used to add structure to text. An author could mark his text by stating "this is a headline" or "this is a paragraph" using HTML tags such as <h1> and <p>.

As the Web gained popularity, designers started looking for possibilities to add layout to online documents. To meet this demand, the browser producers (at that time Netscape and Microsoft) invented new HTML tags such as for example <font> which differed from the original HTML tags by defining layout - and not structure.

This also led to a situation where original structure tags such as <table> were increasingly being misused to layout pages instead of adding structure to text. Many new layout tags such as <blink> were only supported by one type of browser. "You need browser X to view this page" became a common disclaimer on web sites.

CSS was invented to remedy this situation by providing web designers with sophisticated layout opportunities supported by all browsers. At the same time, separation of the presentation style of documents from the content of documents, makes site maintenance a lot easier.