Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Server Side Programming

By Dr. Babaousmail Hassen

Lecturer at Binjiang College of NUIST

1
Another Simple Example of PHP Script
To process the form, we need to create the script say processorder.php. Open
your text editor and create this file. Type in the following code:

<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
</body>
</html>

Notice, how everything we’ve typed so far is just simple HTML. It’s now
time to add some simple PHP code to our script.
2
Embedding PHP in HTML
Under the <h2> heading in your file, add the following lines:
<?php
echo '<p>Order processed.</p>';
?>
Save the file and load it in your browser (Type the following address in
address of your browser- http://localhost/processorder.php or
http://localhost:port/processorder.php). You should see something similar
to the output shown in Figure 1.2.

3
Try viewing the source from your browser. You should see this code:

<html>
<head>
<title>Bob's Auto Parts - Order Results</title>
</head>
<body>
<h1>Bob's Auto Parts</h1>
<h2>Order Results</h2>
<p>Order processed.</p></body>
</html>
Again none of the raw PHP is visible. This is because the PHP interpreter
has run through the script and replaced it.

This means that from PHP we can produce clean HTML accessible with any
browser—in other words, the user’s browser does not need to understand
PHP.

4
The code that we now have in this file consists of four things:

 HTML
 PHP tags
 PHP statements
 Whitespace

We can also add


• Comments
Most of the lines in the previous example are just plain HTML.

5
PHP Tags

The PHP code in the previous example began with <?php


and ended with ?>. This is similar to all HTML tags
because they all begin with a less than (<) symbol and end
with a greater than (>) symbol. These symbols are
called PHP tags that tell the Web server where the PHP
code starts and finishes. Any text between the tags will be
interpreted as PHP. Any text outside these tags will be
treated as normal.

6
PHP Tag Styles

There are actually four different styles of PHP tags we can use.

1. XML style
<?php echo '<p>Order processed.</p>'; ?>

It is the preferred tag style to use with PHP. The server administrator cannot
turn it off, it will be available on all servers. This style of tag can be used with
XML (Extensible Markup Language) documents.

7
2. Short style
<? echo '<p>Order processed.</p>';?>

This style of tag is the simplest and follows the style of an SGML (Standard
Generalized Markup Language) processing instruction. To use this type of tag you
either need to enable short_tags in your config file, or compile PHP with short tags.

3. SCRIPT style
<script language='php'> echo '<p>Order processed.</p>'; </script>

This style of tag is the longest and will be familiar if you’ve used JavaScript or
VBScript.

4. ASP style
<% echo '<p>Order processed.</p>';%>

This style of tag is the same as used inActive Server Pages (ASP). It can be used if you
have enabled the asp_tags configuration setting.

8
PHP Statements

We tell the PHP interpreter what to do by having PHP statements


between our opening and closing tags. In this example, we used
only one type of statement:

echo '<p>Order processed.</p>';


The echo construct has a very simple result; it prints (or
echoes) the string passed to it to the browser. In Figure, you
can see the result is that the text "Order processed." appears in
the browser window.

9
Whitespace

Spacing characters such as new lines, spaces, and tabs are known as whitespace.
Browsers ignore whitespace in HTML. So does the PHP engine?
Consider these two HTML fragments:
<h1>Welcome to Bob's Auto Parts!</h1><p>What would you like to order
today?</p>
And
<h1>Welcome to Bob's Auto Parts!</h1>
<p>What would you like to order today?</p>

These two parts of HTML code produce identical output because they appear the same to
the browser. However, you are encouraged to use whitespace in your HTML as an aid to
humans—to enhance the readability of your HTML code.

10
Whitespace

The same is true for PHP. There is no need to have any whitespace
between PHP statements, but it makes the code easier to read if we put
each statement on a separate line. For example,

echo 'hello ';


echo 'world';

and
echo 'hello ';echo 'world';

are equivalent, but the first version is easier to read.


11
Comments

Comments can be used to explain the purpose of the


script, who wrote it, why they wrote it the way they
did, when it was last modified, and so on. You will
generally find comments in all but the simplest PHP
scripts.
The PHP interpreter will ignore any text in a
comment.

12
Example of comment in PHP

/* Author: Bob Smith


Last modified: April 10
This script processes the customer orders.
*/
Multiline comments should begin with a /*and end with */.
You can also use single line comments, either in the C++ style:

echo '<p>Order processed.</p>'; // Start printing order


or in the shell script style:
echo '<p>Order processed.</p>'; # Start printing order
With both of these styles, everything after the comment symbol (#or //) is a
comment.

13
Adding Dynamic Content

The main reason for using a server-side scripting language is to be able to provide
dynamic content to a site’s users. This is an important application because content that
changes according to a user’s needs or over time will keep visitors coming back to a
site. PHP allows us to do this easily.
Let’s start with a simple example.
Replace the PHP in processorder.php with the following code:
<?php
echo '<p>Order processed at ';
echo date('H:i, jS F');
echo '</p>';
?>
In this code, we are using PHP’s built-in date() function to tell the customer the date
and time when his order was processed. This will be different each time the script is
run.

14
Save the file and load it in your browser (Type the following address in
address of your browser- http://localhost/processorder.php or
http://localhost:port/processorder.php). You should see something similar
to the output shown in Figure 1.2.

15
Calling Functions

Look at the call to date().This is one of the calling function of PHP. PHP has
an extensive library of functions you can use when developing Web
applications.
Most of these functions need to have some data passed to them and return
some data.
Look at the function call:
date('H:i, jS F')

Notice that we are passing a string (text data) to the function inside a pair of
parentheses. This is called the function’s argument or parameter. These
arguments are the input used by the function to output some specific results.

The date() Function


In the date() function. H is the hour in a 24-hour format, i is the minutes with a leading
zero where required, j is the day of the month without a leading zero, S represents the
ordinal suffix (in this case "th"), and Fis the full name of the month.
16
Variables

You can recognize variable names in PHP because they all start with a dollar
sign ($). (Forgetting the dollar sign is a common programming error.)

The following statement creates a variable called $testvariable and assigns it a literal
value of 3:
$testvariable = 3;

In PHP a single variable may contain any type of data, be it a number, a string of
text, or some other kind of value, and may change types over its lifetime.
So the following statement, if you were to type it after the statement above, assigns a
new value to the existing $testvariable.
In the process, the variable changes type: where it used to contain a number, it now
contains a string of text:
$testvariable = 'Three';

17
Variables
The equals sign we used in the last statements is called the assignment operator, as
it’s used to assign values to variables. Other operators may be used to perform
various mathematical operations on values:

$testvariable = 1 + 1; // Assigns a value of 2


$testvariable = 1 - 1; // Assigns a value of 0
$testvariable = 2 * 2; // Assigns a value of 4
$testvariable = 2 / 2; // Assigns a value of 1

From the above examples, you can probably tell that + is the addition operator, - is
the subtraction operator, * is the multiplication operator, and / is the division
operator. These are all called arithmetic operators, because they perform arithmetic
on numbers.

Each of the lines above ends with a comment. Comments are away to describe what
your code is doing.

18
String concatenation operator
A period (.) between two text string sticks strings of text together and known as
string concatenation operator

Example:

$testvariable = 'Hi ' . 'there!'; // Assigns a value of 'Hi there!'

Some Other Examples of variables and Arithmetic Operator

$var1 = 'PHP'; // Assigns a value of 'PHP' to $var1


$var2 = 5; // Assigns a value of 5 to $var2
$var3 = $var2 + 1; // Assigns a value of 6 to $var3
$var2 = $var1; // Assigns a value of 'PHP' to $var2
echo $var1; // Outputs 'PHP'
echo $var2; // Outputs 'PHP'
echo $var3; // Outputs '6'
echo $var1 . ' rules!'; // Outputs 'PHP rules!'
echo '$var1 rules!'; // Outputs '$var1 rules!' 19
Variable Types

A variable’s type refers to the kind of data that is stored in it.

PHP’s Data Types


PHP supports the following data types:
 Integer—Used for whole numbers
 Double—Used for real numbers
 String—Used for strings of characters
 Boolean—Used for true or false values
 Array—Used to store multiple data items of the same type
 Object—Used for storing instances of classes

20
Arithmetic Operators
We have already discussed some arithmetic operators/ Let us revise and
discuss some other arithmetic operators. The arithmetic operators are
shown in Table below
Operator Name Example
+ Addition $a + $b
- Subtraction $a - $b
* Multiplication $a * $b

/ Division $a / $b
% Modulus $a % $b
Consider this code fragment:
$a = 27;
$b = 10;
$result = $a%$b;
The value stored in the $resultvariable is the remainder when we divide 27
by 10; that is, 7.
Arithmetic Operators

The result of the modulo operator % has the same sign as the dividend — that is, the result
of $a % $b will have the same sign as $a. For example:

<?php
echo (5 % 3)."\n"; // prints 2
echo (5 % -3)."\n"; // prints 2
echo (-5 % 3)."\n"; // prints -2
echo (-5 % -3)."\n"; // prints -2
?>

Some other Arithmetic Operators


Example Name Result
+$a Identity Conversion of $a to int as appropriate.

-$a Negation Opposite of $a.


$a ** $b Exponentiation Result of raising $a to the $b'th power.
A very simple use of the modulus (%) operator is to check if an integer is odd or even.
<?php
if (($a % 2) == 1)
{ echo "$a is odd." ;}
if (($a % 2) == 0)
{ echo "$a is even." ;}
?>

Some Examples of Assignment Operators


<?php In the same
expression we
$a = ($b = 4) + 5; // $a is equal to 9 now, and $b has been set to 4. can use
assignment
operator two
?> times
<?php

$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
?>
Comparison Operators
Example Name Result
$a == $b Equal TRUE if $a is equal to $b
$a === $b Identical TRUE if $a is equal to $b, and they are of the same
type.
$a != $b Not equal TRUE if $a is not equal to $b
$a <> $b Not equal TRUE if $a is not equal to $b
$a !== $b Not identical TRUE if $a is not equal to $b, or they are not of the
same type.
$a < $b Less than TRUE if $a is strictly less than $b.
$a > $b Greater than TRUE if $a is strictly greater than $b.
$a <= $b Less than or TRUE if $a is less than or equal to $b.
equal to
$a >= $b Greater than or TRUE if $a is greater than or equal to $b.
equal to
$a <=> $b Spaceship An integer less than, equal to, or greater than zero
when $a is respectively less than, equal to, or
greater than $b.
Comparison Operators

This <=> operator offers combined comparison :


•Return 0 if values on either side are equal
•Return 1 if value on the left is greater
•Return -1 if the value on the right is greater
// Strings
<?php echo "a" <=> "a"; // 0
// Integers echo "a" <=> "b"; // -1
echo 1 <=> 1; // 0 echo "b" <=> "a"; // 1
echo 1 <=> 2; // -1 echo "a" <=> "aa"; // -1
echo 2 <=> 1; // 1 echo "zz" <=> "aa"; // 1

// Arrays
// Floats echo [] <=> []; // 0
echo 1.5 <=> 1.5; // 0 echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo 1.5 <=> 2.5; // -1 echo [1, 2, 3] <=> []; // 1
echo 2.5 <=> 1.5; // 1 echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1
?>
Questions

Q1 <?php Q3 Define Spaceship operator


and its symbol with one example.
$a = 27;
$b = 5; Q4 <?php
$result = $a%$b; echo 1 <=> 1;
echo 1 <=> 2;
?> echo 2 <=> 1;
?>
Q2 <?php
echo (14 % 3)."\n";
echo (14 % -3)."\n";
echo (-14 % 3)."\n";
echo (-14 % -3)."\n";
?>
Error Control Operators

PHP supports one error control operator: the At sign (@). When prepended to an expression
in PHP, any error messages that might be generated by that expression will be ignored.
<?PHP
(@include("file.php"))
OR die("Could not find file.php!");
?>

This cause, that error reporting level is set to zero also for the included file. So if there are some
errors in the included file, they will be not displayed.

Another example is
<?php
$x = @$a["name"];
?>
There are only 2 possible problems here: a missing variable or a missing index. If you're sure
you're fine with both cases, you're good to go.
Example 1:

<?php
echo 2/0; //Gives warning : Division by zero
echo @(2/0); echo 2/0; //@ suppresses the warning
}

?>

Output

Warning: Division by zero in


I:\xampp\htdocs\xampp\ComparisonOpearatorsExample.php
on line 3

In the above example, we do not get the warning "Division by zero" when we add Error
Control operator before the expression 2/0.
Example 2:

<?php
method(); //Gives Fatal Error : Call to undefined function methodCall()
echo @(2/0); echo 2/0; //@ suppresses the Fatal error
}
?>

Output
Fatal error: Call to undefined function methodCall() in
I:\xampp\htdocs\xampp\ComparisonOpearatorsExample.php on line 5

In the above example we are calling a function which has not been defined, that a
fatal error is thrown.
But when the function call is prefixed by @ operator, the fatal error is not
displayed.
Incrementing/Decrementing Operators

Example Name Effect


++$a Pre-increment Increments $a by one,
then returns $a.
$a++ Post-increment Returns $a, then
increments $a by one.
--$a Pre-decrement Decrements $a by
one, then returns $a.
$a-- Post-decrement Returns $a, then
decrements $a by
one.
A simple example script:

….
<?php echo "<h3>Postdecrement</h3>";
echo "<h3>Postincrement</h3>"; $a = 5;
$a = 5; echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 5: " . $a++ . "<br />\n"; echo "Should be 4: " . $a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";
echo "<h3>Predecrement</h3>";
echo "<h3>Preincrement</h3>"; $a = 5;
$a = 5; echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 6: " . ++$a . "<br />\n"; echo "Should be 4: " . $a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n"; ?>

Assignment

 No assignment for this week, just


read the PPT carefully and
understand it.

32

You might also like