PART III : User Input / Time & Dates

In this section we will cover:

HTML form management
File uploads
Cookies
Magic Quotes
Sessions
Times and dates in PHP
Formatting date values
Locale-dependent date formatting
Date validation

HTML Form Management
HTML forms are submitted by the browser using either GET or POST
GET transaction data is sent as part of the query string
POST data is sent as part of the HTTP transaction itself
POST is often considered “safer” than GET—WRONG!
POST data is made available as part of the $_POST superglobal array
GET data is made available as part of the $_GET superglobal array
Both are “superglobal”—in-context everywhere in your scripts
If duplicates are present, only the ones sent last end up in the appropriate superglobal
HTML Form Management
Element arrays can also be sending by postfixing the element names with []
These are transformed into arrays by PHP. The brackets are discarded. A very common (and pernicious) type of security attack. You can also specify your own keys by placing them inside the brackets:

input type=”hidden” name=”a[ts]” value=”1”

Will result in $a[‘ts’] = 1 being inserted in the appropriate superglobal.

Uploading Files
Files are uploaded through a special type of HTML form:

form enctype="multipart/form-data" action="/
upload.php" method="post"
input type="my_file" type="file"
input type="hidden" name="MAX_FILE_SIZE"
value="100000"

An arbitrary number of files can be uploaded at the same time

Uploading Files
Once uploaded, file information is available through the $_FILES superglobal array
[my_file] => Array
(
[name] => php.gif
[type] => image/gif
[tmp_name] => /tmp/phpMJLN2g
[error] => 0
[size] => 4644
)
Uploaded file can be moved using move_uploaded_file()
You can also determine whether a file has been uploaded using is_uploaded_file()
Uploading Files
File uploads are controlled by several PHP.INI settings:
file_uploads — whether or not uploads are enabled
upload_tmp_dir — where temporary uploaded files are stored
upload_max_filesize — the maximum size of each uploaded file
post_max_size — the maximum size of a POST transaction
max_input_time — the maximum time allowed to process a form
Cookies
Cookies are small text strings that are stored client-side
Cookies are sent to the client as part of the HTTP response, and back as part of the HTTP headers. Cookies are notoriously unreliable:
Some browsers are set not to accept them. Some users do not accept them
Incorrect date/time configuration on the client’s end can lead to cookies expiring before they are set
Cookies
To set a cookie:
setcookie ($name, $value, $expires, $path, $domain);
setcookie ($name, $value); // sets a session cookie
Cookies are then available in the $_COOKIE superglobal array:
$_COOKIE[‘mycookie’]
$_COOKIE is populated at the beginning of the script.
Therefore, it does not contain cookies you set during the script itself (unless you update it manually)
You cannot “delete” a cookie. You can set it to Null or an empty string
Remember not to use isset()! You can expire it explicitly
$_REQUEST
$_REQUEST is a superglobal populated from other superglobals
You have no control over how data ends up in it. The variables_order PHP.INI setting controls how data is loaded into it, usually Get -> Post -> Cookie
Generally speaking, you’re better off not using it, as it is a virtual security black hole.
Magic Quotes
By default, PHP will escape any “special” characters found inside the user’s input
You should not rely on this setting being on (as most sysadmins turn it off anyway)
You also (and most definitely) should not rely on it performing proper input filtering for you
In fact, supply your own escaping and “undo” magic quotes if they are enabled!
Sessions
Sessions are mechanisms that make it possible to create a per-visitor storage mechanism on your site
Sessions we born—and remain—a hack, so you can only depend on them up to a certain point
On the client side, sessions are just unique IDs passed back and forth between client and server
On the server side, they can contain arbitrary informaiton
In order to write to a session, you must explicitly start it session_start()
This is not necessary if session.auto_start is on in your PHP.INI file
You can then write directly into the $_SESSION array, and the elements you create will be transparently saved into the session storage mechanism
$_SESSION[‘test’] = $myValue

By default, session data is stored in files; however, you can specify a number of built-in filters
You can also define your own session handlers in “userland”

Date Manipulation in PHP
For the most part, PHP handles dates in the UNIX timestamp format
Timestamps indicate the number of seconds from the UNIX “epoch”, January 1st, 1970. Not all platforms support negative timestamps (e.g.: Windows prior to PHP 5.1)
Timestamps are very handy because they are just large intergers. This makes it easy to manipulate them, but not necessarily to represent them. They are also handy for time calculations For more precision, you can use microtime()

Another way of representing dates is through date arrays using getdate()
A date array contains separate elements for each component of a date
[seconds] => 15 // 0 - 59
[minutes] => 15 // 0 - 59
[hours] => 9 // 0 - 23
[mday] => 4 // 1 - 31
[wday] => 3 // 0 - 6
[mon] => 8 // 1 - 12
[year] => 2004 // 1970 - 2032+
[yday] => 216 // 0 - 366
[weekday] => Wednesday // Monday - Sunday
[month] => August // January - December
[0] => 1091625315 // UNIX time stamp

Time and Local Time
The time() function returns the timestamp for the current time
time() (no parameters needed)
Localtime performs similarly, but returns an array
[0] => 59 // seconds 0 - 59
[1] => 19 // minutes 0 - 59
[2] => 9 // hour 0 - 23
[3] => 4 // day of month 1 - 31
[4] => 7 // month of the year, starting with 0 for January
[5] => 104 // Years since 1900
[6] => 3 // Day of the week, starting with 0 for Sunday
[7] => 216 // Day of the year
[8] => 1 // Is daylight savings time in effect
More Local Time
Localtime() can also return an associative array:
var_dump (localtime(time, 1));
Outputs:
• [tm_sec] => 1 // seconds 0 - 59
[tm_min] => 23 // minutes 0 - 59
[tm_hour] => 9 // hour 0 - 23
[tm_mday] => 4 // day of month 1 - 31
[tm_mon] => 6 // month of the year, 0 for January
[tm_year] => 104 // Years since 1900
[tm_wday] => 0 // Day of the week, 0 for Sunday
[tm_yday] => 185 // Day of the year
[tm_isdst] => 1 // Is daylight savings time in effect
Formatting Dates
Timestamps are great for calculations, but not for human redability
The date() function can be used to format a date according to an arbitrary set of rules:
date (“Y-m-d H:i:s\n”);
date (‘\d\a\t\e: Y-m-d’);
strftime() provides a printf-like, locale-dependent formatting mechanism for date/time values:
strftime (“%A”, time()); // Prints weekday
You need to use setlocale (LC_TIME, $timezone) in order to set the timezone to a particular value
Creating Dates
Dates can be created using mktime():
mktime (hour, min, sec, mon, day, year, daylight)
Several date-related functions have GMT-equivalents:
gmmktime()
gmdate()
gmstrftime()
It is also possible to change the timezone—just change the TZ environment variable:
putenv (“TZ=Canada/Toronto”);
This will be equivalent to EST or EDT
Interpreting Date Input
It is also possible to create a timestamp from a formatted string date using strtotime():
strotime(“now”);
strtotime(“+1 week”);
strtotime(“November 28, 2005”);
strtotime(“Next Monday”);
You can also check whether a date is valid by using the checkdate() function:
checkdate (month, date, year)
Automatically accounts for leap years. Not foolproof—incapable for example, to account for the Gregorian gap

Cumulus Tag Cloud

Kiran Says

I love work environment which is:

Informal yet professional
Demanding yet rewarding
Challenging yet inspiring
Mediocrity is not an option
Having fun is serious business
Making mistakes is human
Forgiveness is Company Policy

Travelling Sucks