Lab 6
Lab 6
Web server
introduction
A website is a set of related web pages containing content such as text, images, video, audio, etc. A website is hosted on at least
one web server, accessible via a network such as the Internet or a private local area network through an Internet address known
as a Uniform Resource Locator. All publicly accessible websites collectively constitute the World Wide Web.
A webpage is a document, typically written in plain text interspersed with formatting instructions of Hypertext Markup
Language (HTML, XHTML). A webpage may incorporate elements from other websites with suitable markup anchors.
WebPages are accessed and transported with the Hypertext Transfer Protocol (HTTP), which may optionally employ encryption
(HTTP Secure, HTTPS) to provide security and privacy for the user of the webpage content. The user's application, often a web
browser, renders the page content according to its HTML markup instructions onto a display terminal.
1
For dynamic web pages, the procedure is a little more involved, because it may bring both PHP and MySQL into the mix (see
Figure 2). Here are the steps:
1. You enter http://server.com into your browser’s address bar.
2. Your browser looks up the IP address for server.com.
3. Your browser issues a request to that address for the web server’s home page.
4. The request crosses the Internet and arrives at the server.com web server.
5. The web server, having received the request, fetches the home page from its hard disk.
6. With the home page now in memory, the web server notices that it is a file incorporating PHP scripting and passes the page to
the PHP interpreter.
7. The PHP interpreter executes the PHP code.
8. Some of the PHP contains MySQL statements, which the PHP interpreter now passes to the MySQL database engine.
9. The MySQL database returns the results of the statements back to the PHP interpreter.
10. The PHP interpreter returns the results of the executed PHP code, along with the results from the MySQL database, to the
web server.
11. The web server returns the page to the requesting client, which displays it.
2
PHP and HTML Are Different Languages
It is important to keep in mind that HTML and PHP are two very different languages used for different purposes and executed by
totally different processes. HTML is called a markup language, which combines text with tags to define the structure and
describe the way a document will be displayed. PHP is a programming language that consists of data and instructions and
procedures that tell the computer what operations to perform on the data.
PHP
What is PHP?
PHP files can contain text, HTML, JavaScript code, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain HTML
PHP files have a default file extension of ".php"
With PHP you are not limited to output HTML. You can output images, PDF files, and even Flash movies. You can also output
any text, such as XHTML and XML.
3
Why PHP?
The PHP script is placed between the PHP open tag <?php and the PHP close tag ?>. The code between these two tags is
what the PHP module processes.
EXAMPLE
<?php print "Hello, world"; // This is the C++ style
print "Hello, world"; comment
?> /* This is a C style comment and it can span
multiple lines */
There are three styles of PHP comments: # And this is a Shell style comment
<?php ?>
variable
A variable is just a storage area. You put things into your storage areas (variables) so that you can use and manipulate them in
your programmes. Things you'll want to store are numbers and text.
$variable_name = Value;
If you forget that dollar sign at the beginning, it will not work. This is a common mistake for new PHP programmers!
Note: Also, variable names are case-sensitive, so use the exact same capitalization when using a variable. The
variables $a_number and $A_numberare different variables in PHP's eyes.
<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
There are a few rules that you need to follow when choosing a name for yourPHP variables.
The scope of a variable is the part of the script where the variable can be referenced/used. PHP has four different variable
scopes:
local
global
static
parameter
4
Local Scope
A variable declared within a PHP function is local and can only be accessed within that function:
Example
<?php echo $x; // local scope
$x=5; // global scope }
You can have local variables with the same name in different functions, because local variables are only recognized by the
function in which they are declared. Local variables are deleted as soon as the function is completed.
Global Scope
A variable that is defined outside of any function, has a global scope. Global variables can be accessed from any part of the
script, EXCEPT from within a function. To access a global variable from within a function, use the global keyword:
Example
<?php
$x=5; // global scope
$y=10; // global scope
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable. This array
is also accessible from within functions and can be used to update global variables directly. The example above can be rewritten
like this:
Example
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
5
Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be
deleted.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained from the last time the function
was called.
Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code. Parameters are declared in a parameter
list as part of the function declaration:
Example
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
String variables are used for values that contain characters. After we have created a string variable we can manipulate it. A string
can be used directly in a function or it can be stored in a variable. In the example below, we create a string variable called txt,
then we assign the text "Hello world!" to it. Then we write the value of the txt variable to the output:
Example
<?php
$txt="Hello world!";
echo $txt;
?>
6
The PHP Concatenation Operator
There is only one string operator in PHP. The concatenation operator (.) is used to join two string values together. The example
below shows how to concatenate two string variables together:
Example
<?php
$txt1="Hello world!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
The output of the code above will be: Hello world! What a nice day!
The PHP strlen() function
Sometimes it is useful to know the length of a string value. The strlen() function returns the length of a string, in characters. The
example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!");
?>
The output of the code above will be: 12
The PHP strpos() function
The strpos() function is used to search for a character or a specific text within a string. If a match is found, it will return the
character position of the first match. If no match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!","world");
?> The output of the code above will be: 6.
Tip: The position of the string "world" in the example above is 6. The reason that it is 6 (and not 7), is that the first character
position in the string is 0, and not 1.
String types
PHP supports two types of strings that are denoted by the type of quotation mark that you use. If you wish to assign a literal
string, preserving the exact contents, you should use the single quotation mark (apostrophe), like this:
$info = 'Preface variables with a $ like this: $variable';
In this case, every character within the single-quoted string is assigned to $info. If you had used double quotes, PHP would have
attempted to evaluate $variable as a variable.
On the other hand, when you want to include the value of a variable inside a string, you do so by using a double-quoted string:
echo "There have been $count presidents of the US";
Escaping characters
Sometimes a string needs to contain characters with special meanings that might be interpreted incorrectly. For example, the
following line of code will not work, because the second quotation mark (apostrophe) encountered in the word sister’s will tell
the PHP parser that the end of the string has been reached. Consequently, the rest of the line will be rejected as an error:
$text = 'My sister's car is a Ford'; // Erroneous syntax
7
To correct this, you can add a backslash directly before the offending quotation mark to tell PHP to treat the character literally
and not to interpret it:
$text = 'My sister\'s car is a Ford';
Additionally, you can use escape characters to insert various special characters into strings, such as tabs, newlines, and carriage
returns. These are represented, as you might guess, by \t, \n, and \r. Here is an example using tabs to lay out a heading; it is
included here merely to illustrate escapes, because in web pages there are always better ways to
do layout:
$heading = "Date\tName\tPayment";
Multiple-Line Commands
There are times when you need to output quite a lot of text from PHP, and using several echo (or print) statements would be
time-consuming and messy. To overcome this, PHP offers two conveniences. The first is just to put multiple lines between
quotes, as
<?php
$author = "Alfred E Newman";
echo "This is a Headline
This is the first line.
This is the second.
Written by $author.";
?>
PHP also offers a multiline sequence using the <<< operator, commonly referred to as here-document or heredoc for short. This
is a way of specifying a string literal, preserving the line breaks and other whitespace (including indentation) in the text.
<?php
$author = "Alfred E Newman";
echo <<<_END
This is a Headline
This is the first line.
This is the second.
- Written by $author.
_END;
?>
PHP Arithmetic Operators
8
PHP Assignment Operators
9
PHP Logical Operators
ex:
<?php
$myname = "Brian";
$myage = 37;
echo "a: " . 73 . "<br />"; // Numeric literal
echo "b: " . "Hello" . "<br />"; // String literal
echo "c: " . FALSE . "<br />"; // Constant literal
echo "d: " . $myname . "<br />"; // Variable string literal
echo "e: " . $myage . "<br />"; // Variable numeric literal
?>
Example: The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
When a user fills out the form above and clicks on the submit button, the form data is sent to a PHP file, called "welcome.php":
10
Output could be something like this:
Welcome John!
You are 28 years old.
Note: The predefined $_GET variable is used to collect values in a form with method="get"
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address bar) and
has limits on the amount of information to send.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
Conditionals
Conditionals alter program flow. They enable you to ask questions about certain things and respond to the answers you get in
different ways. Conditionals are central to dynamic web pages—the goal of using PHP in the first place—because they make it
easy to create different output each time a page is viewed. There are three types of nonlooping conditionals: the if statement, the
switch statement, and the ? operator.
The if Statement
<?php else
if ($bank_balance < 100) {
{ $savings += 50;
$money = 1000; $bank_balance -= 50;
$bank_balance += $money; }
} ?>
$savings += 100;
EX: $bank_balance -= 100;
<?php }
if ($bank_balance < 100) else
{ {
$money = 1000; $savings += 50;
$bank_balance += $money; $bank_balance -= 50;
} }
elseif ($bank_balance > 200) ?>
{
The switch Statement
<?php
switch ($page)
{
case "Home":
11
echo "You selected Home";
break;
case "About":
echo "You selected About";
break;
case "News":
echo "You selected News";
break;
case "Login":
echo "You selected Login";
break;
case "Links":
echo "You selected Links";
break;
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost
equal lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
12
The do...while Statement
The do...while statement will always execute the block of code once, it will then check the condition, and repeat the loop while the
condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
13
EX:
<html>
<head>
<title>Font Choices</title>
</head>
<body>
<center>
<h1>Font Choices</h1>
<h3>Demonstrates how to read HTML form elements</h3>
<h3>Text to modify</h3>
<textarea name = "basicText"
rows = "10"
cols = "40">
software engineering is “A discipline whose aim is the production of quality software, software that is delivered on time, within
budget, and that satisfies its requirements”.</textarea>
<td>
<input type = "radio"
name = "sizeType"
value = "px">pixels<br>
<input type = "radio"
name = "sizeType"
value = "pt">points<br>
<input type = "radio"
name = "sizeType"
value = "cm">centimeters<br>
14
<input type = "radio"
name = "sizeType"
value = "in">inches<br>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
borderMaker.php
<html> border-style:$y;
<head> border-color:green"
<title>Your Output</title> HERE;
</head>
<body> print "<div style = $theStyle>";
<h1>Your Output</h1> print $_post["basicText";
<center> print "</span>";
<?
$x=$_post["borderSize$sizeType"]; ?>
$y=$_post["borderStyle"]; </center>
$theStyle = <<<HERE </body>
"border-width:$; </html>
Assignment
design the following web page, if user typing the correct name and password then the page will be
forwarded to another web page otherwise a message contains "wrong username or password" will appear.
15