This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Monday 22 April 2013

PHP Sessions


PHP Sessions

A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one application.

PHP Session Variables



  • When you are working with an application, you open it, do some changes and then you close it. This is much like a Session.
  • The computer knows who you are. It knows when you start the application and when you end.
  • But on the internet there is one problem: the web server does not know who you are and what you do because the HTTP address doesn't maintain state.
  • A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc).
  • However, session information is temporary and will be deleted after the user has left the website.
  • If you need a permanent storage you may want to store the data in a database.
  • Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID.
  • The UID is either stored in a cookie or is propagated in the URL. 
  • A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping cart items, etc).
  • However, this session information is temporary and is usually deleted very quickly after the user has left the website that uses sessions.
  • It is important to ponder if the sessions' temporary storage is applicable to your website.
  • If you require a more permanent storage you will need to find another solution, like a MySQL database.
  • Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID.
  • This helps to prevent two users' data from getting confused with one another when visiting the same webpage.



Starting a PHP Session


Before you can store user information in your PHP session, you must first start up the session.


<?php session_start(); ?>

<html>
<body>

</body>
</html>


The code above will register the user's session with the server, allow you to start saving user information, and assign a UID for that user's session.

storing a session variable

When you want to store user data in a session use the $_SESSION associative array.

This is where you both store and retrieve session data. In previous versions of PHP there were other ways to perform this store operation, but it has been updated and this is the correct way to do it.


PHP Code:

<?php
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>

Display:

Pageviews = 1



Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:


PHP code:

<?php
session_start();
if(isset($_SESSION['views']))
  unset($_SESSION['views']);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

session_destroy() will reset your session and you will lose all your stored session data.

PHP require


PHP require

Just like the previous lesson, the require command is used to include a file into your PHP code.

However there is one huge difference between the two commands, though it might not seem that big of a deal.

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error.

In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.
require will produce a fatal error (E_COMPILE_ERROR) and stop the script.


Syntax:

require 'filename';

PHP Code:

<?php
require("noFileExistsHere.php");
echo "Hello World!";
?>

Display:

Warning: main(noFileExistsHere.php): failed to open stream: No such file or directory in /home/websiteName/FolderName/tizagScript.php on line 2

Fatal error: main(): Failed opening required 'noFileExistsHere.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/websiteName/FolderName/tizagScript.php on line 2

The echo statement was not executed because our script execution died after the require command returned a fatal error!
We recommend that you use require instead of include because your scripts should not be executing if necessary files are missing or misnamed.


PHP $_GET & PHP $_POST


 The $_GET Variable

The predefined $_GET variable is used to collect values in a form with method="get"

Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and has limits on the amount of information to send.

When using method="get" in HTML forms, all variable names and values are displayed in the URL.

The get method is not suitable for very large variable values. It should not be used with values exceeding 2000 characters.


·   The GET method produces a long string that appears in your server logs, in the browser's Location: box.

·  The GET method is restricted to send upto 1024 characters only.

·  Never use GET method if you have password or other sensitive information to be sent to the server.

·  GET can't be used to send binary data, like images or word documents, to the server.

· The data sent by GET method can be accessed using QUERY_STRING environment variable.

·  The PHP provides $_GET associative array to access all the sent information using GET method.


Example:

<?php
  if( $_GET["name"] || $_GET["age"] )
  {
     echo "Welcome ". $_GET['name']. "<br />";
     echo "You are ". $_GET['age']. " years old.";
     exit();
  }
?>

<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="GET">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>


Output:

Welcome John!

You are 28 years old.



The $_POST Variable

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

·  The POST method does not have any restriction on data size to be sent.

·   The POST method can be used to send ASCII as well as binary data.

·   The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.

The PHP provides $_POST associative array to access all the sent information using GET method.

The predefined $_POST variable is used to collect values from a form sent with method="post".

Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

Note: However, there is an 8 MB max size for the POST method, by default (can be changed by setting the post_max_size in the php.ini file).
  

Example:

<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>

<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">
  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />
  <input type="submit" />
  </form>
</body>
</html>


Output:

Welcome John!

You are 28 years old.






PHP File Upload


PHP File Upload

With PHP, it is possible to upload files to the server.

A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.

When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.

The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.


·        uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.

·        $_FILES['uploadedfile']['name'] - name contains the original path of the user uploaded file.

·        $_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.

Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.

If the upload is successful, then you will see the text "The file filename has been uploaded".

This is because move_uploaded_file returns true if the file was moved, and false if it had a problem.

If there was a problem then the error message "There was an error uploading the file, please try again!" would be displayed.

Example:

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

Upload_file.php

<?php
if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br>";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br>";

  echo "Type: " . $_FILES["file"]["type"] . "<br>";

  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }
?>

PHP File


PHP File Handling

The fopen() function is used to open files in PHP.

Opening a File


The fopen() function is used to open files in PHP.
The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:

<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>

·        The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.

·        Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.

·        When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong.

·        Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.

·        It is our hope that you will be able to avoid these and other slipups after reading this tutorial.

·        However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.
  

Closing a File


The fclose() function is used to close an open file.
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>

Reading a File Line by Line


The fgets() function is used to read a single line from a file.

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br>";
  }
fclose($file);
?>
  

Reading a File Character by Character


The fgetc() function is used to read a single character from a file.

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
  {
  echo fgetc($file);
  }
fclose($file);
?>

PHP Calendar


PHP Calendar Introduction

·        The calendar extension contains functions that simplifies converting between different calendar formats.
·        It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C.
·        Note: To convert between calendar formats, you must first convert to Julian Day Count, then to the calendar of your choice.

Installation


For these functions to work, you have to compile PHP with --enable-calendar.
The Windows version of PHP has built-in support for this extension.

Calendar Functions:

-   cal_days_in_month — Return the number of days in a month for a given year and calendar
-   cal_from_jd — Converts from Julian Day Count to a supported calendar
-   cal_info — Returns information about a particular calendar
-   cal_to_jd — Converts from a supported calendar to Julian Day Count
-   easter_date — Get Unix timestamp for midnight on Easter of a given year
-   easter_days — Get number of days after March 21 on which Easter falls for a given year
-   FrenchToJD — Converts a date from the French Republican Calendar to a Julian Day Count
-   GregorianToJD — Converts a Gregorian date to Julian Day Count
-   JDDayOfWeek — Returns the day of the week
-   JDMonthName — Returns a month name
-   JDToFrench — Converts a Julian Day Count to the French Republican Calendar
-   JDToGregorian — Converts Julian Day Count to Gregorian date
-   jdtojewish — Converts a Julian day count to a Jewish calendar date
-   JDToJulian — Converts a Julian Day Count to a Julian Calendar Date
-   jdtounix — Convert Julian Day to Unix timestamp
-   JewishToJD — Converts a date in the Jewish Calendar to Julian Day Count
-   JulianToJD — Converts a Julian Calendar date to Julian Day Count
-   unixtojd — Convert Unix timestamp to Julian Day


 PHP code for calendar:

<?php
function isLeapYear($year){
    // 1 januari 1900 is monday, use century-check only when 1 januari 1900 is monday;
    if(($year % 100 == 0) and ($year % 400 != 0)) return(0);
    if($year % 4 == 0) return(1);
    return(0);
}
function getWeekDay($year, $month, $day){
    $dcm = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    // 1 januari 1900 is sunday;
    $gwdYear = 1899;
    $gwdMonth = 12;
    $gwdDay = 31;
    // 1 januari 1900 is monday;
    $gwdYear = 1899;
    $gwdMonth = 12;
    $gwdDay = 30;
    $diffDays = 0;
    $diffDays = $diffDays + $day;
    for($m = (($year * 12) + $month) - 1; $m > (($gwdYear * 12) + $gwdMonth); $m--)    {
        $y = (($m - 1) / 12);
        $i = ($m % 12) + 12;
        if(isLeapYear($y) == 1)         {
            $dcm[1] = 29; $dcm[13] = 29;
        }else{
            $dcm[1] = 28; $dcm[13] = 28;
        }
        $diffDays = $diffDays + $dcm[$i-1];
    }
    $diffDays = $diffDays + ($dcm[$gwdMonth - 1] - $gwdDay);
    $weekDay = ($diffDays % 7) - 2;
    if($weekDay < 0) $weekDay = $weekDay + 7;
    return($weekDay + 1);
}
function getDateNumber($year, $month, $day){
    $diffDays = 0;
    for($y = 0; $y < $year; $y++)    {
        $diffDays = $diffDays + 365;
        if(isLeapYear($y) == 1) $diffDays = $diffDays + 1;
    }
    for($m = 1; $m < $month; $m++)    {
        if($m == 1 or $m == 3 or $m == 5 or $m == 7 or $m == 8 or $m == 10 or $m == 12)    {
            $diffDays = $diffDays + 31;
        }else{
            $diffDays = $diffDays + 30;
        }
        if(isLeapYear($year) == 1 and $m == 2) $diffDays = $diffDays - 1;
        if(isLeapYear($year) == 0 and $m == 2) $diffDays = $diffDays - 2;
    }
    $diffDays = $diffDays + $day;
    return($diffDays);
}
function CalculateIsoWeekday($year, $month, $day){
// This function converts the weekday-numbers from the
// standard function to an offset acc. to the ISO version
// monday -> 0, ... , sunday -> 6
$n = getWeekday($year, $month, $day);
    return($n - 1);
}
function getWeekNumber($year, $month, $day){
    // The year value is preset with that of the input date
    $YearInQuestion = $year;
    // Calculate offset to monday from the input date
    $InputDateOffset = CalculateIsoWeekday($year, $month, $day);
    // Calculate offsets for the first/last day of the year
    $January1Offset = CalculateIsoWeekday($YearInQuestion, 1, 1);
    $December31Offset = CalculateIsoWeekday($YearInQuestion, 12, 31);
    // If the input date is before the 4th of January and the year starts with
    // a friday, saturday or sunday, the week belongs to the previous year
    // if the entered date is not a monday or tuesday
    if($month == 1 and $day < 4 and $January1Offset > 3 and $InputDateOffset > 1)    {
        $YearInQuestion = $YearInQuestion - 1;
    }
    // If the input date is after the 28th of December and the year ends with
    // a monday, tuesday or wednesday, then the week belongs to the following year
    // if the entered date is not a saturday or sunday
    if ($month == 12 and $day > 28 and $December31Offset < 3 and $InputDateOffset < 5)    {
        $YearInQuestion = $YearInQuestion + 1;
    }
    // The 4th of January defines week #1
    $January4 = getDatenumber($YearInQuestion, 1, 4);
    // Offset to the monday of week #1
    $FirstMondayOfYear = getDatenumber($YearInQuestion, 1, 4 - CalculateIsoWeekday($YearInQuestion, 1, 4));
    // The time range between the monday of week #1 and the monday
    // of the week in question is divided by 7, plus 1 for the first week
    $weeknum = (getDateNumber($year, $month, $day) - $InputDateOffset - $FirstMondayOfYear ) / 7 + 1;
    return($weeknum);    
}
function phpdate($year, $month, $day, $format){
    if($format == "mmmm")    {
        if($month == 1) return("january");
        if($month == 2) return("february");
        if($month == 3) return("march");
        if($month == 4) return("april");
        if($month == 5) return("may");
        if($month == 6) return("june");
        if($month == 7) return("july");
        if($month == 8) return("august");
        if($month == 9) return("september");
        if($month == 10) return("october");
        if($month == 11) return("november");
        if($month == 12) return("december");
    }
    if($format == "yyyy")    {
        return($year);
    }
}
function getCalendar() {
    if($_GET["year"] == "") $year = date("Y"); else $year = $_GET["year"];
    if($_GET["month"] == "") $month = date("n"); else $month = $_GET["month"];
    if($_GET["day"] == "") $day = date("d"); else $day = $_GET["day"];
    $dow = array("mon", "tue", "wed", "thu", "fri", "sat", "sun");
    if(isLeapYear($year) == 1)    {
        $dom = array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    }else{
        $dom = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    }
    $calendar = "<center><table style='background : ThreedFace; border-style : outset; font-family : Verdana; font-size : 10pt;border-width : 2px;' >";
    $calendar .= "<tr>";
    $calendar .= "<th bgcolor=#000080 colspan='8'>";
    $calendar .= "<font color=white>C A L E N D A R</font>";
    $calendar .= "</th>";
    $calendar .= "</tr>";
    $calendar .= "<tr>";
    $calendar .= "<th><center>";
    $m = $month;
    $y = $year - 1;
    if($year != 1900) $calendar .= "<a style='text-decoration : none; color : #808080;' href='?year=" . $y . "&month=" . $m . "&day=" . 1 . "' ><font face=webdings>7</font></a>";
    if($month == 1) {
        $m = 12;
        $y = $year - 1;
    }else{
        $m = $month - 1;
        $y = $year;
    }
    if(!($year == 1900 and $month == 1)) $calendar .= "<a style='text-decoration : none; color : #808080;' href='?year=" . $y . "&month=" . $m . "&day=" . 1 . "' ><font face=webdings>3</font></a>";
    $calendar .= "</th>";
    $calendar .= "<th nowrap colspan='6'><center>";
    $calendar .= phpdate($year, $month, $day, "mmmm", $lang) . " " . phpdate($year, $month, $day, "yyyy", $lang);
    $calendar .= "</th>";
    $calendar .= "<th><center>";
    if($month == 12){
        $m = 1;
        $y = $year + 1;
    }else{
        $m = $month + 1;
        $y = $year;
    }
    $calendar .= "<a style='text-decoration : none; color : #808080;' href='?year=" . $y . "&month=" . $m . "&day=" . 1 . "' ><font face=webdings>4</font></a>";
    $m = $month;
    $y = $year + 1;
    $calendar .= "<a style='text-decoration : none; color : #808080;' href='?year=" . $y . "&month=" . $m . "&day=" . 1 . "' ><font face=webdings>8</font></a>";
    $calendar .= "</th>";
    $calendar .= "</tr>";
    $dayno = 2 - getWeekDay($year, $month, 1);
    $daymin = 1;
    $daymax = $dom[$month - 1];
    if($month == 1) {$daymaxl = 12;} else {$daymaxl = $month - 1;}
    for($row = 1; $row <= 7; $row++)    {
        for($col = 1; $col <= 8; $col++)        {
            $calendar .= "<td style='border-color : black; border-width : 2px;' ><center>";
            // print weekday headers
            if($row == 1 and $col != 1) {
                $calendar .= "<font color=#000080>";
                $calendar .= $dow[$col-1-1];
                $calendar .= "</font>";
            }
            // print weeknumbers
            if($row != 1 and $col == 1)    {    
                $calendar .= "<font color=#008000>";
                if($dayno < $daymin){
                    $y = $year;
                    if($month == 1) $m = 12;
                    if($month != 1) $m = $month - 1;
                    if($month == 1) $y = $year - 1;
                    $d = ($dom[$daymaxl - 1]) + $dayno;
                    $calendar .= sprintf("%02d",getWeekNumber($y, $m, $d));
                }else{
                    if($dayno > $daymax){
                        $y = $year;
                        if($month == 12) $m = 1;
                        if($month != 12) $m = $month + 1;
                        if($month == 12) $y = $year + 1;
                        $d = $dayno - $daymax;
                        $calendar .= sprintf("%02d",getWeekNumber($y, $m, $d));
                    }else{
                        $calendar .= sprintf("%02d",getWeekNumber($year, $month, $dayno));
                    }
                }
                $calendar .= "</font>";
            }
            // print day numbers
            if($row > 1 and $col != 1){
                if($dayno < $daymin){
                    $calendar .= "<font color=#808080>";
                    $calendar .= ($dom[$daymaxl - 1]) + $dayno;
                    $calendar .= "</font>";
                }else{
                    if($dayno > $daymax){
                        $calendar .= "<font color=#808080>";
                        $calendar .= $dayno - $daymax;
                        $calendar .= "</font>";
                    }else{
                        $calendar .= $dayno;
                    }
                }
                $dayno = $dayno + 1;
            }
            $calendar .= "</td>";
        }
        $calendar .= "</tr><tr>";
    }
    $calendar .= "</tr>";
    $calendar .= "</table>";
    return($calendar);
}
?>
<html>
<title>getCalendar()</title>
<body bgcolor=#D0D0D0>
<?php echo(getCalendar()); ?>
</body>
</html>


Output:



Twitter Delicious Facebook Digg Stumbleupon Favorites More