<?php echo; ?>
Plus Two Computer Science · Chapter 10

Server Side Scripting Using PHP

8 sections
Interactive PHP operator playground
10 review questions
10.1

Overview of PHP

10.1

What is PHP?

PHP (PHP Hypertext Preprocessor) is one of the most popular server side scripting languages used for creating dynamic web pages. PHP usually runs on a web server and is available on different operating systems and platforms. It is an interpreted language — a PHP script is processed by the PHP engine each time it runs. PHP is an HTML embedded language, meaning PHP statements can be written within HTML code. When a PHP script runs, it processes the information and produces hypertext (HTML) as a result.

PHP was created by Rasmus Lerdorf, first in 1995, with the first official release in 1997. He is known as the Father of PHP, and continues to contribute to the project. PHP is an open-source project, completely free, and supported by a worldwide community of volunteers. It can access more than 20 different databases including MySQL, and can also output images, PDF files and Flash movies.

10.1.1

Benefits of using PHP

Client-side scripts execute faster since they run at the client, but a client-side language is dependent on the browser, and code like JavaScript is visible through "view source", making it less secure. PHP code, on the other hand, is executed on the server — only the output is sent to the client, so it is impossible for users to see the PHP source code.

  • Easily embedded into HTML — simple to convert a static site into a dynamic one.
  • Compatible with a wide variety of databases.
  • An independent platform — runs across Windows, Linux or Mac servers.
  • Supports most current web servers and interfaces easily with Apache/MySQL.
  • Simple and easy to learn, with syntax similar to C++.
  • Operates fast since it does not use a lot of system resources.
  • Offers many levels of security to prevent malicious attacks.
  • Free, open source, and legally usable for personal and commercial development.
10.1.2

Basics of PHP

A. Setting up the development environment — A PHP compatible web server and PHP interpreter must be installed, either separately or from a bundled package like WAMP (Windows, Apache, MySQL, PHP), XAMPP (X-OS, Apache, MySQL, PHP, PERL — works on any OS) or LAMP (Linux, Apache, MySQL, PHP). After installation, typing http://localhost in the browser confirms the server is running.

B. Writing and running the script — PHP scripts are plain text; only a text editor is needed. PHP scripting begins with <?php and ends with ?>. Files are saved with a .php extension in the web server's document root directory (e.g. C:\wamp\www for WAMP), and the output is viewed by typing the corresponding URL (e.g. http://localhost/example.php).

C. Combining HTML and PHP — PHP and HTML function together: PHP generates HTML, and HTML passes information to PHP. PHP code is embedded anywhere inside standard HTML using the tags <?php and ?>; anything outside these tags is read as plain HTML.

<HTML><BODY>
<?php
 echo "<H2> Welcome to php </H2>";
?>
</BODY></HTML>

D. Comments in PHP — A comment is a line not read/executed as part of the program. PHP supports single line comments (//) and multiline comments (/* ... */).

E. Output statements — echo and print are the two basic constructs used to display output; both can output any data type, but only echo can take multiple comma-separated parameters. var_dump() displays both the data type and value of one or more variables.

echoprint
Can take more than one parameter (without parentheses)Takes only one parameter
Does not return any valueReturns TRUE/1 on success, FALSE if unable to print
Slightly fasterSlightly slower
<?php
 $a1=678; $a2="678"; $a3="Apple"; $a4=698.99;
 var_dump($a1); var_dump($a2); var_dump($a3); var_dump($a4);
?>
// int(678) string(3) "678" string(5) "Apple" float(698.99)
10.2

Fundamentals of PHP

10.2.1

Variables

A PHP variable name starts with the $ sign, followed by the name of the variable. Unlike other languages, a PHP variable does not need to be declared before use — it is created the first time a value is assigned to it, and PHP automatically determines its data type.

$Var_name = value;

Naming rules:

  • Must start with $, followed by a letter or underscore.
  • Can contain only alpha-numeric characters and underscores (a–z, A–Z, 0–9, _).
  • Variable names are case-sensitive ($name and $NAME are different).
  • Punctuation such as commas, quotation marks, periods or spaces are not allowed.
10.2.2

Data Types

PHP data types are grouped into Core Data Types — Integer, Float, Boolean, String — and Special Data Types — Null, Array, Object, Resource.

IntegerFloatBooleanStringNullArrayObjectResource
  • Integer — whole numbers, positive or negative (e.g. -32, 32, 986); PHP does not support unsigned integers.
  • Float/Double — fractional numbers (e.g. 123.56, 1.2e3).
  • String — text within single or double quotes, e.g. "Apple", 'PHP'; the opening and closing quote type must match.
  • Boolean — TRUE or FALSE, often used in conditional testing.
  • Null — a variable is NULL if not set; can also be used to empty a variable.
  • Array — holds multiple key/value pairs (indexed, associative or multidimensional).
  • Object — can contain variables and functions; created from a class using new.
  • Resource — a special variable holding references to external resources like a file handler or database object.
10.2.3

Operators in PHP

PHP operators are grouped as Assignment, Arithmetic, Relational, Logical, String and Combined operators.

CategoryOperators
Arithmetic+ – * / %
Relational== != < > <= >=
Logicaland, &&, or, ||, xor, !
String. (concatenation), .= (concatenating assignment)
Combined+= –= *= /= %= .=
Increment/Decrement++$x, $x++, --$x, $x--
<?php
 $string1= 'Good'; $string2= ' Morning';
 $newstring = $string1.$string2; //concatenation
 $string1 .= $string2; //concatenation assignment
 echo $newstring."<BR>"; echo $string1;
?> // Good Morning / Good Morning

Escape sequences — a single character headed by a backslash (\) used inside strings:

OperatorMeaning
\"Print double quote
\'Print single quote
\nNew line
\tTab
\$Print $ symbol
\\Print backslash
10.3

Control Structures in PHP

10.3.1

Conditional Statements

Conditional statements such as if, else, elseif and switch allow a program to execute different pieces of code, or none at all, depending on some condition.

if (expression) { // runs if true }
elseif (expression) { // runs if this is true }
else { // runs otherwise }

The switch statement is similar to a series of if statements on the same expression, working exactly like switch in C++ — except PHP's switch can also accept strings as case identifiers.

switch ($n) {
 case 1: echo "One"; break;
 case 2: echo "Two"; break;
 default: echo "Enter correct no.";
}
10.3.2

Loops in PHP

The while loop executes the nested statements repetitively until the expression returns false. The do…while loop executes a block of code at least once, then repeats as long as the condition is true. The for loop is used when the number of iterations is known in advance.

for ($i=1; $i<=5; $i++) { echo "$i "; } // 1 2 3 4 5

continue skips the rest of the current loop iteration and jumps to the condition evaluation. break ends execution of the current for, foreach, while, do–while or switch structure; it accepts an optional numeric argument telling it how many nested structures to break out of.

10.4

Arrays in PHP

10.4

Array Basics

An array in PHP is a collection of key and value pairs. Unlike C++, where only non-negative integers are used as keys, PHP allows either non-negative integers or strings as keys. PHP supports three types of arrays: Indexed, Associative and Multidimensional.

10.4.1

Indexed Arrays

Arrays with a numeric index are called indexed arrays; by default the index starts from zero. The function array() creates an array, and print_r() prints an array in a single statement.

$colors = array("red","brown","yellow");
// OR
$colors[0] = "red"; $colors[1] = "brown"; $colors[2] = "yellow";
10.4.2

Associative Arrays

Arrays with named (string) keys are called associative arrays — similar to indexed arrays in functionality, but different in how the index is represented.

$cost=array("Pen"=>"35","Pencil"=>"5","Brush"=>"20");
echo "A pencil costs " . $cost['Pencil'] . " rupees."; // 5
10.4.3

foreach Loops

foreach is an extension to the for loop, used when the number of array elements is unknown. It iterates through each key/value pair until the end of the array, and has two forms:

foreach ($array as $value) { // use $value }
foreach ($array as $key => $value) { // use $key and $value }
10.5

Functions in PHP

10.5.1

User-defined Functions

Just like other languages, PHP has both user-defined and built-in functions. A user-defined function declaration starts with the word function; naming rules for functions are the same as for variables.

function add($a, $b)
{ $c = $a + $b; return $c; }
echo "5+10 = ".add(5,10); // 5+10 = 15
10.5.2

Built-in Functions

PHP comes with many useful built-in functions:

FunctionPurpose
date(format, timestamp)Formats a date/time; d=day, m=month, Y=year, l=day of week
chr(ascii)Returns the character for a given ASCII value
strlen(string)Returns the length of a string
strpos(string, find, start)Finds position of first occurrence of a substring
strcmp(string1, string2)Compares two strings
10.6

Three Tier Architecture in PHP

10.6

The Three Tiers

Three-tier architecture is a client-server architecture in which the functionalities like user interface, application programs and data storage are separated into layers (tiers), usually located on physically separate computers, so that one layer can be modified without affecting the others.

  • Tier-1 (Browser/Client) — the front end that renders the content received from the web server, which may be plain HTML or HTML embedded with JavaScript.
  • Tier-2 (Web Server) — the middle, dynamic-content processing level (e.g. Apache running PHP). It accepts requests from the browser, runs the requested script and sends the output back as HTML.
  • Tier-3 (Database) — the back-end DBMS (e.g. MySQL) that interprets and executes SQL commands sent from the web server and returns the result.
10.7

PHP Forms

10.7

Forms and Global Variables

In PHP, forms are used to collect information from the client and pass it to the server. Global variables are always accessible from anywhere in the code — regardless of scope, they can be accessed from any function, class or file.

10.7.1

Superglobal Arrays

PHP contains predefined global arrays called superglobals, always available regardless of scope:

SuperglobalDescription
$GLOBALSVariables available in the global scope
$_SERVERInformation about headers, paths and script locations
$_GETData passed using the HTTP GET method
$_POSTData passed using the HTTP POST method
$_REQUESTData passed via $_GET, $_POST and $_COOKIE combined
$_FILESData passed by an HTML file input
$_SESSIONCurrent session data specific to the user
$_COOKIEData stored on the user's browser as a cookie

$_REQUEST collects submitted form data regardless of method; $_POST and $_GET collect data submitted with method="post" and method="get" respectively, and $_GET can also read parameters appended directly to a URL.

10.7.2

GET and POST Comparison

Method = GETMethod = POST
Data remains visible in the address barData is not visible; passed as an input file
Page can be bookmarkedPage can never be bookmarked
Fast but not secureSecure but slower than GET
Can only send 2000 charactersNo limit

GET should never be used for sending passwords or other sensitive information.

10.8

Connecting PHP to Database (MySQL)

10.8

Dynamic Pages and MySQL

Static web pages never change unless a new page is loaded; dynamic pages change every time they are loaded, based on what users do. A dynamic website is built automatically by the web server, pulling information from the database into a web page template on each request.

10.8.1

Establishing Connection — Four Steps

  1. Open a connection to MySQL using mysql_connect($server,$user_name,$password), which returns a link identifier or NULL on error.
  2. Specify the database to open using mysql_select_db($database), which returns true or false.
  3. Retrieve/insert data: execute the SQL query with mysql_query(), then populate rows into an array with mysql_fetch_array().
  4. Close the connection using mysql_close($db_handle).
$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$result_set = mysql_query($SQL);
$record = mysql_fetch_array($result_set);
mysql_close($db_handle);

As too many open MySQL connections can cause problems, it is good practice to close the connection once all queries are executed.

10.8.2–10.8.4

Creating, Inserting and Updating via PHP

Once connected, DDL and DML statements are prepared as strings and executed with mysql_query():

// create table
$SQL = "CREATE TABLE marks (regno number, tname char(20), ...)";
mysql_query($SQL);

// insert data
$SQL = "INSERT INTO marks VALUES (".$sregno.",'".$sname."', ...)";
mysql_query($SQL);

// update data
$SQL = "UPDATE marks SET m1=70 WHERE regno='".$sregno."'";
mysql_query($SQL);
Try It Yourself

PHP Operator Playground

Pick two operand values for $a and $b and an operator, then press Run — see the PHP statement and the browser output it would produce, just like echo would display it.

<?php echo $a <op> $b; ?>
echo $a + $b;
 localhost/playground.php
Self-Assessment

Question & Answer Review

Tap a question to reveal the answer — a quick way to check understanding of PHP concepts.

01What is PHP?
PHP (PHP Hypertext Preprocessor) is a popular server side scripting language used to create dynamic web pages. It runs on a web server, is an interpreted, HTML-embedded language, and produces HTML output when the script is executed.
02What is the difference between PHP and JavaScript?
JavaScript is a client-side scripting language — it runs in the browser, is dependent on the browser, and its source code is visible via "view source", making it less secure. PHP is a server-side language — it executes on the server and only the resulting output (HTML) is sent to the client, so the PHP source code itself is never exposed to the user.
03What are the steps involved in running a PHP script?
The browser requests a page by typing its URL; the web server recognises the requested URL is a PHP script and instructs the PHP engine to process and run it; the script runs and, once finished, sends an HTML page containing the result back to the browser.
04What are the differences between "echo" and "print" statements?
echo can accept more than one comma-separated parameter (when used without parentheses) and does not return a value, while print takes only a single parameter and returns TRUE or 1 on success and FALSE if it could not print the string. echo is also marginally faster than print.
05Why is PHP superior to client-side languages such as JavaScript for many tasks?
Because PHP executes on the server rather than in the browser, it is independent of the browser being used, its source code stays hidden from the client, and it can directly interact with server-side resources like databases — something a purely client-side language cannot do securely.
06Which character is used to terminate a PHP statement? Name one situation where omitting it does not produce an error.
Each line of PHP code is terminated with a semicolon (;). The one exception is the very last statement inside a block of PHP code (just before the closing ?> tag) — the semicolon is not compulsory there.
07What is an escape sequence? Name three commonly used ones.
An escape sequence is a single character headed by a backslash (\) used inside a PHP string to represent a special character. Examples include \n (new line), \t (tab), and \" (a literal double quote character).
08What are the differences between GET and POST methods in form submitting?
With GET, data is appended to and remains visible in the URL, the page can be bookmarked, and it is limited to about 2000 characters — making it unsuitable for sensitive data. With POST, data is embedded in the body of the HTTP request (invisible in the URL), the page cannot be bookmarked, there is no size limit, and it is the more secure choice, though marginally slower than GET.
09What is the use of $_SERVER?
$_SERVER is a PHP superglobal variable that holds information about headers, paths and script locations — for example, $_SERVER['PHP_SELF'] returns the filename of the currently executing script and $_SERVER['SERVER_NAME'] returns the name of the host server.
10Explain the procedure for connecting PHP with MySQL.
Four steps are involved: first, open a connection to the MySQL server using mysql_connect() with the server, username and password; second, select the required database using mysql_select_db(); third, execute an SQL query with mysql_query() and retrieve its rows using mysql_fetch_array(); and finally, close the connection with mysql_close() once all queries are done.