Download the
PhpBasics.zip archive.
Install the archived directory PhpBasics
into the directory representing your "default" website directory,
as discussed
in the Apache/Php/MySQL (AMP) setup for either
Windows
or
Linux.
The installed website should correspond to the URL
This document is meant to be read in conjunction with the
on-line PhpBasics website where you can see each of the scripts
mentioned in the document side-by-side with the output from
web execution. The website is also available on the
Computer Science web server, in case you do not want to install it:
To install this in Aptana, install the folder PhpBasics
into the default web directory,
then
assuming this default directory is the Aptana workspace used
create a new project of the name PhpBasics. The
files will automatically be "loaded" into the project.
NetBeans installation
Start up NetBeans and
follow these steps to create the PhpBasics
project in your default directory.
Extract the PhpBasics project into your default directory.
Select File New Project
In the New Project window,
select the PHP category,
and choose PHP Application with Existing Sources, then Next.
Select the correct Sources Folder
to be the location of PhpBasics folder just extracted.
The Project Name should be correctly set to PhpBasics.
Choose the Sources Folder so that it is the PhpBasics folder within
your default website folder.
Click Next.
In the Run Configuration window, choose these, then Finish.
Run As: Local Web Site
(the default)
Project URL: http://localhost/default/PhpBasics/
In the Projects Window, right-click on the newly-created HelloPhp
project and select Set as Main Project.
Select Run Run Main Project.
This should bring up a new browser window (or frame) with the project.
This demo application allows the user to choose a Php script to execute
and see the results in the display windows. The two relevant directories
for the demo are:
examples/ the script files
examples-list.txt the order in which the script files are listed
You can use this application to view and test your own Php scripts.
Simply add them to the examples directory and make an entry in
the examples-list.txt file.
Server-side web programming
Web applications are client/server applications
where the web browser is the client who always initiates the connection.
The server is a program running on some computer which is
identified by a number called the port to distinguish it
from other server programs. Clients access the server
program via the pair (server,port) called a socket.
The browser client (as well as other client programs)
initiates the interaction with a URL request:
protocol://data_source
where the protocol is any number of possiblities, including
http, file, https, ftp, etc.
The data_source can be any number of things from a regular
file on the client machine to a program on some server
such as these:
file://file
http://server/dir1/dir2/file
http://server/dir1/program
http://server:port/file (server running on alternate port)
The protocol normally dictates the port, but we can
specify it if the different than the usual one,
as in the case of the alternate Tomcat server which we want to use.
If the target file is a directory, then a default file or program is
chosen as the source.
Server-side web programming means that an HTTP request from a browser
causes the web server to run a program which generates HTML
(or other data) to sends back to the browser.
Server-side programming stands in contrast to client-side programming
which is usually equated with JavaScript, but can also be effected by
Java Applets, Flash, or any others which provide a browser plugin.
There are two styles that a server-side program can use
to generate the HTML code sent to the browser:
HTML code generated by programming: (e.g. Perl/CGI, Servlets)
program code embedded within HTML code: (e.g., PHP, ASP, JSP)
Both styles have certain advantages and disavantages.
One advantage of the embedded code style is that it is easier to
adapt static HTML files to dynamic server-side script files.
On the other hand, the generative style is more uniform and avoids
the sometimes confusing transitions between HTML and the program code.
Php execution modalities
Php code can be executed in three different ways:
as an Apache module (this is what we're interested in)
as an executable running as a CGI program
as a command-line program
The Apache module execution (1) is quite different from (2) and (3)
which rely on a system Php executable.
In Ubuntu Linux systems and other, there are three different
Php init files, one for each of these execution modalities.
The CGI programming method creates a separate Php process running
for every server-side invocation. In contrast, the Apache module
maintains one or more "live" Php processes, thereby avoiding the startup
latency.
Nevertheless, the CGI system can have very good performance
if enhanced by using FastCGI to cache the executable code created
from Php invocations.
In fact, the combination of
LIGHTTPD
in conjunction with Php/FastCGI is considered one of the fastest
server-side programming alternatives.
Php syntax
Php was written with Web applications in mind.
It derives much of its syntax and function names from Perl; however,
where Perl favors added syntax, Php relies primarily on function calls.
Php code is embedded directly into HTML syntax, similar to ASP, JSP, etc.
The most basic Php code tags look like this:
<?php
...
?>
The echo command is used to send output to the browser.
Php also has a print function but it permits only a single argument.
Here is a "hello world" script:
hello.php
<pre>
<?php
echo "1: hello world\n";
print ("2: hello world\n");
echo "3:", "hello ", "world", "\n";
/* this would fail because print only accepts one argument */
//print ("4:", "hello ", "world", "\n");
echo "5:", "hello " . "world" . "\n"; // "." is concatenation
print ("6:" . "hello " . "world" . "\n"); // this is OK
# newlines can be embedded in quotes
echo "7: hello
world\n";
# this is the so-called "heredoc" style permitting embedded comments
echo <<<END
8: hello (and not the END of the)
"world"
END;
// END must start at first position, nothing else on line
?>
</pre>
In "HTML mode" the content being echo'd to standard output.
As you see, Php has a rich supply of comment-creating structures
which combine those of C++/Java and UNIX script languages.
# comment line
// comment line
/*
comment
region
*/
It also has a number of modes for creating output.
Start Tag Only
When using a Php script which contains
only Php code, it is unnecessary to include, and
sometimes useful to omit the closing tag.
Consider these three similar examples:
<?php
// Php code
<?php
// Php code
exit();
?>
<?php
// Php code
?>
The first two are effectively identical, but the last one is different based
on the fact that it may output additional whitespace characters after
the closing tag. For the most part this difference is innocuous, except when
the output is binary, as in the case of a generated image.
Short Open Tags
Php uses a configuration setting called
short tags defined in its "standard" init file
with this default definition:
short_open_tag = On
With this setting
you can drop the "php" in the "<?php" and
simply use
"<?".
This setting also permits the usage of the "<?=" tag
to automatically echo expressions, i.e.:
<?php echo PHP-EXPRESSION ?>
=
<?= PHP-EXPRESSION ?>
Unfortunately, this feature can be turned off, and actually
is turned off in the so-called "production" or "recommended"
versions
of the init file. Here is this warning excerpted from the
init file documentation:
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. For portable, redistributable code,
be sure not to use short tags.
The reason for not using short tags is the conflict with
this standard XHTML statement:
<?xml version="1.0" encoding="ISO-8859-1"?>
Nevertheless, it's a convenience to be able to use the short tags
(other server-side languages have them).
Reversed tag pairs
It's often convenient to replace echo
statements by the actual HTML code which would be generated
in HTML mode. Towards this
end, the Php entry tags are used in reverse manner to effect
HTML entry in Php code, like this:
for ( ... ) {
?>
<!-- HTML mode -->
<?
}
Used in this way, the focus is more toward HTML mode and we see
the entry/exit in Php as a way adding control structures to HTML
as seen in this common usage pattern:
<!-- HTML mode -->
<? for ( ... ) { ?>
<!--
HTML mode with Php expression <?= ... ?> insertions
-->
<? } ?>
<!-- HTML mode -->
Scalars
The three main scalar types are string, numeric and boolean.
Php permits variables to be in an undefined state, in which
case they have a dedicated type, NULL.
Php also differentiates between integer
and floating-point (double).
There is a built-in function gettype which
tells the type of a variable.
In Php, all variables have the '$' prefix.
When creating strings, Php uses:
interpolated double quotes
in which "$" is special. Occurrences
of "$x" are replaced by the value of the variable $x.
uninterpolated single quotes.
a "heredoc" style of quoting
(note the three '<' characters):
<<<ENDSTR
here's the string
ENDSTR;
Here are some points:
Unlike Java, strings can span multiple lines, causing the
automatic insertion of a newline. Unlike Java, there is a
dedicated string concatenation operator
"." and "+" always does arithmetic addition,
unlike Java, where it is ambiguous.
Unlike Java, Php is very loose with its type conversions. The
desired operation more-or-less dictates the type and so strings
become numeric in "+".
The Php undefined, or NULL, value behaves in many ways like
the empty string, and so you can concatentate NULL and even
use it within an arithmetic expression in which it behaves like 0.
Php has something that it calls references which are like
C++ reference variables (no such thing in Java). References act
like synonyms of a variable. For example if we define:
$a = 1;
$b =& $a; // "&" applies to $a, but it is usually written like this
then $b and $a are effectively identical.
Php has the higher-level notion of a variable-variable operator
$$. This means
that variables value, presumably a string, can act like the variable
named by that string. If we define:
$a = "x";
then "$$a" is effectively the same as "$x".
Look at the sample script
online:
scalars1.php
scalars2.php
scalars3.php
Php controls
Php is syntactically quite close to Java. Here are some key points:
The "else if" occurrences in chained
if..else clauses can be replaced by the contracted
elseif keyword.
The isset function tests for definedness of a variable.
We can undefines a variable using the unset operation,
or by setting it to the null value.
With respect to usage in test statements, the five values
null, 0, "", "0", false
all act like false in the usual sense.
The relational operators
==, !=, <,
>, <=, >= are used
for numerical comparisons. They also perform
lexicographic comparisons on strings unless the strings
are numerical,
in which case they do numerical comparisons. This leads to some
unexpected behaviors like this failure of the transitivity:
"" == 0 (true)
0 == "0" (true)
"" == "0" (false)
Php has the C-like strcmp function to ensure
lexicographic string comparison under all circumstances.
Php has binary operators === (really equal)
and !== (something doesn't quite match)
which will compare any two Php values for both type and
structural equality. In particular,
none of the false values 0, "",
false, "0", NULL,
are equal via the
=== operator.
The Php array represents both an unbounded list,
like the Java List implementations,
and a map, or hash, or associative array,
like the Java Map implementations. When
treated as an array, the
integer indices act more like keys than simple positional indicators.
Array literals are created using the "array" operator,
or can be created sequentially in a Php-idiosyncratic way.
Here are some points:
The count operator gives the array's size.
The range operator generates an array between two integer
endpoints.
Expressions of the form $a[index] are also interpolated
in double quotes.
The foreach operator iterates over the array elements
instead of the array indices. This is equivalent to the
alternative for loop introduced in Java 1.5:
for ( Type t: object-holding-element-of-Type ) { ... }
Arrays are not automatically rendered when printed;
you need to use functions such as join or print_r.
Concatenation is done by the array_merge operator.
The Php-idiosyncratic way of creating
arrays sequentially is by this syntax:
$a[] = "first"; $a[] = "second", ...
Array creation by assigning at specified indices can produce
unexpected results.
The list operator is useful for assigning variables from an
array's values, like this:
list($x,$y,$z) = $some_array
delete an element of an the array at a position
with the unset operator (setting to null doesn't work).
Php has the array convenience operators:
array_push, array_pop,
array_shift, array_unshift and array_splice.
When an array is declared
with only elements, Php effectively
assigns integer indices 0, 1, ... as
keys. In order to specify the key directly one must use the
=> operator or by setting:
$m[key] = value;
Here are some points:
Expressions of the form $m['key'] are not interpolated
in double quotes.
The Php foreach
operator can be used in a modified form
to iterate through the key/value pairs.
The operators
array_keys and array_values
extract the keys and values, respectively, from an array.
The order that elements are
extracted from a hash via array_keys
or foreach operator is the order in which
the (key,value) pairs were entered. Thus the "entry order"
is preserved. The Java language has an equivalent of this
notion in the LinkedHashMap class.
The array_merge operation can be used for hashes
as well as list. For (key/value)
pairs which are duplicated, the later pairs override the earlier
ones.
Keys which are integer strings are automatically converted
to type integer. Keys of type double are also converted to integer.
Php functions are declared using the keyword function in a syntax
similar to Java, except that there are no types involved.
Here are other aspects of functions:
The sense of locality/globality of a variable inside a function is exactly
the reverse of C/Java. In particular variables inside a function are local
by default and need to be declared global using the
explicit global statement. This is not true
of the Php-special variables like $_SERVER.
Php supports named (untyped) parameters.
Unlike Java, but like C++, Php functions parameters can set
default argument values.
A Php function can only be used once, unlike Java/C++ where a function
can be defined with varying numbers of arguments and varying types.
In Php you can work around this restriction in two ways:
use default parameter values
determine the parameter type using gettype and structure
the behavior accordingly
In addition to having named parameters,
Php provides a way to access the argument array without the named
parameters via the function:
$a = func_get_args();
By default, parameters are passed by value, but there is a means
for passing by reference not available in Java, but available in C++.
Functions and classes (below) are usually made available to
Php scripts via file inclusions
much like the inclusions in C/C++.
In Php, one uses one of the operators
include, require, include_once or
require_once.
This is quite different than the Java import statements.
The difference between include and require is
how they handle failure when the target file doesn't exist:
include produces a warning while require
results in a fatal error.
The "_once" alternatives avoid the problem
of multiple inclusion when multiple included files somehow include
the same file.
The moral is that, for the most part, probably you want
to use require_once.
If you want to include files from some global directory you might want
to add
this directory to the configuration variable include_path defined
in the Php init file and restart Apache.
Classes and Objects
Php 5 radically changed the class structure from older
versions of Php and should be favored.
Php classes imitate many of the features of Java.
Here are some comparisons:
Like Java, there is a specific class construct, a
new operator, data members,
constructor and a class derivation operation.
Member functions use the function declaration like global functions.
Like Java, the object obtained is really a pointer,
but the "->" operator is used to access the data value
("." is already in use as concatenation).
Unlike Java, there is no linguistic connection between
a class name and a file name which contains this class.
Furthermore,
there is no equivalent to the Java import statement;
Php classes are brought in simply through included files.
Static member access uses the C++-like "::" notation.
Data members can be initialized to numeric and string
literals only, otherwise initializations must take place in
a constructor.
The constructor is declared as a function with the name
"__construct" (that's two "_" characters).
Unlike Java, a class can have only one constructor, but the
contructor can use default arguments and have different
behavior based on the parameter type.
Member functions must use the "$this->" prefix
(moving the "$" to the outside)
to access non-static data members.
Static data members are accessed using the "self::" prefix
(keeping the the "$" where it is).
Unqualified variables are assumed to be local
as they are in global Php functions.