Tuesday, January 8, 2008

PHP Advanced

PHP Date - Robust Dates and Times
While PHP's date() function may seem to have an overwhelming amount of options available, isn't it always better to have more choices than not enough? With PHP's date function you format timestamps, so they are more human readable.
This lesson will teach you how to display the current time, formating PHP's timestamp, and show you all the various date arguments for reference purposes.
PHP Date - The Timestamp
The date function always formats a timestamp, whether you supply one or not. What's a timestamp? Good question!
Timestamp: A timestamp is the number of seconds from January 1, 1970 at 00:00. Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize.
PHP Date - What Time Is It?
The date function uses letters of the alphabet to represent various parts of a typical date and time format. The letters we will be using in our first example are:
d: The day of the month. The type of output you can expect is 01 through 31.
m: The current month, as a number. You can expect 01 through 12.
y: The current year in two digits ##. You can expect 00 through 99
We'll tell you the rest of the options later, but for now let's use those above letters to format a simple date! The letters that PHP uses to represent parts of date and time will automatically be converted by PHP.
However, other characters like a slash "/" can be inserted between the letters to add additional formatting. We have opted to use the slash in our example.
PHP Code:
echo date("m/d/y");
?>
If the 2010 Winter Olympics were just finishing up, you would see something like:
Display:
02/27/10
Be sure to test this out on your own PHP enabled server, it's really great to see the instant results available with PHP date!
PHP Date - Supplying a Timestamp
As our first example shows, the first argument of the date function tells PHP how you would like your date and time displayed. The second argument allows for a timestamp and is optional.
This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime.
Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp.
mktime(hour, minute, second, month, day, year, daylight savings time)
PHP Code:
$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));
echo "Tomorrow is ".date("m/d/y", $tomorrow);
?>
Notice that we used one letter at a time with the function date to get the month, day and year. For example the date("m") will return the month's number 01-12.
If we were to run our new script just after the 2010 Winter Olympics our display would look like:
Display:
Tomorrow is 02/28/10
PHP Date - Reference
Now that you know the basics of using PHP's date function, you can easily plug in any of the following letters to format your timestamp to meet your needs.
Important Full Date and Time:
r: Displays the full date, time and timezone offset. It is equivalent to manually entering date("D, d M Y H:i:s O")
Time:
a: am or pm depending on the time
A: AM or PM depending on the time
g: Hour without leading zeroes. Values are 1 through 12.
G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
h: Hour with leading zeroes. Values 01 through 12.
H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
i: Minute with leading zeroes. Values 00 through 59.
s: Seconds with leading zeroes. Values 00 through 59.
Day:
d: Day of the month with leading zeroes. Values are 01 through 31.
j: Day of the month without leading zeroes. Values 1 through 31
D: Day of the week abbreviations. Sun through Sat
l: Day of the week. Values Sunday through Saturday
w: Day of the week without leading zeroes. Values 0 through 6.
z: Day of the year without leading zeroes. Values 0 through 365.
Month:
m: Month number with leading zeroes. Values 01 through 12
n: Month number without leading zeroes. Values 1 through 12
M: Abbreviation for the month. Values Jan through Dec
F: Normal month representation. Values January through December.
t: The number of days in the month. Values 28 through 31.
Year:
L: 1 if it's a leap year and 0 if it isn't.
Y: A four digit year format
y: A two digit year format. Values 00 through 99.
Other Formatting:
U: The number of seconds since the Unix Epoch (January 1, 1970)
O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours
We suggest that you take a few minutes to create several timestamps using PHP's mktime function and just try out all these different letters to get your feet wet with PHP's date function.

PHP Sessions - Why Use Them?
As a website becomes more sophisticated, so must the code that backs it. When you get to a stage where your website need to pass along user data from one page to another, it might be time to start thinking about using PHP sessions.
A normal HTML website will not pass data from one page to another. In other words, all information is forgotten when a new page is loaded. This makes it quite a problem for tasks like a shopping cart, which requires data(the user's selected product) to be remembered from one page to the next.
PHP Sessions - Overview
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.
Note:If you are not experienced with session programming it is not recommended that you use sessions on a website that requires high-security, as there are security holes that take some advanced techniques to plug.
Starting a PHP Session
Before you can begin storing user information in your PHP session, you must first start the session. When you start a session, it must be at the very beginning of your code, before any HTML or text is sent.
Below is a simple script that you should place at the beginning of your PHP code to start up a PHP session.
PHP Code:
session_start(); // start up your PHP session!
?>
This tiny piece of code will register the user's session with the server, allow you to start saving user information and assign a UID (unique identification number) 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:
session_start();
$_SESSION['views'] = 1; // store session data
echo "Pageviews = ". $_SESSION['views']; //retrieve data
?>
Display:
Pageviews = 1
In this example we learned how to store a variable to the session associative array $_SESSION and also how to retrieve data from that same array.
PHP Sessions: Using PHP's isset Function
Now that you know can easily store and retrieve data from the $_SESSION array, we can now explore some of the real functionality of sessions. When you create a variable and store it in a session, you probably want to use it in the future. However, before you use a session variable it is necessary that you check to see if it exists already!
This is where PHP's isset function comes in handy. isset is a function that takes any variable you want to use and checks to see if it has been set. That is, it has already been assigned a value.
With our previous example, we can create a very simple pageview counter by using isset to check if the pageview variable has already been created. If it has we can increment our counter. If it doesn't exist we can create a pageview counter and set it to one. Here is the code to get this job done:
PHP Code:
session_start();
if(isset($_SESSION['views']))
$_SESSION['views'] = $_SESSION['views']+ 1;
else
$_SESSION['views'] = 1;

echo "views = ". $_SESSION['views'];
?>
The first time you run this script on a freshly opened browser the if statement will fail because no session variable views would have been stored yet. However, if you were to refresh the page the if statement would be true and the counter would increment by one. Each time you reran this script you would see an increase in view by one.
Cleaning and Destroying your Session
Although a session's data is temporary and does not require that you explicitly clean after yourself, you may wish to delete some data for your various tasks.
Imagine that you were running an online business and a user used your website to buy your goods. The user has just completed a transaction on your website and you now want to remove everything from their shopping cart.
PHP Code:
session_start();
if(isset($_SESSION['cart']))
unset($_SESSION['cart']);
?>
You can also completely destroy the session entirely by calling the session_destroy function.
PHP Code:
session_start();
session_destroy();
?>
Destroy will reset your session, so don't call that function unless you are entirely comfortable losing all your stored session data!


PHP Cookies - Background
Cookies have been around for quite some time on the internet. They were invented to allow webmaster's to store information about the user and their visit on the user's computer.
At first they were feared by the general public because it was believed they were a serious privacy risk. Nowadays nearly everyone has cookies enabled on their browser, partly because there are worse things to worry about and partly because all of the "trustworthy" websites now use cookies.
This lesson will teach you the basics of storing a cookie and retrieving a cookie, as well as explaining the various options you can set with your cookie.
Creating Your First PHP Cookie
When you create a cookie, using the function setcookie, you must specify three arguments. These arguments are setcookie(name, value, expiration):
1. name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!
2. value: The value that is stored in your cookie. Common values are username(string) and last visit(date).
3. expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.
In this example we will be creating a cookie that stores the user's last visit to measure how often people return to visit our webpage. We want to ignore people that take longer than two months to return to the site, so we will set the cookie's expiration date to two months in the future!
PHP Code:
//Calculate 60 days in the future
//seconds * minutes * hours * days + current time
$inTwoMonths = 60 * 60 * 24 * 60 + time();
setcookie('lastVisit', date("G:i - m/d/y"), $inTwoMonths);
?>
Don't worry if you can't follow the somewhat involved date calculations in this example. The important part is that you know how to set a cookie, by specifying the three important arguments: name, value and expiration date.
Retrieving Your Fresh Cookie
If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!
PHP Code:
if(isset($_COOKIE['lastVisit']))
$visit = $_COOKIE['lastVisit'];
else
echo "You've got some stale cookies!";

echo "Your last visit was - ". $visit;
?>
This handy script first uses the isset function to be sure that our "lastVisit" cookie still exists on the user's PC, if it does, then the user's last visit is displayed. If the user visited our site on February 28, 2008 it might look something like this:
Display:
Your last visit was - 11:48 - 02/28/08

No comments: