PHP Basic
PHP Basic
When PHP parses a file, it looks for opening and closing tags, which tell PHP to start
and stop interpreting the code between them.
Parsing in this manner allows php to be embedded in all sorts of different documents, as
everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the
time you will see php embedded in HTML documents, as in this example.
<?php
if ($expression) {
?>
<strong>This is true.</strong>
<?php
} else {
?>
<strong>This is false.</strong>
<?php
}
?>
This works as expected, because when PHP hits the ?> closing tags, it simply starts outputting
whatever it finds (except for an immediately following newline - see instruction separation ) until it
hits another opening tag. The example given here is contrived, of course,
but for outputting large blocks of text, dropping out of PHP parsing mode is generally
more efficient than sending all of the text through echo() or print().
There are four different pairs of opening and closing tags which can be used in php.
Two of those, <?php ?> and <script language="php"> </script>, are always available.
The other two are short tags and ASP style tags, and can be turned on and off from the
php.ini configuration file.
As such, while some people find short tags and ASP style tags convenient, they are less portable, and
generally not recommended.
Note: Also note that if you are embedding PHP within XML or XHTML you will need
to use the <?php ?> tags to remain compliant with standards.
2. <script language="php">
echo 'some editors (like FrontPage) don\'t
like processing instructions';
</script>
While the tags seen in examples one and two are both always available, example one is the most
commonly used, and recommended, of the two.
Short tags (example three) are only available when they are enabled via the short_open_tag php.ini
configuration file directive, or if php was configured with the --enable-short-tags option.
ASP style tags (example four) are only available when they are enabled via the asp_tags php.ini
configuration file directive.
Note: Using short tags should be avoided when developing applications or libraries that are meant
for redistribution, or deployment on PHP servers which are not under your control, because short
tags may not be supported on the target server.
short_open_tag
Tells whether the short form (<? ?>) of PHP's open tag should be allowed. If you want to
use PHP in combination with XML, you can disable this option in order to use <?xml ?>
inline. Otherwise, you can print it with PHP, for example: <?php echo '<?xml
version="1.0"'; ?>. Also if disabled, you must use the long form of the PHP open tag (<?
php ?>).
Note: This directive also affects the shorthand <?=, which is identical to <? echo.
Use of this shortcut requires short_open_tag to be on.
asp_tags
Enables the use of ASP-like <% %> tags in addition to the usual <?php ?> tags. This includes
the variable-value printing shorthand of <%= $value %>.
Instruction separation
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each
statement.
The closing tag of a block of PHP code automatically implies a semicolon; you do not
need to have a semicolon terminating the last line of a PHP block.
The closing tag for the block will include the immediately trailing newline if one is present.
<?php
echo 'This is a test';
?>
and in some cases omitting it is helpful when using include() or require(), so unwanted
whitespace will not occur at the end of files, and you will still be able to add headers to the
response later. It is also handy if you use output buffering, and would not like to see added
unwanted whitespace at the end of the parts generated by the included files.
Comments:
PHP supports 'C', 'C++' and Unix shell-style (Perl style) comments. For example:
<?php
echo 'This is a test'; // This is a one-line c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a one-line shell-style comment
?>
The "one-line" comment styles only comment to the end of the line or the current block of PHP
code, whichever comes first. This means that
HTML code after // ... ?> or # ... ?> WILL be printed. ?> breaks out of PHP mode and
returns to HTML mode, and // or # cannot influence that. If the asp_tags configuration
directive is enabled, it behaves the same with // %> and # %>.
However, the </script> tag doesn't break out of PHP mode in a one-line comment.
'C' style comments end at the first */ encountered. Make sure you don't nest 'C' style
comments. It is easy to make this mistake if you are trying to comment out a large block
of code.
<?php
/*
echo 'This is a test'; /* This comment will cause a problem */
*/
?>
Variables
Basics
Variables in PHP are represented by a dollar sign followed by the name of the variable.
Variable names follow the same rules as other labels in PHP. A valid variable name starts with a
letter or underscore, followed by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).
<?php
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"
As of PHP 4, PHP offers another way to assign values to variables: assign by reference. This means
that the new variable simply references (in other words, "becomes an alias for" or "points to") the
original variable. Changes to the new variable affect the original, and vice versa.
To assign by reference, simply prepend an ampersand (&) to the beginning of the variable which is
being assigned (the source variable). For instance, the following code snippet outputs 'My name is
Bob' twice:
<?php
$foo = 'Bob'; // Assign the value 'Bob' to $foo
$bar = &$foo; // Reference $foo via $bar.
$bar = "My name is $bar"; // Alter $bar...
echo $bar;
echo $foo; // $foo is altered too.
?>
One important thing to note is that only named variables may be assigned by reference.
<?php
$foo = 25;
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.
function test()
{
return 25;
}
It is not necessary to initialize variables in PHP however it is a very good practice. Uninitialized
variables have a default value of their type - FALSE, zero, empty string or an empty array.
<?php
echo ($unset_bool ? "true" : "false"); // false
$unset_int += 25; // 0 + 25 => 25
echo $unset_string . "abc"; // "" . "abc" => "abc"
$unset_array[3] = "def"; // array() + array(3 => "def") => array(3 => "def")
?>
Relying on the default value of an uninitialized variable is problematic in the case of including one
file into another which uses the same variable name. It is also a major security risk with
register_globals turned on. E_NOTICE level error is issued in case of working with uninitialized
variables, however not in the case of appending elements to the uninitialized array.
isset() language construct can be used to detect if a variable has been already initialized.
Predefined variables
PHP provides a large number of predefined variables to any script which it runs. Many of these
variables, however, cannot be fully documented as they are dependent upon which server is running,
the version and setup of the server, and other factors. Some of these variables will not be available
when PHP is run on the command line. For a listing of these variables, please see the section on
Reserved Predefined Variables.
Warning
In PHP 4.2.0 and later, the default value for the PHP directive register_globals is off. This is a major
change in PHP. Having register_globals off affects the set of predefined variables available in the
global scope. For example, to get DOCUMENT_ROOT you'll use
$_SERVER['DOCUMENT_ROOT'] instead of $DOCUMENT_ROOT, or $_GET['id'] from the URL
http://www.example.com/test.php?id=3 instead of $id, or $_ENV['HOME'] instead of $HOME.
For related information on this change, read the configuration entry for register_globals, the security
chapter on Using Register Globals , as well as the PHP 4.1.0 and 4.2.0 Release Announcements.
Using the available PHP Reserved Predefined Variables, like the superglobal arrays, is preferred.
From version 4.1.0 onward, PHP provides an additional set of predefined arrays containing variables
from the web server (if applicable), the environment, and user input. These new arrays are rather
special in that they are automatically global--i.e., automatically available in every scope. For this
reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined
superglobals.) The superglobals are listed below; however, for a listing of their contents and further
discussion on PHP predefined variables and their natures, please see the section Reserved Predefined
Variables. Also, you'll notice how the older predefined variables ($HTTP_*_VARS) still exist. As of
PHP 5.0.0, the long PHP predefined variable arrays may be disabled with the register_long_arrays
directive.
Variable variables: Superglobals cannot be used as variable variables inside functions or class
methods.
Note: Even though both the superglobal and HTTP_*_VARS can exist at the same time; they are not
identical, so modifying one will not change the other.
If certain variables in variables_order are not set, their appropriate PHP predefined arrays are also
left empty.
PHP Superglobals
$GLOBALS
Contains a reference to every variable which is currently available within the global scope of
the script. The keys of this array are the names of the global variables. $GLOBALS has
existed since PHP 3.
$_SERVER
Variables set by the web server or otherwise directly related to the execution environment of
the current script. Analogous to the old $HTTP_SERVER_VARS array (which is still
available, but deprecated).
$_GET
Variables provided to the script via URL query string. Analogous to the old
$HTTP_GET_VARS array (which is still available, but deprecated).
$_POST
Variables provided to the script via HTTP POST. Analogous to the old $HTTP_POST_VARS
array (which is still available, but deprecated).
$_COOKIE
Variables provided to the script via HTTP cookies. Analogous to the old
$HTTP_COOKIE_VARS array (which is still available, but deprecated).
$_FILES
Variables provided to the script via HTTP post file uploads. Analogous to the old
$HTTP_POST_FILES array (which is still available, but deprecated). See POST method
uploads for more information.
$_ENV
Variables provided to the script via the environment. Analogous to the old
$HTTP_ENV_VARS array (which is still available, but deprecated).
$_REQUEST
Variables provided to the script via the GET, POST, and COOKIE input mechanisms, and
which therefore cannot be trusted. The presence and order of variable inclusion in this array
is defined according to the PHP variables_order configuration directive. This array has no
direct analogue in versions of PHP prior to 4.1.0. See also import_request_variables().
Caution
Since PHP 4.3.0, FILE information from $_FILES does not exist in $_REQUEST.
Note: When running on the command line , this will not include the argv and argc
entries; these are present in the $_SERVER array.
$_SESSION
Variables which are currently registered to a script's session. Analogous to the old
$HTTP_SESSION_VARS array (which is still available, but deprecated). See the Session
handling functions section for more information.
Variable scope:
The scope of a variable is the context within which it is defined. For the most part all PHP variables
only have a single scope. This single scope spans included and required files as well. For example:
<?php
$a = 1;
include 'b.inc';
?>
Here the $a variable will be available within the included b.inc script. However, within user-defined
functions a local function scope is introduced.
Any variable used inside a function is by default limited to the local function scope.
For example:
<?php
$a = 1; /* global scope */
function Test()
{
echo $a; /* reference to local scope variable */
}
Test();
?>
This script will not produce any output because the echo statement refers to a local version of the $a
variable, and it has not been assigned a value within this scope. You may notice that this is a little bit
different from the C language in that global variables in C are automatically available to functions
unless specifically overridden by a local definition. This can cause some problems in that people
may inadvertently change a global variable. In PHP global variables must be declared global inside a
function if they are going to be used in that function.
<?php
$a = 1;
$b = 2;
function Sum()
{
global $a, $b;
$b = $a + $b;
}
Sum();
echo $b;
?>
The above script will output "3". By declaring $a and $b global within the function, all references to
either variable will refer to the global version. There is no limit to the number of global variables that
can be manipulated by a function.
A second way to access variables from the global scope is to use the special PHP-defined
$GLOBALS array. The previous example can be rewritten as:
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
The $GLOBALS array is an associative array with the name of the global variable being the key and
the contents of that variable being the value of the array element. Notice how $GLOBALS exists in
any scope, this is because $GLOBALS is a superglobal. Here's an example demonstrating the power
of superglobals:
A static variable exists only in a local function scope, but it does not lose its value
when program execution leaves this scope.
<?php
function Test()
{
$a = 0;
echo $a;
$a++;
}
?>
This function is quite useless since every time it is called it sets $a to 0 and prints "0". The $a++
which increments the variable serves no purpose since as soon as the function exits the $a variable
disappears. To make a useful counting function which will not lose track of the current count, the $a
variable is declared static:
<?php
function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>
Now, every time the Test() function is called it will print the value of $a and increment it.
Static variables also provide one way to deal with recursive functions. A recursive function is one
which calls itself. Care must be taken when writing a recursive function because it is possible to
make it recurse indefinitely. You must make sure you have an adequate way of terminating the
recursion. The following simple function recursively counts to 10, using the static variable $count to
know when to stop:
<?php
function Test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test();
}
$count--;
}
?>
Trying to assign values to these variables which are the result of expressions will cause a
parse error.
<?php
function foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
?>
Variable variables
That is, a variable name which can be set and used dynamically.
<?php
$a = 'hello';
?>
A variable variable takes the value of a variable and treats that as the name of a variable. In the
above example, hello, can be used as the name of a variable by using two dollar signs. i.e.
<?php
$$a = 'world';
?>
At this point two variables have been defined and stored in the PHP symbol tree: $a with contents
"hello" and $hello with contents "world". Therefore, this statement:
<?php
echo "$a ${$a}";
?>
<?php
echo "$a $hello";
?>
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if
you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you
wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this
ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
Warning
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or
class methods. The variable $this is also a special variable that cannot be referenced dynamically.
Depending on your particular setup and personal preferences, there are many ways to access data
from your HTML forms. Some examples are:
<?php
// Available since PHP 4.1.0
echo $_POST['username'];
echo $_REQUEST['username'];
import_request_variables('p', 'p_');
echo $p_username;
echo $HTTP_POST_VARS['username'];
echo $username;
?>
Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET
also applies to the QUERY_STRING (the information after the '?' in a URL). So, for
example, http://www.example.com/test.php?id=3 contains GET data which is accessible with
$_GET['id']. See also $_REQUEST and import_request_variables().
Note: Superglobal arrays, like $_POST and $_GET, became available in PHP 4.1.0
As shown, before PHP 4.2.0 the default value for register_globals was on. And, in PHP 3 it was
always on. The PHP community is encouraging all to not rely on this directive as it's preferred to
assume it's off and code accordingly.
Note: The magic_quotes_gpc configuration directive affects Get, Post and Cookie values. If turned
on, value (It's "PHP!") will automagically become (It\'s \"PHP!\"). Escaping is needed for DB
insertion. See also addslashes(), stripslashes() and magic_quotes_sybase.
PHP also understands arrays in the context of form variables (see the related faq). You may, for
example, group related variables together, or use this feature to retrieve values from a multiple select
input. For example, let's post a form to itself and upon submission display the data:
<?php
if ($_POST) {
echo '<pre>';
echo htmlspecialchars(print_r($_POST, true));
echo '</pre>';
}
?>
<form action="" method="post">
Name: <input type="text" name="personal[name]" /><br />
Email: <input type="text" name="personal[email]" /><br />
Beer: <br />
<select multiple name="beer[]">
<option value="warthog">Warthog</option>
<option value="guinness">Guinness</option>
<option value="stuttgarter">Stuttgarter Schwabenbru</option>
</select><br />
<input type="submit" value="submit me!" />
</form>
In PHP 3, the array form variable usage is limited to single-dimensional arrays. As of PHP 4, no such
restriction applies.
When submitting a form, it is possible to use an image instead of the standard submit button with a
tag like:
When the user clicks somewhere on the image, the accompanying form will be transmitted to the
server with two additional variables, sub_x and sub_y. These contain the coordinates of the user
click within the image. The experienced may note that the actual variable names sent by the browser
contains a period rather than an underscore, but PHP converts the period to an underscore
automatically.
HTTP Cookies
PHP transparently supports HTTP cookies as defined by Netscape's Spec. Cookies are a
mechanism for storing data in the remote browser and thus tracking or identifying return users. You
can set cookies using the setcookie() function. Cookies are part of the HTTP header, so the
SetCookie function must be called before any output is sent to the browser. This is the same
restriction as for the header() function. Cookie data is then available in the appropriate cookie data
arrays, such as $_COOKIE, $HTTP_COOKIE_VARS as well as in $_REQUEST. See the setcookie()
manual page for more details and examples.
If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For
example:
<?php
setcookie("MyCookie[foo]", 'Testing 1', time()+3600);
setcookie("MyCookie[bar]", 'Testing 2', time()+3600);
?>
That will create two separate cookies although MyCookie will now be a single array in your script. If
you want to set just one cookie with multiple values, consider using serialize() or explode() on the
value first.
Note that a cookie will replace a previous cookie by the same name in your browser unless the path
or domain is different. So, for a shopping cart application you may want to keep a counter and pass
this along. i.e.
<?php
if (isset($_COOKIE['count'])) {
$count = $_COOKIE['count'] + 1;
} else {
$count = 1;
}
setcookie('count', $count, time()+3600);
setcookie("Cart[$count]", $item, time()+3600);
?>
Typically, PHP does not alter the names of variables when they are passed into a script. However, it
should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For
the reason, look at it: <?php
$varname.ext; /* invalid variable name */
?> Now, what the parser sees is a variable named $varname, followed by the string concatenation
operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or
reserved words) 'ext'. Obviously, this doesn't have the intended result.
For this reason, it is important to note that PHP will automatically replace any dots in
incoming variable names with underscores.
Because PHP determines the types of variables and converts them (generally) as needed, it is not
always obvious what type a given variable is at any one time. PHP includes several functions which
find out what type a variable is, such as: gettype(), is_array(), is_float(), is_int(), is_object(), and
is_string(). See also the chapter on Types.
Constants
A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change
during the execution of the script (except for magic constants, which aren't actually constants).
The name of a constant follows the same rules as any label in PHP. A valid constant name starts with
a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular
expression, it would be expressed thusly: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
<?php
?>
Note: For our purposes here, a letter is a-z, A-Z, and the ASCII characters from 127 through 255
(0x7f-0xff).
You can access constants anywhere in your script without regard to scope. For more information
on scope, read the manual section on variable scope.
Syntax
You can define a constant by using the define()-function. Once a constant is defined, it
can never be changed or undefined.
Only scalar data (boolean, integer, float and string) can be contained in constants. Do
not define resource constants.
You can get the value of a constant by simply specifying its name. Unlike with variables, you should
not prepend a constant with a $. You can also use the function constant() to read a constant's value if
you wish to obtain the constant's name dynamically. Use get_defined_constants() to get a list of all
defined constants.
Note: Constants and (global) variables are in a different namespace. This implies that for
example TRUE and $TRUE are generally different.
If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as
if you called it as a string (CONSTANT vs "CONSTANT"). An error of level E_NOTICE will be
issued when this happens. See also the manual entry on why $foo[bar] is wrong (unless you first
define() bar as a constant). If you simply want to check if a constant is set, use the defined()
function.
<?php
define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."
echo Constant; // outputs "Constant" and issues a notice.
?>
Magic constants
PHP provides a large number of predefined constants to any script which it runs. Many of these
constants, however, are created by various extensions, and will only be present when those
extensions are available, either via dynamic loading or because they have been compiled in.
There are five magical constants that change depending on where they are used. For example, the
value of __LINE__ depends on the line that it's used on in your script. These special constants are
case-insensitive and are as follows:
Name Description
__LINE__ The current line number of the file.
The full path and filename of the file. If used inside an include, the name of the
__FILE__ included file is returned. Since PHP 4.0.2, __FILE__ always contains an absolute path
whereas in older versions it contained relative path under some circumstances.
The function name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the
__FUNCTION__ function name as it was declared (case-sensitive). In PHP 4 its value is always
lowercased.
__CLASS__
The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class
name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.
The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-
__METHOD__
sensitive).