Content
- What is PHP?
- Hello World!
- PHP Syntax
- XML Example
- Access Web Service with nuSOAP
- MySQL Interface
- NVO PHP Library
What is PHP?
PHP is a server-side scripting language designed specifically for the Web. The PHP code is interpreted at the Web server and the output is sent to the Web browser or to any client program. PHP was originally developed by Rasmus Lerdorf in 1994. The current major version is 5. The PHP home page is http://www.php.net.Requirements
PHP is known to run on all major operating systems. Although PHP commonly runs as an Apache module, it can also run with other Web servers or standalone from the command line. Most Linux distributions include Apache with PHP and MySQL. The PHP Web site provides binaries for easy installation on Windows systems.The National Virtual Observatory summer school software package includes installation instructions to setup PHP with Tomcat Web server on Windows systems. On other systems, it is simpler to install PHP with Apache server.
What you need before you start
- Your Web server host name, ie www.nvoss.net, localhost
- Your Web server port number, ie 80 if omitted
- Your Web server document root, ie /htdocs or c:\abc\Root\webapps
- Your favorite text editor, ie vi or emacs
- Your favorite Web browser, ie firefox
See $NVOSS_HOME/php/README and $NVOSS_HOME/php/INSTALL for more information.
Hello World
At this point, we assume that PHP is installed and we proceed to test that PHP is working with the traditional Hello World! program.
Hello World!
Write a file containing the two words as shown above and save the file
as hello.php under the document root directory of your Web
server. Point your favorite browser to the URL
http://hostname/hello.php, where hostname
is the name of your web server and you should see the text "Hello World!".
From this example, we learn that PHP works like a filter. Everything that is not specially marked will be forwarded to the output. In other words, a HTML file is a correct PHP program.
A real PHP program
<?
phpinfo ();
?>
The output of this example is a series of tables
showing PHP configuration, installed modules,
internal variables, Apache and enviroment variables.
The symbols "<?" and "?>" mark the start and
the end of a PHP program segment. PHP will
interpret the content between the two markers as
PHP statements. Everything outside of the two
markers is repeated verbatim and forwarded to the output.
A PHP program can have any number of segments intermixed with HTML code.
Today is
<?
echo date ('r');
?>.
Your machine IP is
<?
echo $_SERVER['REMOTE_ADDR']
?>.
PHP Syntax
In general PHP syntax ressembles C or Java, with the a few important exceptions.- Variables start with '$'.
- Variables are dynamically typed and do not require declaration.
- The list(...) operator enables multiple assigment.
- The foreach flow control operator iterates through arrays or lists.
- Assignment of arrays and objects mean copying the content.
- PHP function names are case-insensitive.
PHP Arrays
<?
$array[0] = 1;
$array[5] = "This is element 5";
$array[200] = 300;
$array['one'] = "One";
$b = $array;
$b[5] = 'Only in b';
foreach ($array as $elem)
{
echo "Element is $elem<br>";
}
?>
Arrays in PHP are totally dynamically. They do not require declaration, do not have a fixed length, elements do not need to be consecutive, can store elements of different types and can any simple type as index.
PHP Objects
<?
class myClass
{
function myClass ()
{
$this->elem1 = 'Initial 1';
$this->elem2 = 'Initial 2';
} // constructor
function method1 ($par1)
{
$this->elem1 = $par1;
} // method
} // myClass
$obj = new myClass ();
$obj->method1 ('New value');
print var_dump ($obj);
?>
Classes in PHP are easy to define. A method with the same name as the class acts as the constructor for the class. New attributes can be added at any time. Attributes and methods are by default public. Since PHP version 5, the new() can also be used as constructor, and the keywords public, protected and private can be used to define visibility of class members and methods.
XML Example
The next example shows a PHP script with commonly used features.
<?
class xmlExClass
{
function getFields ()
{
$xml = simplexml_load_file ($this->url);
$rows = $xml->xpath ("//TR");
foreach ($rows as $row)
{
$out = array ();
foreach ($row->TD as $cell)
{
$out[] = $cell;
}
echo join (',', $out);
echo "<br>";
}
} // getFields
function getParameters ()
{
$this->url = $_GET['url'];
} // getParameters
function printForm ()
{
?>
<form action='#' method=get>
<table><tr>
<td>Enter URL of a VOTable:
<td><input type=text size=80 name=url
value='<? echo $this->url; ?>'>
<input type=submit name='go' value='GO'>
</table>
</form>
<?
} // printForm
function genPage ()
{
echo "<html>";
echo "<body>";
$this->printForm ();
$this->getFields ();
echo "</body>";
echo "</html>";
} // genPage
} // xmlEx
$xmlEx = new xmlExClass ();
$xmlEx->getParameters ();
$xmlEx->genPage ();
?>
The example defines the class xmlExClass, which has four methods: getFields(), getParameters(),
printForm() and genPage(). The main program consists of instantiating an object of the class
xmlExClass, calling getParamters() and genPage() to generate the page. The method genPage() outputs
the necessary HTML starting and closing tags and delegates the main work to printForm() and
getFields().
Comparing genPage() and printForm(), we see two different styles of generating HTML code
in a PHP script. While genPage() uses echo (or print) to output text and content of
variables, printForm() intermixes HTML code with PHP code. PHP programmers should
avoid mixing program logic with display handling. Thus, the first style is preferred. But the second style is sometimes more convenient, especially when
large portions of HTML code are to be imported.
The method getFields() shows how to read a XML file using simplexml_load_file.
There are several methods to handle XML in PHP. The SimpleXML extention is
sufficient for most applications that only need to extract information from XML files.
Amongst other features, SimpleXML provides XPATH capabilities. In the example,
the selection pattern '//TR' matches all 'TR' nodes. Another possible
pattern is '/RESOURCE/TABLE/DATA/TABLEDATA/TR/', which explicitly describes the
path from the root to the TR nodes.
See http://www.zend.com/php5/articles/php5-simplexml.php for more information
about SimpleXML.
Accessing Web Service with nuSOAP
nuSOAP consists of a set of PHP classes that implement SOAP. It is entirely written in PHP and it is included in the NVO summer school software package at $NVOSS_HOME/php/web/phpVOlib/nusoap.php. This version of nusoap has been modified to avoid name conflict with the PHP own SOAP classes. The soapclient class in the nuSOAP package has been changed to nusoapclient.See http://www.zend.com/zend/tut/tutorial-campbell.php for more information about nuSOAP.
<?
include_once 'nusoap.php';
class SesameExClass
{
function resolve ()
{
$wsdl = 'http://cdsws.u-strasbg.fr/axis/services/Sesame?wsdl';
$params = array ();
$params['name'] = $this->name;
$params['resultType'] = 'oxpI';
$params['all'] = 1;
$params['service'] = 'SNVA';
$sesame = new nuSoapClient ($wsdl, True);
$res = $sesame->call ('sesame', $params);
echo "<pre>";
var_dump ($res['return']);
echo "</pre>";
} // resolve
function getParameters ()
{
$this->name = @$_GET['name'];
} // getParameters
function printForm ()
{
?>
<form action='#' method=get>
<table><tr>
<td>Enter name to resolve:
<td><input type=text size=80 name=name
value='<? echo $this->name; ?>'>
<input type=submit name='go' value='GO'>
</table>
</form>
<?
} // printForm
function genPage ()
{
echo "<html>";
echo "<body>";
$this->printForm ();
if ($this->name)
$this->resolve ();
echo "</body>";
echo "</html>";
} // genPage
} // SesameExClass
$sesame = new SesameExClass ();
$sesame->getParameters ();
$sesame->genPage ();
?>
The source code can be found at $NVOSS_HOME/php/web/tutorial/SesameEx.php.
The SesameExClass example has a similar structure as the XML example.
The nuSOAP is included at the beginning of the script.
In the method resolve(),
we instantiate the nuSoapClient class with the WSDL URL. The
second parameter is set to True indicating that the URL provided is
a WSDL instead of an service URL.
Services parameters are built using an associative array in the order
as they are specified in the WSDL. The actual invocation of the service
is performed using the method call() of the nuSOAPClient class.
The first parameter is the name of the services operation. The second
parameter is an associative array containing the services parameters.
The result is output without formatting using var_dump().
MySQL Interface
<?
class MySQLExClass
{
function performQuery ()
{
$db = mysql_connect ('localhost', 'nvoss', '');
mysql_select_db ('nvoss');
$res = mysql_query ($this->qstr);
if (!$res)
{
echo mysql_error ($db);
return;
}
while ($row = mysql_fetch_row ($res))
{
$out = array();
foreach ($row as $elem)
{
$out[] = $elem;
}
echo join (',',$out).'<br>';
}
} // performQuery
function getParameters ()
{
$this->qstr = @$_POST['qstr'];
} // getParameters
function printForm ()
{
?>
<form action='#' method=post>
<table><tr>
<td>Enter your query:
<td><textarea rows=10 cols=80
name=qstr><? echo $this->qstr; ?></textarea>
<input type=submit name='go' value='GO'>
</table>
</form>
<?
} // printForm
function genPage ()
{
echo "<html>";
echo "<body>";
$this->printForm ();
$this->performQuery ();
echo "</body>";
echo "</html>";
} // genPage
} // MySQLExClass
$mq = new MySQLExClass ();
$mq->getParameters ();
$mq->genPage ();
?>
The MySQLExClass example shows how to interface with MySQL. Following the same
layout as the previous examples, genPage() and
printForm() build the web page. The new method
performQuery() connects to the database server using
user name and password and
selects a database. Students can replace these default values with their own.
Note that on some platform, the database name is case sensitive.
The code of the example can be found at
$NVOSS_HOME/php/web/tutorial/MySQLEx.php.
The user can enter any valid SQL statement and the script will perform the query
and display the results or an error message.
See http://www.zend.com/manual/ref.mysql.php for more information
about PHP-MySQL interface.
NVO PHP Library
Included in the NVO summer school software package is the PHP client package, located at $NVOSS_HOME/php/web/phpVOlib. This package consists of a set of PHP classes that implement interfaces for cone search, simple image/spectrum access, skynode, skyportal, VO registry, and the Sesame name resolver service. PHP scripts implementing a Web-based user interface can be found at $NVOSS_HOME/php/web.The template.php file can be used to start a new PHP script that will share the same look and feel of the other pages.
Shui Hung Kwok
NVO Summer School 2005
