Chapter 1
Chapter 1
Internet Programming2
Chapter One Server Side Scripting Basics
Chapter One
Web page is a document, typically written in HTML that is almost always accessible via HTTP.
Or pages on which, information is displayed on the web. It can be static or dynamic.
Static web page means that what is displayed does not change until the underlying HTML or
XML is changed.
When the content that is displayed changes in response to actions taken by the user, then the web
page is said to be dynamic. This kind of web page is developed using scripting languages.
Scripts can be written to run either server-side or client-side. A script must be interpreted at the
time it is requested from the web server. Each scripting language has its own script interpreter –
called a script engine.
A client-side script is executed on the client, by the browser. Client-scripting is often used to
validate data entered on a form by the user, before the form is submitted to the server e.g. check
that an email address has a @ sign in it. Some of client side scripts are java script, VB script etc.
In client side script, users may be able to see the source code by viewing a file that contains the
script.
A server-side script is executed on the server, and generally produces HTML which is then
output HTML to the client.
Server-side scripting is a web server technology in which a user's request is fulfilled by running
a script directly on the web server to generate dynamic web pages. It is usually used to provide
interactive web sites that interface to databases or other data stores. The primary advantage of
server-side scripting is the ability to highly customize the response based on the user's
Page 2 of 22
Chapter One Server Side Scripting Basics
requirements, access rights, or queries into data stores. From security point of view, server-side
scripts are never visible to the browser as these scripts are executed on the server and emit
HTML corresponding to user's input to the page.
In contrast, server-side scripts, written in languages such as PHP, ASP.NET, Java, ColdFusion,
Perl, Ruby, Go, Python, and server-side JavaScript, are executed by the web server when the
user requests a document. They produce output in a format understandable by web browsers
(usually HTML), which is then sent to the user's computer. The user cannot see the script's
source code (unless the author publishes the code separately), and may not even be aware that a
script was executed. Documents produced by server-side scripts may, in turn, contain client-side
scripts.
Server-side Web scripting is mostly about connecting Web sites to back end servers, such as
databases. This enables two-way communication:
Dynamically edit, change or add any content to a Web page to make it more useful for
individual users
Respond to user queries or data submitted from HTML forms
Access any data or databases and return the result to a browser
Provide security since server side codes cannot be viewed from a browser
In server side script, since the scripts are executed on the server, the browser that displays the file
does not need to support scripting at all. The following are server-side scripting languages:
PHP (*.php)
Active Server Pages (ASP)
ANSI C scripts
Java via JavaServer Pages (*.jsp)
JavaScript using Server-side JavaScript (*.ssjs)
Lasso (*.lasso) etc
Page 3 of 22
Chapter One Server Side Scripting Basics
What is PHP?
PHP stands for Hypertext Preprocessor and is a server-side language. This means that the script
is run on your web server, not on the user's browser, so you do not need to worry about
compatibility issues. PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid,
PostgreSQL, Generic ODBC, Microsoft SQL Server etc.). PHP files can contain text, HTML
tags and scripts. Like other files written in server side language, PHP files are returned to the
browser as plain HTML and it has a file extension of ".php", ".php3", or ".phtml".
Why PHP?
Hopefully you have established a basic idea of what server-side scripting is, and when you
should use it. Next you need some basic requisites to be able to write and execute scripts.
Basically you need:
1) First of all you need a computer with a web server installed. PHP uses web servers such
as Apache, IIS etc. But for this course we will install WAMP server. WAMP server
refers to a software stack for the Microsoft Windows operating system, created by
Romain Bourdon and consisting of the Apache web server, OpenSSL for SSL (Secure
Sockets Layer) support, MySQL database and PHP programming language. WAMP sever
has a root directory called WWW. So all the files of a website must be stored under this
directory (C:\wamp\www\) to be executed by the server.
2) You need some sort of text editor such as Notepad, Notepad++, etc. to write the scripts.
3) You also need a web browser to display the web content. The web browser can be
Internet Explorer, Mozilla Firefox, Opera, and Google Chrome etc.
Page 4 of 22
Chapter One Server Side Scripting Basics
The PHP parsing engine needs a way to differentiate PHP code from other elements in the page.
The mechanism for doing so is known as ‘escaping to PHP.’ There are four ways to do this:
<?php
Your PHP code
here
If you use this style, you can be positive that your tags will always be correctly interpreted.
ii. Short-open (SGML-style) tags: Short or short-open tags look like this:
<?
Your PHP code
here
?>
Short tags are, as one might expect, the shortest option. We must do one of two things to enable
PHP to recognize the tags:
To use ASP-style tags, we should set the configuration option in your php.ini file.
iv. HTML script tags: HTML script tags look like this :
PHP output Statement <script
language="PHP">
Your PHP code here
</script>
Page 5 of 22
Chapter One Server Side Scripting Basics
As shown above PHP has different syntaxes but for maximum compatibility, it is recommended
to use <?php…?> .
Each code line in PHP must end with a semicolon. The semicolon is a separator and is used to
distinguish one set of instructions from another.
There are two basic statements to output text with PHP: echo and print.
echo has no return value whereas print has a return value. The returned value represents
whether the print statement is succeeded or not. If the print statement succeeds, the
statement returns 1 otherwise 0. It is rare that a syntactically correct print statement will
fail, but in theory this return value provides a means to test, for example, if the user’s
browser has closed the connection and sometimes the returned value can be used in
expressions.
echo can take multiple parameters (although such usage is rare) but print can only take
one argument.
echo is marginally faster than print.
The echo or print statement can be used with or without parentheses: echo or echo().
Page 6 of 22
Chapter One Server Side Scripting Basics
The command print is very similar to echo, with two important differences:
Unlike echo, print can accept only one argument.
Unlike echo, print returns a value, which represents whether the print statement
succeeded.
It is possible to embed HTML tags in echo or print statements. The browser will parse and
interpret them like any tag included in HTML page and display the page accordingly.
Table1.1 Using echo/print statements
echo/print statement PHP output web page display
echo “Hello World”; HelloWorld! HelloWorld!
The first echo statement includes a space so the space is output. The second row has two echo
statements, but neither includes a space, so no space appears in the Web page. Each echo
statement output does not go to new line unless we insert \n. The third row shows a space on the
Web page, even though no space is included in the echo statement. The space is added by the
browser when it reads the PHP output as HTML. In HTML, a new line is not displayed as a new
line; it is just interpreted as a single space.
Multi-lines printing: use the key word END next to <<< symbol and before the statement
terminating symbol (;) or enclose the statements to be displayed using double quotes. Here are
the examples to print multiple lines in a single print statement:
<?php
# First Example
print <<<END
This uses the "here document" syntax to output multiple lines with $variable
interpolation. Note that the here document terminator must appear on a line with
just a semicolon no extra whitespace!
END;
# Second Example
print "This spans multiple lines. The newlines will be
output as well";
?>
Page 7 of 22
Chapter One Server Side Scripting Basics
Note: The file must have a .php extension. If the file has a .html extension, the PHP code will
not be executed.
A comment is the portion of a program that exists only for the human reader and stripped out
before displaying the programs result. There are two commenting formats in PHP:
Single-line comments: They are generally used for short explanations or notes relevant
to the local code. Here are the examples of single line comments.
<?php
# This is a comment
// This is a comment too
print “An example with single line
comment”;
?>
Multi-lines comments: They are generally used to provide pseudo code algorithms and
more detailed explanations when necessary. The multiline style of commenting is the
same as in C. Here is the example of multi lines comments.
<?php
/* This is a comment with multiline
Author : Abebe Kebede
Purpose: Multiline Comments Demo
Subject: PHP
*/
echo "An example with multi line
comments";
1.6. ?>
Working with
Variables
A variable is a special container that can be defined to hold a value such as number, string,
object, array, or a Boolean. The main way to store information in the middle of a PHP program is
by using a variable. Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side and the
expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Page 8 of 22
Chapter One Server Side Scripting Basics
Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
PHP does a good job of automatically converting types from one to another when
necessary.
When creating PHP variables, you must follow these four rules:
Variable names must start with a letter of the alphabet or the _ (underscore) character.
Variable names can contain only the characters: a-z, A-Z, 0-9, and _ (underscore).
Variable names may not contain spaces. If a variable must comprise more than one word
it should be separated with the _ (underscore) character. (e.g., $user_name).
Variable names are case-sensitive. The variable $High_Score is not the same as the
variable $high_score.
PHP has a total of eight data types which we use to construct our variables: integers, doubles,
Booleans, null, strings, arrays, objects and resources. The first five are simple types, and the
next two (arrays and objects) are compound - the compound types can package up other arbitrary
values of arbitrary type, whereas the simple types cannot.
Integers:
Integers are whole numbers, without a decimal point, like 3214. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so:
$int_var = 12345;
$another_int = -12345 + 12345;
Doubles:
They are floating point numbers. By default, doubles print with the minimum number of decimal
places needed. For example, the code:
$pi= 3.14;
$version=1.12;
Boolean:
Page 9 of 22
Chapter One Server Side Scripting Basics
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so:
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
NULL:
NULL is a special type that only has one value: NULL. To give a variable the NULL value, simply assign it like
this:
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive; you
could just as well have typed:
$my_var = null;
A variable that has been assigned NULL has the following properties:
Strings:
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace variables
with their values as well as specially interpreting certain character sequences.
<? php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
$literally = "My $variable will print!\\n";
print($literally);
?>
There are no artificial limits on string length - within the bounds of available memory, you ought
to be able to make arbitrarily long strings.
Page 10 of 22
Chapter One Server Side Scripting Basics
Strings that are delimited by double quotes (as in "this") are preprocessed in both the following
two ways by PHP:
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their values.
PHP provides a large number of predefined variables to all scripts. The variables represent
everything from external variables to built-in environment variables, last error messages to last
retrieved headers.
Superglobals — Superglobals are built-in variables that are always available in all scopes
$GLOBALS — References all variables available in global scope
$_SERVER — Server and execution environment information
$_GET — HTTP GET variables
$_POST — HTTP POST variables
$_FILES — HTTP File Upload variables
$_REQUEST — HTTP Request variables, and can replace $_POST, $_GET and
$_COOKIE variables
$_SESSION — Session variables
$_COOKIE — HTTP Cookies
$php_errormsg — The previous error message
$HTTP_RAW_POST_DATA — Raw POST data
$http_response_header — HTTP response headers
$argc — The number of arguments passed to script
$argv — Array of arguments passed to script
Many of these variables, however, cannot be fully documented as they are dependent upon which
server are running, the version and setup of the server, and other factors.
Removing Variables
We can uncreated the variable by using this statement: unset(VariableName);
Page 11 of 22
Chapter One Server Side Scripting Basics
After this statement, the variable $age no longer exists. If we try to echo it, you get an
“undefined variable” notice. It is possible to unset more than one variable at once, as
follows: unset($age, $name, $address);
Variable Scope:
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types:
Local variables
Function parameters
Global variables
Static variables
A variable declared in a function is considered local; that is, it can be referenced solely in that
function. Any assignment outside of that function will be considered to be an entirely different
variable from the one contained in the function:
<?
$x = 4;
function assignx () {
$x = 0;
print "\$x inside function is $x. ";
}
assignx();
print "\$x outside of function is $x. ";
?>
Function parameters are declared after the function name and inside parentheses. They are
declared much like a typical variable would be:
<?
// multiply a value by 10 and return it to the caller
function multiply ($value) {
Page 12 of 22
Chapter One Server Side Scripting Basics
In contrast to the variables declared as function parameters, which are destroyed on the
function's exit, a static variable will not lose its value when the function exits and will still hold
that value should the function be called again.
You can declare a variable to be static simply by placing the keyword STATIC in front of the
variable name.
<?
function keep_track() {
STATIC $count = 0;
$count++;
print $count;
print " ";
}
keep_track();
Page 13 of 22
Chapter One Server Side Scripting Basics
keep_track();
keep_track();
?>
A constant is a name or an identifier for a simple value. A constant value cannot change during
the execution of the script. By default a constant is case-sensitive. By convention, constant
identifiers are always uppercase. A constant name starts with a letter or underscore, followed by
any number of letters, numbers, or underscores. If you have defined a constant, it can never be
changed or undefined.
To define a constant you have to use define() function and to retrieve the value of a constant, you
have to simply specifying its name. Unlike with variables, you do not need to have a constant
with a $. You can also use the function constant() to read a constant's value if you wish to obtain
the constant's name dynamically.
constant() function
As indicated by the name, this function will return the value of the constant.
This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It
is stored in a variable or returned by a function.
Example
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Only scalar data (boolean, integer, float and string) can be contained in constants.
There is no need to write a dollar sign ($) before a constant, where as in Variable one has
to write a dollar sign.
Constants cannot be defined by simple assignment, they may only be defined using the
define() function.
Page 14 of 22
Chapter One Server Side Scripting Basics
Constants may be defined and accessed anywhere without regard to variable scoping
rules.
Once the Constants have been set, may not be redefined or undefined.
In everyday life, numbers are easy to identify. They're 3:00 P.M., as in the current time, or 1.29
Birr, as in the cost of an item. Maybe they're like, the ratio of the circumference to the diameter
of a circle. In PHP, numbers can be all these things.
However, PHP doesn't treat all these numbers as "numbers." Instead, it breaks them down into
two groups: integers and floating-point numbers. Integers are whole numbers, such as -4, 0, 5,
and 1,975. Floating-point numbers are decimal numbers, such as -1.23, 0.0, 3.14159, and
9.9999999999.
Conveniently, most of the time PHP doesn't make you worry about the differences between the
two because it automatically converts integers to floating-point numbers and floating-point
numbers to integers. This conveniently allows you to ignore the underlying details. It also means
3/2 is 1.5, not 1, as it would be in some programming languages. PHP also automatically
converts from strings to numbers and back. For instance, 1+"1" is 2.
You want to ensure that a string contains a number. For example, you want to validate an age
that the user has typed into a form input field. Use is_numeric( ):
if (is_numeric('five')) { /* false */ }
if (is_numeric(5)) { /* true */ }
if (is_numeric('5')) { /* true */ }
if (is_numeric(-5)) { /* true */ }
if (is_numeric('-5')) { /* true */ }
Use the range( ) function, which returns an array populated with integers:
Page 15 of 22
Chapter One Server Side Scripting Basics
foreach(range($start,$end) as $i) {
echo “$i<br>”; }
Instead of using range( ), it can be more efficient to use a for loop. Also, you can increment
using values other than 1. For example:
for ($i = $start; $i <= $end; $i += $increment) {
echo “$i<br>”; }
Calculating Exponents
Formatting Numbers
You have a number and you want to print it with thousands and decimals separators. For
instance, you want to display prices for items in a shopping cart.
Strings in PHP are a sequence of characters, such as "We hold these truths to be self evident," or
"Once upon a time," or even "111211211". When you read data from a file or output it to a web
browser, your data is represented as strings. The followings are string manipulation operations:-
String concatenation operation: - To concatenate two string variables together, use the dot (.)
operator like echo $string1 . " " . $string2;
Substr()-uses to copy strings.
Page 16 of 22
Chapter One Server Side Scripting Basics
The start argument is the position in string at which to begin copying, with 0 meaning the
start of the string. The length argument is the number of characters to copy (the default is to
copy until the end of the string).
For example:
$name = "Fred Flintstone";
$fluff = substr($name, 6, 4);// $fluff is "lint" i.e copy strings from 6th about 4 chars consicativelly
$sound = substr($name, 11);// $sound is "tone" i.e copy from 11th character on wards and assign
to the variable $sound
substr_count():- uses to count how many times a smaller string occurs in a larger one.
For example:
$sketch = <<< End_of_Sketch
Well, there's egg and bacon; egg sausage and bacon; egg and spam;
egg bacon and spam; egg bacon sausage and spam; spam bacon sausage
and spam; spam egg spam spam bacon and spam; spam sausage spam spam
End_of_Sketch;
Has syntax of $string = substr_replace(original string, new string, start [, length ]);
where start shows starting from where we need replace by new string/ start is the index of the
first character that we need to replace. The length parameter uses to indicate how many
characters we need to replace from original characters.
The function replaces the part of original indicated by the start (0 means the start of the
string) and length values with the string new. If no fourth argument is given, substr_replace(
) removes the text from start to the end of the string.
For instance:
Page 17 of 22
Chapter One Server Side Scripting Basics
Here's how can insert at the beginning of the string without deleting from orginal character:
A negative value for start indicates the number of characters from the end of the string from
which to start the replacement:
$farewell = substr_replace($farewell, "riddance", -3);
A negative length indicates the number of characters from the end of the string at which to stop
deleting:
$farewell = substr_replace($farewell, "", -8, -5);
strrev() function:- takes a string and returns a reversed copy of it. Has syntax:-
$string = strrev(string);
For example:
echo strrev("There is no cabal");
labac on si erehT
str_repeat() function:- takes a string and a count and returns a new string consisting of the
Page 18 of 22
Chapter One Server Side Scripting Basics
str_pad( ) function:- pads one string with another i.e left blank space. Optionally, we can say
what string to pad with, and whether to pad on the left, right, or both:
$padded = str_pad(to_pad, length [, with [, pad_type ]]);
The optional fourth argument can be either STR_PAD_RIGHT (the default), STR_PAD_LEFT, or
STR_PAD_BOTH (to center). For example:
echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_LEFT) . "]\n";
echo '[' . str_pad('Fred Flintstone', 30, ' ', STR_PAD_BOTH) . "]\n";
[ Fred Flintstone]
[ Fred Flintstone ]
strpos() function:- used to search for a string or character within a string. If a match is found in
the string, this function will return the position of the first match. If no match is found, it will
return FALSE.
The output will be 6. As seen the position of the string "world" in our string is position 6. The
reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
Example:-
$long = "Today is the day we go on holiday to Florida";
$to_find = "day";
$pos = strpos(strrev ($long), strrev($to_find));
if ($pos === false) {
Page 19 of 22
Chapter One Server Side Scripting Basics
echo("Not found");
} else {
// $pos is offset into reversed strings
// Convert to offset into regular strings
$pos = strlen($long) - $pos - strlen($to_find);;
echo("Last occurrence starts at position $pos");
}
String-Searching Functions
Several functions find a string or character within a larger string. They come in three families:
strpos() and strrpos(), which return a position; strstr() and strchr(), which return the
string they find; and strspn() and strcspn(), which return how much of the start of the string
matches a mask.
The strstr() function finds the first occurrence of a small string in a larger string and returns
from that small string on. For instance:
$record = "Fred,Flintstone,35,Wilma";
$rest = strstr($record, ","); // $rest is ",Flintstone,35,Wilma"
As with strrpos(), strrchr() searches backward in the string, but only for a character, not for
an entire string.
Reading Assignment
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
An array stores multiple values in one single variable:
Page 20 of 22
Chapter One Server Side Scripting Basics
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " .
$cars[2] . ".";
?>
Page 21 of 22
Chapter One Server Side Scripting Basics
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
The named keys can then be used in a script:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Multidimensional Arrays
Multidimensional arrays will be explained in the PHP advanced section.
Page 22 of 22