Home > Articles > Programming > PHP

PHP Basics: Writing Simple PHP Applications

Ewald Geschwinde and Hans-Juergen Schoenig discuss how to write simple PHP applications. Learn the basics of PHP syntax as well as PHP's built-in functions.
This chapter is from the book

PHP is an easy language and you'll find it an easy task to get used to PHP. In this chapter you learn to write simple PHP applications. You learn the basics of PHP syntax as well as PHP's built-in functions.

3.1 Getting Started

In this section you learn to write simple applications. The basics of PHP's interpreter are also covered in detail.

3.1.1 "Hello World"

The first application you will find in most books about computer programming is "Hello World". "Hello World" is easy to implement in all languages because it does nothing except print a string on the screen, so it is a good start. Here is the easiest version of "Hello World" written in PHP:

<?php
    echo 'hello world<br>';
?>

With just three lines of code, you can print a simple message on the screen. The first line of code tells the Web server that the next lines of code have to be executed by the PHP interpreter. ?> means that the code ends here. Using <?php is not the only possible way to tell the Web server that PHP code has to be executed. PHP provides three additional ways to escape from HTML:

<?
    echo 'hello world 1<br>';
?>
 
<script language="php">
    echo 'hello world 2<br>';
</script>
 
<%
    echo 'hello world 3<br>';
%>

In the first three lines, you can see that it is not necessary to mention that the PHP interpreter has to be called. This method of escaping HTML is possible only when short tags are enabled (you can do this by setting the short_open_tag option in PHP's configuration file). However, to make clear which programming language is meant, we recommend using <?php instead of <?.

The third method can be used if Active Server Pages (ASP) tags are enabled. If ASP tags are turned off, <% and %> will be treated like ordinary text and the PHP code will not be interpreted. Therefore we recommend using either <?php or <script language="php"> to tell the Web server what to do with the PHP code. In this book we will use <?php to escape HTML.

If you have put the file containing the code into the right directory (see the documentation and configuration of your Web server to find the right directory), you can execute the script by accessing it in your Web browser. If the file is called hello.php and if it is in the default HTML directory of your local machine, it can easily be accessed by using http://localhost/hello.php. You do not have to add execute rights to the file because the Web server only has to read the file.

If everything has been done correctly, PHP has been configured successfully, and your Web server has been started, hello world will be displayed on the screen.

Your first version of "Hello World" produces just text. However, the main target of a PHP program is to generate HTML code. In the next example, you will see a small script generating the HTML version of "Hello World".

<html>
<head>
    <title>Title of the site</title>
</head>
<body>
    <?php echo 'hello world<br>'; ?>
</body>
</html>

As you can see, the PHP code is included in the HTML code. <?php tells the server that the PHP interpreter has to be started here. In the example you can see that parts of the document are static and other parts of the document are created dynamically by PHP.

Another way to obtain the same target would be to generate the entire document dynamically. This will be slower than the version you have just seen, but in some cases it makes sense or is necessary to generate everything dynamically. Let's have a look at the following code:

<?php
    echo '<html>
        <head>
        <title>Title of the site</title> '.
       '</head>';
    echo "<body>hello world<br></body></html>\n";
?>

The first echo command consists of two parts. The first three lines can be found between two single quotes. PHP recognizes that the command continues in the next line and does not end in the first line of the echo command. This way multiple lines can be treated as one command. Another way is to use a string operation as you can see at the end of line number 3 of the echo command. After the single quote, we use a point to tell PHP that the first string, which has just ended, has to be connected with the next string. In this case the second string is </head>. All components of the first echo command are passed to PHP in single quotes.

The second echo command contains the text we want to be displayed on the screen. This time we pass the text to echo using double quotes. Using single quotes or double quotes makes a significant difference: Single quotes are used to pass static text to PHP. Using double quotes allows you to use variables within the string. Knowing this difference is important because otherwise you might run into trouble. When executing the script you have just seen, the result will be a simple HTML document:

<html>
        <head>
        <title>Title of the site</title> 
        </head>
        <body>hello world<br></body>
</html>

The HTML is still not more than a simple "Hello World" application, but it is already HTML code.

3.1.2 Variables

Variables are a core component of almost every programming language available, and without variables it would be impossible to write useful applications. The idea behind variables is to have a language component that can have different values assigned to it. It is also possible to use variables as containers for storing data that is used in many different places in your application. Let's imagine an example where you want to display the same text on the screen twice:

<?php
    $text="hello world";
 
    echo '<html><head><title>Title of the site</title></head><body>';
    echo "$text<br>";
    echo "$text<br>";
    echo '</body></html>';
?>

First, you assign the string you want to be displayed on the screen to the variable called text. In the next step some HTML code is generated and the variable is printed on the screen twice. Keep in mind that we have to use double quotes instead of single quotes; otherwise, the result would be:

$text
$text

With single quotes, variables cannot be used within a string, so the result is not what you want it to be.

Figure 3.1 shows what comes out when you look at the result using Mozilla.

Figure 3.1Figure 3.1 A more sophisticated version of Hello World.

3.1.3 Adding Comments

Documentation is nearly as important as the code of a program. Nowadays only 10% of all costs of producing a software product are used for writing the source code. The remaining 90% are used for maintaining the product (this information is provided by the University of Vienna). To reduce the costs of maintaining a product and to reduce the time required to become familiar with the source code, it is essential to add comments to your programs. PHP provides some simple ways to add comments to a program:

<?php
    // this is a comment
    /* a C-style comment */
    echo 'hello world';
?>

In PHP comments can be added to the code as in C and C++. // tells the interpreter that the entire line should not be executed. /* */ is the old C style, which is also supported by PHP. C-style comments can be used to insert commands consisting of multiple lines:

<?php
    /*
     a C-style comment
     which is longer than just one line.
    */
?>

We recommend making heavy use of comments to make your code clearer and easier to understand. Especially if you are not the only one who will have to work with the code, comments will make your daily life much easier.

3.1.4 Executing PHP from the Command Line

In many cases it is useful to execute PHP code from the command line instead of executing the script by starting it using a Web browser.

Let's return to the three-liner called hello.php that we discussed at the beginning of this chapter:

<?php
    echo 'hello world<br>';
?>

To execute a script using a shell command, try the following:

[hs@athlon test]$ php ./hello.php
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
 
hello world<br>

As you can see, PHP produces more output than just "hello world". The additional information created by PHP defines which output has been created by PHP. In this case it is text/html. To make sure that the entire output is sent to standard output and not to standard error, we redirect all errors returned by PHP and see what comes out:

[hs@athlon test]$ php ./hello.php 2> /dev/null
X-Powered-By: PHP/4.0.4pl1
Content-type: text/html
 
hello world<br>

The result is still the same, and this shows that no errors have occurred.

PHP provides a lot of command-line parameters that can make daily life with the language much easier:

[hs@athlon test]$ php -h
Usage: php [-q] [-h] [-s] [-v] [-i] [-f <file>] | {<file> [args...]}
 -q       Quiet-mode. Suppress HTTP Header output.
 -s       Display colour syntax highlighted source.
 -f<file>    Parse <file>. Implies ´-q'
 -v       Version number
 -c<path>    Look for php.ini file in this directory
 -a       Run interactively
 -d foo[=bar]  Define INI entry foo with value 'bar'
 -e       Generate extended information for debugger/profiler
 -z<file>    Load Zend extension <file>.
 -l       Syntax check only (lint)
 -m       Show compiled in modules
 -i       PHP information
 -h       This help

As you can see, PHP provides a lot of options you can use from the command line directly. Many developers use only a Web browser to build and to debug PHP applications. Using PHP's command-line parameters can make life much easier; we strongly recommend making heavy use of these features.

One of the most important command-line flags is the -m flag, which you can use to ask PHP which modules have been compiled. This is extremely important if you have not compiled PHP yourself or if you no longer know which modules you added at compile time:

[hs@athlon test]$ php -m
Running PHP 4.0.4pl1
Zend Engine v1.0.4, Copyright (c) 1998-2000 Zend Technologies
 
[PHP Modules]
imap
ldap
mysql
pgsql
zlib
yp
xml
wddx
sysvshm
sysvsem
standard
sockets
session
posix
pcre
gettext
gd
ftp
dba
 
[Zend Modules]

As you can see, the standard PHP distribution included in Red Hat 7.1 supports a lot of modules. You will learn about many of these modules in this book, which will guide you through the details of these modules. One module you will have a very close look at is the pgsql module, which is responsible for interacting with PostgreSQL databases.

An important command-line flag of the PHP interpreter is the -i flag, which can be used to generate information about PHP itself. To generate the result, you can use the following:

[hs@athlon test]$ php -i > /tmp/phpinfo.html

The HTML file that has been generated is very long, so it is not included here.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020