Php Basics
— print (last updated: Feb 13, 2009) print

Select font size:
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
http://localhost/default/PhpBasics
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:
PhpBasics on the Comp. Sci. Server
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.
  1. Extract the PhpBasics project into your default directory.
  2. Select File New Project
  3. In the New Project window, select the PHP category, and choose PHP Application with Existing Sources, then Next.
  4. Select the correct Sources Folder to be the location of PhpBasics folder just extracted.
  5. 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.
  6. In the Run Configuration window, choose these, then Finish.
    Run As: Local Web Site       (the default)
    Project URL: http://localhost/default/PhpBasics/
  7. In the Projects Window, right-click on the newly-created HelloPhp project and select Set as Main Project.
  8. 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: 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:
  1. as an Apache module (this is what we're interested in)
  2. as an executable running as a CGI program
  3. 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: Here are some points: 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:

Look at the sample scripts online:
controls1.php
controls2.php
controls3.php
controls4.php

Alternative control syntax

Php supports alternative syntax for the operators if, for, foreach and while according to these equivalents:
if (...) { 
 // code
} elseif(...) {
 // code
} else {
 // code
}
=
if (...):
 // code
elseif(...):
 // code
else:
 // code
endif
for/foreach/while (...) { 
 // code
}
=
for/foreach/while (...):  
 // code
endfor/endforeach/endwhile
The most common usage of these formats is to create HTML-like control tags in an example like this:
<!-- HTML code -->
<? foreach( range(1,4) as $i ): ?>
  Some HTML code which uses <?= $i ?>
<? endforeach ?>
<!-- HTML code -->
Look at the sample script online:
controls5.php

Arrays

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: Look at the sample scripts online:
arrays1.php
arrays2.php
arrays3.php

Associative arrays (hashes, maps)

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: Look at the sample scripts online:
arrays4.php
arrays5.php

Nested array structures

Arrays maintain their integrity when inserted into arrays. For example, the information record on each person might be expressed like this:
$info = array (
  "John"  => array( "height" => "5'10\"", "age" => 34 ),
  "Ellen" => array( "height" => "5'6\"", "age" => 45 ),
  "Bill"  => array( "height" => "6'2\"", "age" => 29 ),
);
In this case, we could obtain John's age by
$info["John"]["age"]

Functions

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: Look at the sample script online:
funcs1.php

File inclusions

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: Look at the sample script online:
classes1.php


© Robert M. Kline