Wednesday, 12 January 2011

PHP’s Superglobal Variables

PHP offers a number of useful predefined variables that are accessible from anywhere within the
executing script and provide us with a substantial (quan trọng, giá trị) amount of environment-specific information.

We can sift (sàng lọc )through these variables to retrieve details about the current user session, the user’s operating environment, the local operating environment, and more.

PHP creates some of the variables, while the availability and value of many of the other variables are specific to the operating system and web server.

Therefore, rather than attempt to assemble a comprehensive list of all possible predefined variables and their possible values, the following code will output all predefined variables pertinent to any given web server and the script’s execution environment:


This returns a list of variables similar to the following.




As we can see, many information are available =>some useful, some not so useful. Wecan
display just one of these variables simply by treating it as a regular variable. For example, use this code to display the user’s IP address:


This returns a numerical IP address:

We can also gain information regarding the user’s browser and operating system by following code:


This returns information similar to the following:



Learning More About the Server and Client

The $_SERVER superglobal contains information created by the web server—details regarding the server and client configuration and the current request environment.

We will likely find all of these variables to be quite useful in our applications, some of which include the following:

$_SERVER['HTTP_REFERER']: The URL of the page that referred the user to the
current location.

$_SERVER['REMOTE_ADDR']: The client’s IP address.

$_SERVER['REQUEST_URI']: The path component of the URL. For example, if the
URL is http://www.example.com/blog/apache/index.html, the URI is
/blog/apache/index.html.

$_SERVER['HTTP_USER_AGENT']: The client’s user agent, which typically offers
information about both the operating system and the browser.

Retrieving Variables Passed Using GET


The $_GET superglobal contains information pertinent (thích hợp, có liên quan) to any parameters passed using the GET method.

If the URL http://www.example.com/index.html?cat=apache&id=157 is requested, we could access the following variables by using the $_GET superglobal:


The $_GET superglobal by default is the only way that you can access variables passed via the GET method. You cannot reference GET variables like this: $cat, $id.

Retrieving Variables Passed Using POST

The $_POST superglobal contains information pertinent to any parameters passed using the POST method. Consider the following form, used to solicit (nài nỉ, lôi kéo) subscriber (thuê bao) information:


The following POST variables will be made available via the target subscribe.php script:


Like $_GET, the $_POST superglobal is by default the only way to access POST variables. We can not reference POST variables like this: $email, $pswd, and $subscribe.

Retrieving Information Stored Within Cookies


The $_COOKIE superglobal stores information passed into the script through HTTP cookies. Such cookies are typically set by a previously executed PHP script through the PHP function setcookie().

For example, suppose that we use setcookie() to store a cookie named pvhung.com with the value ab2213. We could later retrieve that value by calling $_COOKIE["pvhung.com"].

Retrieving Information About Files Uploaded Using POST

The $_FILES superglobal contains information regarding data uploaded to the server via the POST method.

This superglobal is a tad (1 ít, 1 chút) different from the others in that it is a two-dimensional array containing five elements.

The first subscript refers to the name of the form’s file-upload form element;
the second is one of five predefined subscripts that describe a particular attribute of the uploaded file:

$_FILES['upload-name']['name']: The name of the file as uploaded from the client
to the server.

$_FILES['upload-name']['type']: The MIME type of the uploaded file. Whether
this variable is assigned depends on the browser capabilities.

$_FILES['upload-name']['size']: The byte size of the uploaded file.

$_FILES['upload-name']['tmp_name']: Once uploaded, the file will be assigned a
temporary name before it is moved to its final location.

$_FILES['upload-name']['error']: An upload status code. Despite the name, this
variable will be populated even in the case of success. There are five possible
values:
  • UPLOAD_ERR_OK: The file was successfully uploaded.
  • UPLOAD_ERR_INI_SIZE: The file size exceeds the maximum size imposed by the
  • upload_max_filesize directive.
  • UPLOAD_ERR_FORM_SIZE: The file size exceeds the maximum size imposed by an
  • optional MAX_FILE_SIZE hidden form-field parameter.
  • UPLOAD_ERR_PARTIAL: The file was only partially uploaded.
  • UPLOAD_ERR_NO_FILE: A file was not specified in the upload form prompt.
Learning More About the Operating System Environment

The $_ENV superglobal offers information regarding the PHP parser’s (phân tách cú pháp) underlying server environment. Some of the variables found in this array include the following:
  • $_ENV['HOSTNAME']: The server hostname
  • $_ENV['SHELL']: The system shell
Caution: PHP supports two other superglobals, namely $GLOBALS and $_REQUEST.

The $_REQUEST superglobal is a catch-all of sorts, recording variables passed to a script via the GET, POST, and Cookie methods.

The order of these variables doesn’t depend on the order in which they appear in the sending script; rather, it depends on the order specified by the variables_order configuration directive

The $GLOBALS superglobal array can be thought of as the superglobal superset and contains a comprehensive (bao hàm toàn diện) listing of all variables found in the global scope.

Retrieving Information Stored in Sessions


The $_SESSION superglobal contains information regarding all session variables.
Registering session information allows us the convenience of referring to it throughout our entire web site, without the hassle of explicitly passing the data via GET or POST.

Variable Variables

On occasion, we may want to use a variable whose content can be treated dynamically as a variable in itself. Consider this typical variable assignment:

$recipe = "spaghetti";

We can treat the value spaghetti as a variable by placing a second dollar sign in front
of the original variable name and again assigning another value:

$$recipe = "& meatballs";

This in effect assigns & meatballs to a variable named spaghetti.

Therefore, the following two snippets of (mẩu tin, đoạn trích ngắn) code produce the same result:

echo $recipe $spaghetti;
echo $recipe ${$recipe};

The result of both is the string spaghetti & meatballs.

Constants

A constant is a value that cannot be modified throughout the execution of a program. Constants are particularly useful when working with values that definitely will not require modification, such as Pi (3.141592) or the number of feet in a mile (5,280).

Once a constant has been defined, it cannot be changed (or redefined) at any other point of the program. Constants are defined using the define() function.

Defining a Constant
The define() function defines a constant by assigning a value to a name. Its prototype follows:


If the optional parameter case_insensitive is included and assigned TRUE, subsequent references to the constant will be case insensitive. Consider the following example in which the mathematical constant Pi is defined:

define("PI", 3.141592);

The constant is subsequently used in the following listing:
printf("The value of Pi is %f", PI);
$pi2 = 2 * PI;
printf("Pi doubled equals %f", $pi2);
This code produces the following results:



There are several points to note regarding the previous listing.
The first is that constant references are not prefaced (mở đầu) with a dollar sign.
The second is that we can’t redefine or undefine the constant once it has been defined (e.g., 2*PI); if we need to produce a value based on the constant, the value must be stored in another variable. Finally, constants are global; they can be referenced anywhere in our script.

Saturday, 18 December 2010

PHP’s Supported Data Types

A datatype is the generic name assigned to any data sharing a common set of characteristics.

Common data types include Boolean, integer, float, string, and array

Scalar Data Types are used to represent a single value. Several data types fall under this category, including Boolean, integer, float, and string.

Boolean

The Boolean data type represents truth, supporting only two values: TRUE and FALSE (case insensitive). Alternatively, we can use zero to represent FALSE, and any nonzero value to represent TRUE. A few examples follow:



Integer

An integer is representative of any whole number or, in other words, a number that does not contain fractional parts. PHP supports integer values represented in base 10 (decimal), base 8 (octal), and base 16 (hexadecimal) numbering systems, although it’s likely we’ll only be concerned with the first of those systems. Several examples follow:


The maximum supported integer size is platform-dependent, although this is typically positive or negative 2^31 for PHP version 5 and earlier. PHP 6 introduced a 64-bit integer value, meaning PHP will support integer values up to positive or negative 2^63 in size.

Float

Floating-point numbers, also referred to as floats, doubles, or real numbers, allow us to specify numbers that contain fractional parts. Floats are used to represent monetary values, weights, distances, and a whole host of other representations in which a simple integer value won’t suffice. PHP’s floats can be specified in a variety of ways, several of which are demonstrated here:


String

Simply put, a string is a sequence of characters treated as a contiguous group. Strings are delimited by single or double quotes, although PHP also supports another delimitation methodology, which is introduced in the later “String Interpolation” section.
The following are all examples of valid strings:


Compound Data Types

Compound data types allow for multiple items of the same type to be aggregated under a single representative entity. The array and the object fall into this category.

Array


It’s often useful to aggregate a series of similar items together, arranging and referencing them in some specific way. This data structure, known as an array, is formally defined as an indexed collection of data values. Each member of the array index (also known as the key) references a corresponding value and can be a simple numerical reference to the value’s position in the series, or it could have some direct correlation to the value.

For example, if we were interested in creating a list of cities in Vietnam, we could use
a numerically indexed array, like so:


But what if the project required correlating the list of city to their famous sightseeing? Rather than base the keys on a numerical index, we might instead use an associative index, like this:


Object

The object is a central concept of the object-oriented programming paradigm.
Unlike the other data types contained in the PHP language, an object must be explicitly declared. This declaration of an object’s characteristics and behavior takes place within something called a class.



A class definition creates several attributes and functions pertinent to a data structure, in this case a data structure named Appliance. There is only one attribute, power, which can be modified by using the method setPower().

Converting Between Data Types Using Type Casting

Converting values from one datatype to another is known as type casting.
A variable can be evaluated once as a different type by casting it to another.
This is accomplished by placing the intended type in front of the variable to be cast.




Let’s consider several examples. Suppose we’d like to cast an integer as a double:


Output will be 13.0

Type casting a double to an integer will result in the integer value being rounded down, regardless of the decimal value. Here’s an example:


What happens if we cast a string datatype to that of an integer? Let’s find out:



Output will return to 0 (zero).

We can also cast a datatype to be a member of an array. The value being cast simply becomes the first element of the array:


Output will be 1985

Note that this shouldn’t be considered standard practice for adding items to an array because this only seems to work for the very first member of a newly created array. If it is cast against an existing array, that array will be wiped out, leaving only the newly cast value in the first position.

Any datatype can be cast as an object. The result is that the variable becomes an attribute of the object, the attribute having the name scalar:


The result is BMW

Adapting Data Types with Type Juggling


Variables are sometimes automatically cast to best fit the circumstances in which they are referenced. Consider the following snippet:


The outcome is the expected one; $total is assigned 20, converting the $count variable from a string to an integer in the process.

Here’s another example demonstrating PHP’s type-juggling capabilities:


The integer value at the beginning of the original $total string is used in the calculation. However, if it begins with anything other than a numerical representation, the value is 0. Let's consider another example:


In this example, a string is converted to Boolean type in order to evaluate the if statement.

Let's consider one last particularly interesting example. If a string used in a mathematical calculation includes ., e, or E (representing scientific notation), it will be evaluated as a float:


Variables

A variable is a symbol that can store different values at different times.

For example, suppose we create a web-based calculator capable of performing mathematical tasks. Of course, the user will want to input values of his choosing; therefore, the program must be able to dynamically store those values and perform calculations accordingly. At the same time, the programmer requires a user-friendly means for referring to these value-holders within the application. The variable accomplishes both tasks.

Variable Declaration
A variable always begins with a dollar sign, $, which is then followed by the variable name.
Variable names follow the same naming rules as identifiers.
That is, a variable name can begin with either a letter or an underscore and can consist of letters, underscores, numbers, or other ASCII characters ranging from 127 through 255.

The following are all valid variables:
  • $color
  • $operating_system
  • $_vai_variable
  • $kieuCach
Note that variables are case sensitive. For instance, the following variables bear no relation to each other:
  • $color
  • $Color
  • $COLOR
Value Assignment
Assignment by value simply involves copying the value of the assigned expression to the variable assignee. This is the most common type of assignment.

A few examples follow:
  • $color = "red";
  • $number = 12;
  • $age = 12;
  • $sum = 12 + "15"; // $sum = 27
Each of these variables possesses a copy of the expression assigned to it.
For example, $number and $age each possesses their own unique copy of the value 12.

Reference Assignment
the ability in PHP to assign variables by reference, which essentially means that you can
create a variable that refers to the same content as another variable does.

We can assign variables by reference by appending an ampersand (&) to the equal sign.

Example:

An alternative reference-assignment syntax is also supported, which involves appending the
ampersand to the front of the variable being referenced.

The following example adheres to this new syntax:


Variable Scope
We can declare our variables (by value or by reference) anywhere in a PHP script.

The location of the declaration greatly influences the realm in which a variable can be accessed. This accessibility domain is known as its scope.

PHP variables can be one of four scope types:
  • Local variables
  • Function parameters
  • Global variables
  • Static variables
Local Variables
A variable declared in a function is considered local. it can be referenced only in that function.

Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

Note that when we exit the function in which a local variable has been declared, that variable and its corresponding value are destroyed.

Local variables are helpful because they eliminate the possibility of unexpected side effects that can result from globally accessible variables that are modified, intentionally or not. Consider this listing:



Executing this listing results in the following:



Two different values for $x are output. This is because the $x located inside the assignx() function is local.
Modifying the value of the local $x has no bearing on any values located outside of the function.
On the same note, modifying the $x located outside of the function has no bearing on any variables contained in assignx().

Function Parameters
Any function that accepts arguments must declare those arguments in the function header. Although those arguments accept values that come from outside of the function, they are no longer accessible once the function has exited.

Function parameters are declared after the function name and inside parentheses (dấu ngoặc) . They are declared much like a typical variable would be:



Global Variables

In contrast to local variables, a global variable can be accessed in any part of the program.
To modify a global variable, however, it must be explicitly (rõ ràng) declared to be global in the function in which it is to be modified.
By placing the keyword global in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example:



The displayed value of $somevar would be 16.

However, if we were to omit this line, global $somevar; then the variable $somevar would be assigned the value 1 because $somevar would then be considered local within the addit() function. This local declaration would be implicitly set to 0 and then incremented by 1 to display the value 1.

An alternative method for declaring a variable to be global is to use PHP’s $GLOBALS array.
Reconsidering the preceding example, we can use this array to declare the variable $somevar to be global:



This returns the following:



Static Variables
In contrast to the variables declared as function parameters, which are destroyed on the function’s exit, a static variable does not lose its value when the function exits and will still hold that value if the function is called again.

We can declare a variable as static simply by placing the keyword static in front of the variable name, like so:

STATIC $somevar;

Consider an example:



There will be 2 different cases that may result.
If the variable $count was not designated to be static (thus making $count a local variable), the outcome would be as follows:



Another case with variable $count which is static, it retains its previous value each time the function is executed. Therefore, the outcome is the following:



Static scoping is particularly useful for recursive functions (hàm đệ quy), a powerful programming concept in which a function repeatedly calls itself until a particular condition is met.

Thursday, 21 October 2010

PHP Basic

One of PHP’s advantages is that you can embed PHP code directly alongside HTML. For the code to do anything, the page must be passed to the PHP engine for interpretation. But the web server doesn’t just pass every page; rather, it passes only those pages identified by a specific file extension (typically .php). However, even selectively passing only certain pages to the engine would nonetheless be highly inefficient for the engine to consider every line as a potential PHP command. Therefore, the engine needs some means to immediately determine which areas of the page are PHP-enabled. This is logically accomplished by delimiting the PHP code.

Default Syntax
The default delimiter syntax opens with < ? php and concludes with ? >, like this:


Result:


Short-Tags

For less motivated typists, an even shorter delimiter syntax is available. Known as short-tags, this syntax forgoes the php reference required in the default syntax. However, to use this feature, we need to enable PHP’s short_open_tag directive. An example follows:


Important: Although short-tag delimiters are convenient, do not use them when creating PHP-driven software intended for redistribution. This is because this feature could potentially be disabled within the php.ini file.

When short-tags syntax is enabled and you want to quickly escape to and from PHP to output a bit of dynamic text, you can omit these statements using an output variation known as short-circuit syntax:

This is functionally equivalent to both of the following variations:




Embedding Multiple Code Blocks

We can escape to and from PHP as many times as required within a given page. For instance, the following example is perfectly acceptable:



As we can see here, any variables declared in a prior code block are remembered for later blocks, as is the case with the $date variable in this example.

Outputting Data to the Browser
There are many several methods to output the data on our browsers.

The print() Statement
All of the following are plausible print() statements:



All these statements produce identical output:



The print() statement’s return value is misleading because it will always return 1 regardless of outcome (the only outcome I’ve ever experienced using this statement is one in which the desired output is sent to the browser). This differs from the behavior of most other functions in the sense that their return value often serves as an indicator of whether the function executed as intended.

The echo() Statement

Alternatively, we could use the echo() statement for the same purposes as print().
To use echo(), just provide it with an argument just as was done with print():

echo "I love Ho Chi Minh city.";

echo() is capable of outputting multiple strings. The utility of this particular trait is questionable; using it seems to be a matter of preference more than anything else. Nonetheless, it’s available should you feel the need. Here’s an example:


or executing followings:



All above code will produce the following:


Which is faster, echo() or print()?
The fact that they are functionally interchangeable leaves many pondering this question. The answer is that the echo() function is a tad faster because it returns nothing, whereas print() will return 1 if the statement is successfully output. It’s rather unlikely that we’ll notice any speed difference, however, so we can consider the usage decision to be one of stylistic concern.

The printf() Statement
The printf() statement is ideal when you want to output a blend of static text and dynamic information stored within one or several variables. It’s ideal for two reasons.
  1. It neatly separates the static and dynamic data into two distinct sections, allowing for easy maintenance.
  2. printf() allows us to wield considerable control over how the dynamic information is rendered to the screen in terms of its type, precision, alignment, and position.
For example, suppose we wanted to insert a single dynamic integer value into an otherwise static string:


The output will be


In this example, %d is a placeholder known as a type specifier, and the d indicates an integer value will be placed in that position. When the printf() statement executes, the lone argument, 100, will be inserted into the placeholder.

Note that an integer is expected, so if we pass along a number including a decimal value (known as a float), it will be rounded down to the closest integer. For example: if we pass
along 100.2 or 100.6, then 100 will be output or pass along a string value such as “one hundred”, and 0 will be output, although if we pass along 123food, then 123 will be output.



The sprintf() Statement

The sprintf() statement is functionally identical to printf() except that the output is assigned to a string rather than rendered to the browser. The prototype follows:

string sprintf(string format [, mixed arguments])

An example follows:



Output: