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

Republic of the Philippines

CAVITE STATE UNIVERSITY


Silang Campus
Biga I, Silang, Cavite
 046 513-5706  046 513-3965
✉ cvsusilang@cvsu.edu.ph

DEPARTMENT OF INFORMATION TECHNOLGY

ITEC50 – Web System Technologies

Module 5 (Week 14-15)


Introduction to Hypertext Preprocessor

Overview
Do you remember how websites used to be very static and boring to look at not too long ago? In contrast,
today’s websites are more dynamic, interactive and easier to use overall. One of the things that made
this possible is a programming language called PHP.

PHP, or Hypertext Preprocessor, is a popular scripting language used to create the attractive, user-
friendly and interactive Web pages that we see today. PHP is open-source which means that it is well-
documented and can easily be downloaded for free from the Web.

Objectives

After working on this module, you will be able to:


1. Apply hypertext Preprocessor and its functions

Introduction to PHP

 PHP (Hypertext Preprocessor) is an open-source HTML-embedded server-side scripting


language that is used to develop dynamic and interactive web applications and also used as
a general-purpose programming language.

Some Facts about PHP:


 PHP was developed by Rasmus Lerdorf in 1995 and is later being developed as an open-source.
PHP group now manages the implementation of PHP.
 PHP has many syntaxes similar to C, Java, and Perl, and has many unique features and specific
functions.
 PHP page is a file with a .php extension can contain a combination of HTML Tags and PHP scripts.
 PHP recursive acronym for PHP(Hypertext Preprocessor): HyperText means, text containing all
sorts of web markups, PreProcessor means all of the HyperText is processed first and then the

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


result is sent as pure HTML to the web browser. A client cannot see the PHP source code because
it is preprocessed and interpreted.
 PHP is Server-side scripting language: Server-side scripting means that the PHP code is
processed on the web server rather than the client machine.
 PHP supports many databases (MySQL and PHP combination is widely used).
 PHP is an open-source scripting language.
 PHP is free to download and use.

What you can do with PHP?


 PHP is used to create web applications, and some of the most popular web applications like
Facebook, Yahoo, Wikipedia, Twitter, WordPress have all been developed in PHP. And you can
also develop the next big thing using PHP.

Why PHP?
 The best thing about using PHP is extremely easy for a newcomer, and also it has many advanced
features for a professional programmer.
 Learning PHP is very easy, and it runs efficiently on the server-side.
 PHP works on many operating systems such as Linux, Windows, Mac OS X.
 PHP is FREE to download from the official PHP resource: php.net
 PHP supports many databases like MySQL, MS SQL, Oracle, Sybase, PostgreSQL, and many
others.
 PHP can dynamically generate HTML, PDF, Flash, Text, CSV, XML and many others.
 Coding in PHP is easy and fast, so it takes less time to build an application.
 Many good PHP frameworks like Zend, Codeigniter, and Laravel are available for PHP.
 Many web hosting options are available at a fair price for PHP.
 With PHP, code deployment is very easy.
 Substantial PHP community support, and many tutorials and sample programs are available
online.

What you need to run PHP

To run PHP code, you need the following three software on your local machine:

1. Web Server (e.g., Apache)


2. PHP (Interpreter)
3. MySQL Databases (optional)

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


You can separately install Web Server, PHP Interpreter, and MySQL databases, but to make work easier,
developers have made all in one setup package called WAMP, LAMP, MAMP and XAMPP which will
automatically install and set up PHP environment on your Windows, Linux or MAC machines.

 WAMP (Windows, Apache, MySQL, PHP)


 LAMP (Linux, Apache, MySQL, PHP)
 MAMP (MAC, Apache, MySQL, PHP)
 XAMPP (Windows/Linux/MAC, Apache, MySQL, PHP)

Start where?
To execute PHP code, you need access to a web server in which PHP is running.

Your main options are:

 Install Apache and PHP or Install WAMP, LAMP, MAMP or XAMPP according to your OS.
 After installation, you need to run and start the Apache Server and PHP from your program list,
and then type http://localhost in your web browser for a start working.
 In the Apache installation folder, you will find the www folder, where you can save PHP files, and
you can also create your project folder inside the www folder.
 Find a web hosting plan with Apache, PHP, and MySQL support and Run your PHP scripts on
your Web host.
 You can also use runphponline.com interface to interpret your PHP code online.

Note: You can watch this link in YouTube to know how to install wamp server.
(https://www.youtube.com/watch?v=xoMggz9-n6E&feature=emb_imp_woyt)

Creating the script


You need to use a text editor program to write your code. All OS come with one or more text editors, for
example:

1. Windows Notepad
2. Vi or Emacs on Linux
3. TextEdit on Mac OS X

Note: Commercially, Adobe Dreamweaver, NetBeans, and Sublime Text are used to edit PHP code.

PHP Basics
This lesson gives you a fundamental understanding of PHP files, its configuration and How PHP works.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


The PHP file:

 PHP file will have a .php or .php3 extension; you also have the option of changing the default file
extension using the web server's configuration file.
 A .php file should have all the PHP code within <?php (opening tag) and ?> (closing tag), then It
will be considered as PHP language code and parsed accordingly. It is also useful when you want
to write PHP code with HTML.
 PHP can be embedded inside HTML but in a slightly different fashion. In between the HTML tags
where ever you want to make use of PHP code, you will have to use <?php /*PHP code*/ ?> and
PHP will parse this.
 All PHP statements must end with a ; (semicolon) which is also called statement terminator. It is
essential because semicolon tells the PHP interpreter to read this line as a single statement, and
without this, you will see error messages while interpreting the code.

The php.ini file


 php.ini is a plain text file that configures PHP settings. PHP interpreter reads the php.ini file to
determine what settings to use. We will refer to this file from time to time in the course, but now, it
is enough that you are aware of its existence.

How PHP works


 When a user navigates in her browser to a page that ends with a .php extension, the browser
sends an HTTP request to the web server, for example, you are typing the URL of the file index.php
and hit enter, the browser will send the request to server and server will start finding this file on its
file system. If the server finds the file, the server will send this file to PHP interpreter. Otherwise,
the server will generate ERROR 404, which is also known as file not found.

 The web server only sends those files to an interpreter, whose file extension is .php, all other files
such as .html, .htm and others are not sent to PHP interpreter even if they contain PHP codes
inside them.

 Once the file is sent to the PHP interpreter, it starts finding all of the opening and closing PHP tags
and then process the PHP code inside these tags.

 PHP interpreter also checks that whether there is a database connection or not, if it finds database
connection then it will send or retrieve data from the database.

 PHP scripts are interpreted on the web server, and outcome (HTML) is sent back to the client
machine.
As shown in the picture, PHP
interprets the page and
primarily communicates with
the file system, database, and
email server, and then delivers
a web page to the web server
to return to the browser.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


PHP Coding Standard
PHP follows few rules and maintains its style of coding. As there are many developers all over the
world, if each of them follows different coding styles and standards this will raise great confusion and
difficulty for a developer to understand another developer’s code. It will be very hard to manage and
store the code for future reference.
The coding standards come into play for all the reasons.
Reasons for maintaining coding standards:
 People working in different modules can easily manage the source code due to familiarity.
 Acts as a blueprint for other team members to understand the code for management or changes.
 Clarity saves a lot of time doing common mistakes as it’s easy to understand.
 Coding standards or industry standards improve the quality and consistency of software.

PHP Syntax
This lesson has a detailed description of PHP Syntax. It's essential for you to before proceeding to learn
more advanced lessons in PHP.

PHP Tags
PHP is designed to work with HTML, so you can easily write and embed PHP code with HTML. A PHP
code block begins with <?php tag and ends with ?> tag.

PHP with HTML


 echo is a command in PHP for writing output data to the browser, and at the end of each PHP
statement we require to write a ; (semicolon) as you see in the below example code. Otherwise, if
you write another statement, then PHP will report a syntax error.

To run this PHP program, you need to write above code in any text editor and save it to your web server
under www directory with a .php extension.

Once it's done, start the server and go to localhost and type in the path of your file, i.e.,
http://localhost/HelloWorld.php

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


Note: You can watch this link in YouTube to know how to write and execute PHP.
(https://www.youtube.com/watch?v=SNA3Z5dq_Ko&feature=emb_imp_woyt)

Comments in PHP
 The PHP interpreter ignores the comment block; it can be used anywhere in the program to add
info about program or code block, which can be helpful for the programmer to understand the
code easily in the feature.
 In PHP, we can use // or # to make a single-line comment, and /* and */ to make a large
comment block.

PHP – Line Length and Indentation


It is a standard recommendation to not exceed more than 75-85 characters per line of code. One must
not use tabs for indentation instead use spaces as it is the standard indenting method in most
programming languages. One statement per line or else split lines for long multiple ones.

PHP – Control structures


The control flow or conditional statements must be written in such a way so that they could be
differentiated from function call statements. While writing if, for, else, foreach, do, while, switch, and
other controls flow statements there must be one space between the keyword and the opening
parenthesis. The function definitions do not have any space between the function name and opening
parenthesis.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


PHP - Functions

PHP functions are similar to other programming languages. A function is a piece of code which takes one
more input in the form of parameter and does some processing and returns a value.

You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP
gives you option to create your own functions as well.

There are two parts which should be clear to you:

1. Creating a PHP Function


2. Calling a PHP Function

In fact, you hardly need to create your own PHP function because there are already more than 1000 of
built-in library functions created for different area and you just need to call them according to your
requirement.

Creating PHP Function


 It’s very easy to create your own PHP function. Suppose you want to create a PHP function which
will simply write a simple message on your browser when you will call it. Following example creates
a function called writeMessage() and then calls it just after creating it.

Note that while creating a function its name should start with keyword function and all the PHP code should
be put inside { and } braces as shown in the following example below.

<html>

<head>
<title>Writing PHP Function</title>
</head>

<body>

<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice
person, Have a nice time!";
}

/* Calling a PHP Function */


writeMessage();
?>

</body>
</html>

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


PHP Functions with Parameters
 PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters your like. These parameters work like variables inside your function. Following
example takes two integer parameters and add them together and then print them.

<html>

<head>
<title>Writing PHP Function with
Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>

Dynamic Function Calls


 It is possible to assign function names as strings to variables and then treat these variables exactly
as you would the function name itself. Following example depicts this behavior.

<html>

<head>
<title>Dynamic Function Calls</title>
</head>

<body>

<?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>

</body>
</html>

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


PHP - Form Introduction

Dynamic Websites
 The Websites provide the functionalities that can use to store, update, retrieve, and delete the data
in a database.

What is the Form?


 A Document that containing black fields, that the user can fill the data or user can select the data.
Casually the data will store in the data base

Below example shows the form with some specific actions by using post method.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


Note: You can copy and use this code to try on how to perform the form function in PHP.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


PHP - Validation Example
Required field will check whether the field is filled or not in the proper way. Most of cases we will use the
* symbol for required field.

What is Validation?
 Validation means check the input submitted by the user. There are two types of validation are
available in PHP. They are as follows:

 Client-Side Validation − Validation is performed on the client machine web browsers.

 Server-Side Validation − After submitted by data, the data has sent to a server and perform
validation checks in server machine.

Some of Validation rules for field


Field Validation Rules

Name Should required letters and white-spaces

Email Should required @ and .

Website Should required a valid URL

Radio Must be selectable at least once

Check Box Must be checkable at least once

Drop Down menu Must be selectable at least once

Valid URL
Below code shows validation of URL
$website = input($_POST["site"]);

if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

Above syntax will verify whether a given URL is valid or not. It should allow some keywords as https, ftp,
www, a-z, 0-9,..etc..

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


Valid Email
Below code shows validation of Email address
$email = input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid format and please re-enter valid email";
}

Above syntax will verify whether given Email address is well-formed or not. If it is not, it will show an error
message.

Example below shows the form with required field validation:

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


<p><span class = "error">* required field.</span></p>

<form method = "post" action = "<?php


echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name">
<span class = "error">* <?php echo $nameErr;?></span>
</td>
</tr>

<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>

<tr>
<td>Time:</td>
<td> <input type = "text" name = "website">
<span class = "error"><?php echo $websiteErr;?></span>
</td>
</tr>

<tr>
<td>Classes:</td>
<td> <textarea name = "comment" rows = "5" cols =
"40"></textarea></td>
</tr>

<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender" value =
"female">Female
<input type = "radio" name = "gender" value =
"male">Male
<span class = "error">* <?php echo $genderErr;?></span>
</td>
</tr>

<td>
<input type = "submit" name = "submit" value = "Submit">
</td>

</table>

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


</form>

<?php
echo "<h2>Your given values are as:</h2>";
echo $name;
echo "<br>";

echo $email;
echo "<br>";

echo $website;
echo "<br>";

echo $comment;
echo "<br>";

echo $gender;
?>

</body>
</html>

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


PHP - Complete Form
This page explains about time real-time form with actions. Below example will take input fields as text,
radio button, drop down menu, and checked box.

<html>

<head>
<style>
.error {color: #FF0000;}
</style>
</head>

<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $class = $course = $subject = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);

// check if e-mail address is well-formed


if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["course"])) {
$course = "";
}else {
$course = test_input($_POST["course"]);
}

if (empty($_POST["class"])) {
$class = "";
}else {
$class = test_input($_POST["class"]);
}

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
}else {
$gender = test_input($_POST["gender"]);
}

if (empty($_POST["subject"])) {
$subjectErr = "You must select 1 or more";
}else {
$subject = $_POST["subject"];
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>Absolute classes registration</h2>

<p><span class = "error">* required field.</span></p>

<form method = "POST" action = "<?php echo


htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td>Name:</td>
<td><input type = "text" name = "name">
<span class = "error">* <?php echo $nameErr;?></span>
</td>
</tr>

<tr>
<td>E-mail: </td>
<td><input type = "text" name = "email">
<span class = "error">* <?php echo $emailErr;?></span>
</td>
</tr>

<tr>
<td>Time:</td>
<td> <input type = "text" name = "course">
<span class = "error"><?php echo $websiteErr;?></span>
</td>
</tr>

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


<tr>
<td>Classes:</td>
<td> <textarea name = "class" rows = "5" cols =
"40"></textarea></td>
</tr>

<tr>
<td>Gender:</td>
<td>
<input type = "radio" name = "gender" value =
"female">Female
<input type = "radio" name = "gender" value =
"male">Male
<span class = "error">* <?php echo $genderErr;?></span>
</td>
</tr>

<tr>
<td>Select:</td>
<td>
<select name = "subject[]" size = "4" multiple>
<option value = "Android">Android</option>
<option value = "Java">Java</option>
<option value = "C#">C#</option>
<option value = "Data Base">Data Base</option>
<option value = "Hadoop">Hadoop</option>
<option value = "VB script">VB script</option>
</select>
</td>
</tr>

<tr>
<td>Agree</td>
<td><input type = "checkbox" name = "checked" value =
"1"></td>
<?php if(!isset($_POST['checked'])){ ?>
<span class = "error">* <?php echo "You must agree to
terms";?></span>
<?php } ?>
</tr>

<tr>
<td>
<input type = "submit" name = "submit" value =
"Submit">
</td>
</tr>

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


</table>
</form>

<?php
echo "<h2>Your given values are as :</h2>";
echo ("<p>Your name is $name</p>");
echo ("<p> your email address is $email</p>");
echo ("<p>Your class time at $course</p>");
echo ("<p>your class info $class </p>");
echo ("<p>your gender is $gender</p>");

for($i = 0; $i < count($subject); $i++) {


echo($subject[$i] . " ");
}
?>

</body>
</html>

Laboratory Activity (for next week)


Continue to work on your prefer website activity by applying the skills that you’ve learn so far in
this module.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022


WEBSITE DESIGN RUBRIC
Criteria 5 4 3 2 Score
Contents of page Information is correct; three Information is mostly correct; Information is somewhat Information is ambiguous;
pages; hyperlinks to a menu and three pages; hyperlinks to a vague; one or two pages; link only one page; No links; text
additional pages; text is precisely menu and additional pages; s are missing; text somewhat is unorganized;
organized on page; grade level grade level appropriate; organized; email address inappropriate for grade
appropriate, google email email address is present present level; email address missing
address provided on page
Layout and Design The web site has an The web site has an attractive The web site has a usable The web site has a cluttered
exceptionally attractive and and usable layout. It is easy to layout, but may appear busy look and is confusing. It is
usable layout. It is easy to locate locate all important elements. or boring. It is easy to locate often difficult to locate
all important elements. White most of the important important elements.
space, graphic elements and/or elements.
alignment are used effectively to
organize material.
Graphics Graphics are related to the Graphics are related to the Graphics are related Graphics seem randomly
theme/purpose of the site, are theme/purpose of the site, are to the theme/purpose chosen, are of low quality,
thoughtfully cropped, are of high of good quality and enhance of the site, and are of OR distract the reader.
quality and enhance reader reader interest or good quality.
interest or understanding. understanding.
Navigation Links for navigation are clearly Links for navigation are clearly Links for navigation are the Some links do not take the
labeled, consistently placed, labeled, allow the reader to reader where expected, but reader to the sites/pages
allow the reader to easily move easily move from page to page some needed links seem to described. A user typically
from a page to related pages and and internal links take the reader be missing. A user feels lost.
take reader where he expects to where he expects to go. A user sometimes gets lost.
go. A user does not become lost. rarely becomes lost.
Work Ethic Student always uses classroom Student usually uses classroom Student usually uses Student does not use
project time well. Conversations project time well. Most classroom project time well, classroom project time well
are primarily focused on the conversations are focused on the but occasionally distracts OR typically is disruptive to
project and things needed to get project and things needed to get others from their work. the work of others.
the work done and are held in a the work done and are held in a
manner that typically does not manner that typically does not
disrupt others. disrupt others.
Content Accuracy All information provided by the Almost all the information Almost all of the information There are several
student on the Web site is provided by the student on the provided by the student on inaccuracies in the content
accurate and all the Web site is accurate and all the Web site is accurate and provided by the students
requirements of the assignment requirements of the assignment almost all of the OR many of the
have been met have been met. requirements have been requirements were not met.
met.
Learning of Material The student has an exceptional The student has a good The student has a fair Student did not appear to
understanding of the material understanding of the material understanding of the learn much from this
included in the site and where to included in the site. Can easily material included in the site. project. Cannot answer
find additional information. Can answer questions about the Can easily answer most most questions about the
easily answer questions about content and procedures used to questions about the content content and the procedures
the content and procedures used make the web site. and procedures used to used to make the web site.
to make the web site make the web site.

ITEC 50 WEB SYSTEMS TECHNOLOGIES K. Guilaran SECOND SEMESTER AY 2021-2022

You might also like