· 6 years ago · May 27, 2019, 06:58 AM
1 SULTANATE OF OMAN
2 MINISTRY OF MANPOWER
3 COLLEGES OF TECHNOLOGY
4COURSE
5MATERIAL
6WEB APPLICATION DEVELOPMENT I
7ITDB201
8DEPARTMENT OF IT
92 [Web Application Development I-ITDB201]
10Table of Contents
11Course Overview …………………………………………………… 7
12a. Course Description ………………………………………………………………… 7
13b. Course Objectives ………………………………………………………………….. 7
14c. Course Outcomes …………………………………………………………………... 7
15d. Timeframe ………………………………………………………………………….. 7
16e. Resources ………….……………………………………………………………….. 8
17f. Margin Icons……………………………………………………………………….. 8
18CHAPTER 1– Web Application Basics
19OBJECTIVES……………………………………………………………………………… 10
20Web Application?.................................................................................................................. 10
21Internet Terminologies...........................................................................................................… 10
22Request and response model..................................................................................................… 11
23Web Servers…………………………………………………………………………………. 12
24Web Application Architectures................................................................................................ 12
25Dynamic and static web sites................................................................................................... 15
26Client-side and server-side scripting languages....................................................................... 16
27Emerging trends in web applications………………………………………………………… 17
28CHAPTER SUMMARY …………………………………………………………………… 17
29ASSIGNMENTS ………………………………………………………………………….… 18
30Lab Exercises/ Case Studies/Problem Solving …………………………………………… 19
31REFERENCES………………………………………………………………………………. 21
32CHAPTER 2 – Setting up the Development Environment
33OBJECTIVES………………………………………………………………………………. 22
34Development vs Production Environment…………………………………………………… 22
35Web Development Environment Components......................................................................... 23
36What is a Software Stack?........................................................................................................ 25
37Setting Up Local Web Server................................................................................................... 27
38Methods of Testing the Installation.......................................................................................... 28
39Apache Web Server Configuration………………………………………………………….. 30
40CHAPTER SUMMARY …………………………………………………………………… 31
41ASSIGNMENTS ………………………………………………………………………….… 32
42Lab Exercises/ Case Studies/Problem Solving …………………………………………… 32
43REFERENCES……………………………………………………………………………… 34
443 [Web Application Development I-ITDB201]
45CHAPTER 3 – Front-End Web Development
46OBJECTIVES…………………………………………………………………………….. 35
47Principles of Effective Web Design Principles...................................................................... 35
48Responsive Web Design………………................................................................................. 39
49Bootstrap………………………………................................................................................. 40
50CHAPTER SUMMARY ………………………………………………………………….. 61
51ASSIGNMENTS ………………………………………………………………………….. 61
52Lab Exercises/ Case Studies/Problem Solving …………………………………………. 63
53REFERENCES……………………………………………………………………………. 65
54CHAPTER 4 – PHP BASICS
55OBJECTIVES………………………………………………………………………………. 66
56PHP for Web Application Development…………………………………………………….. 66
57PHP Basics…………………………………………………………………………………… 67
58PHP Functions……………………………………………………………………………….. 77
59Arrays………………………………………………………………………………………... 81
60CHAPTER SUMMARY …………………………………………………………………… 86
61ASSIGNMENTS ………………………………………………………………………….… 86
62Lab Exercises/ Case Studies/Problem Solving …………………………………………… 87
63REFERENCES……………………………………………………………………………… 91
64CHAPTER 5– FILES AND DIRECTORIES
65OBJECTIVES………………………………………………………………………………. 92
66Working with Files……………….…………………………………………………………... 92
67Working with directories……………………………………………………………………... 94
68CHAPTER SUMMARY …………………………………………………………………… 96
69ASSIGNMENTS ………………………………………………………………………….… 96
70Lab Exercises/ Case Studies/Problem Solving …………………………………………… 97
71REFERENCES……………………………………………………………………………… 98
724 [Web Application Development I-ITDB201]
73CHAPTER 6 – FORMS AND DATA VALIDATIONS
74OBJECTIVES……………………………………………………………………………… 99
75PHP Forms……………………............................................................................................... 99
76HTTP Methods Retrieving Submitted Data............................................................................. 102
77HTML5 Validation................................................................................................................... 103
78JavaScript Validation................................................................................................................ 106
79CHAPTER SUMMARY …………………………………………………………………… 108
80ASSIGNMENTS ………………………………………………………………………….… 108
81Lab Exercises/ Case Studies/Problem Solving …………………………………………… 109
82REFERENCES……………………………………………………………………………… 110
83CHAPTER 7 – INTRODUCTION TO MySQL
84OBJECTIVES………………………………………………………………………………. 111
85MySQL Overview..................................................................................................................... 111
86Advantages of MySQL.............................................................................................................. 111
87Communicating with MySQL Server........................................................................................ 114
88Building SQL Queries................................................................................................................ 114
89Creating a new database............................................................................................................. 115
90Creating a table........................................................................................................................... 115
91Set Field Names.......................................................................................................................... 115
92Table Operations......................................................................................................................... 116
93Exporting and Importing MySQL database................................................................................ 117
94Dropping a database…………………………………………………………………………… 118
95CHAPTER SUMMARY …………………………………………………………………… 119
96ASSIGNMENTS ………………………………………………………………………….… 119
97Lab Exercises/ Case Studies/Problem Solving …………………………………………… 120
98REFERENCES……………………………………………………………………………… 121
99CHAPTER 8 – DATABASE MANIPULATION using PHP
100OBJECTIVES………………………………………………………………………………. 122
101Overview…………………………………………………………………………………….. 122
102Choosing an API to Connect to MySQL…………………………………………………….. 122
103Connecting to MySQL DBMS................................................................................................. 123
104Example: Student Information System..................................................................................... 123
105Executing Queries…………………………………………………………………………… 127
106Adding Records……………………………………………………………………………… 127
107Redirecting to Another Page………………………………………………………………….. 131
108Retrieving Records …………..……………………………………………………………….. 131
109Fetching Rows…………..…………………………………………………………………….. 131
1105 [Web Application Development I-ITDB201]
111Retrieving and Displaying Records in Bootstrap Tables……………………………………… 131
112Deleting Records………………………………………………………………………………. 133
113Updating Records........................................................................................................................ 134
114Counting Records........................................................................................................................ 137
115CHAPTER SUMMARY …………………………………………………………………… 139
116ASSIGNMENTS ………………………………………………………………………….… 139
117Lab Exercises/ Case Studies/Problem Solving …………………………………………… 140
118REFERENCES……………………………………………………………………………… 141
119CHAPTER 9 – Session Management
120OBJECTIVES………………………………………………………………………………. 142
121Overview.................................................................................................................................... 142
122Start a PHP Session.................................................................................................................... 143
123Accessing PHP Session Variables.............................................................................................. 145
124Retrieving the Session ID and Destroying PHP......................................................................... 146
125CHAPTER SUMMARY …………………………………………………………………… 147
126ASSIGNMENTS ………………………………………………………………………….… 147
127Lab Exercises/ Case Studies/Problem Solving …………………………………………… 148
128REFERENCES……………………………………………………………………………… 148
129CHAPTER 10 – Web Application Security
130OBJECTIVES……………………………………………………………………………… 150
131Overview……………………………...................................................................................... 150
132The Foundations of Security…………………………………………………………………. 150
133Threats, Vulnerabilities and Attacks......................................................................................... 151
134Proper Error Handling............................................................................................................... 159
135CHAPTER SUMMARY …………………………………………………………………… 160
136ASSIGNMENTS ………………………………………………………………………….… 160
137Lab Exercises/ Case Studies/Problem Solving …………………………………………… 161
138REFERENCES……………………………………………………………………………… 162
1396 [Web Application Development I-ITDB201]
140CHAPTER 11 – Testing and Application Deployment
141OBJECTIVES……………………………………………………………………………… 164
142Web Application Testing....................................................................................................... 164
143Web Hosting……………........................................................................................................ 169
144CHAPTER SUMMARY …………………………………………………………………… 171
145ASSIGNMENTS ………………………………………………………………………….… 171
146Lab Exercises/ Case Studies/Problem Solving …………………………………………… 172
147REFERENCES……………………………………………………………………………… 173
148APPENDIX
1497 [Web Application Development I-ITDB201]
150Course Overview
151a. Course Description:
152To provide the student with skills needed to develop functional and dynamic database-driven web
153sites.
154b. Course Objectives
155Upon completion of the course, the students should be able to:
1561. Develop a database-driven web application using related and latest
157technologies.
1582. Appreciate the use of new emerging web application tools that are available in
159the market.
160c. Course Outcomes:
161Upon completion of the course, the students should be able to:
1621. Describe the features, the development environment, and the capabilities
163of dynamic web application tools such as PHP and MySQL.
1642. Describe the function of the web server and web browser (client) with
165examples and the way they communicate with each other using HTTP and
166HTTPS.
1673. Compare between client-side scripting languages and server-side scripting
168languages with examples.
1694. Compare between dynamic and static websites in terms of the
170requirements to build the sites and the methods where data can be
171physically stored.
1725. Write server-side scripts of web applications that include constants,
173variables, data types, functions, control structures, arrays and the relevant
1748 [Web Application Development I-ITDB201]
175d. Time Frame :
176How long?
177The expected duration of this course is from _____ weeks/Hours
178Formal study time is required is ______ weeks/Hours
179Self-study time is expected/recommended is ______ weeks/Hours
180e. Resources:
181[Hardware & software Requirements for the concerned course]
182statements to send data to the client-side in different HTML formats.
1836. Work with forms, files, and directories.
1847. Handle and validate the data sent by the client through HTTP post and get
185methods.
1868. Create web page templates such as header and footer.
1879. Create database connectivity between the server-side script and a database
188server to execute SQL commands such as select, insert, update,
189REPLACE, and delete data.
19010. Apply security to web pages using session management techniques such
191as cookies and user sessions.
19211. Develop web applications using the latest web application tools.
1939 [Web Application Development I-ITDB201]
194f. Margin Icons:
195Activity Assessment Assignment Case study Objectives
196Discussion Group activity Help Note it! Basic
197Competence
198Outcomes Reading Reflection Study skills Answers to
199Assessments
200Summary Terminology Time Tip
201ComputerBased
202Learning Audio Video Feedback
20310 [Web Application Development I-ITDB201]
204Chapter 1: Web Application Basics
205 Objectives
206At the end of this module, the students will be able to:
207ï‚· Elaborate the basic concept of a web application.
208ï‚· Define and explain the common Internet terminologies.
209ï‚· Compare and contrast the different types of web application architectures.
210ï‚· Classify web development tools as either a client-side or server side.
211ï‚· Enumerate the characteristics of dynamic website and static website.
2121.1. Web Application
213In computing, a web application or web app is a client–server software application in
214which the client (or user interface) runs in a web browser. In another word, A Web
215application (Web app) is an application program that is stored on a remote server and
216delivered over the Internet through a browser interface. Simply put, Web Applications
217are dynamic web sites combined with server side programming which provide
218functionalities such as interacting with users, connecting to back-end databases, and
219generating results to browsers.
220Some examples of web application
221Examples of Web Applications are Online Banking, Social Networking, Online
222Reservations, eCommerce / Shopping Cart Applications, Interactive Games, Online
223Training, Online Polls, Blogs, Online Forums, Content Management Systems, etc..
2241.2. Internet Terminologies
225The Internet is a worldwide network of computers that are connected (networked)
226and are using the communication method called TCP/IP. The Internet was named
227ARPANET in 1969 by the Advanced Research Projects Agency of the U.S. Department
228of Defense with just four computers connected together.
229a. World Wide Web
230Also called web or www, it is a collection of information, resources, pictures,
231and sounds, multimedia on the internet that are linked and connected together. Using
232a software product such as Netscape makes accessing and linking to web pages
23311 [Web Application Development I-ITDB201]
234containing information, easy. The World Wide Web was invented by Tim Bernes-lee
235in the CERN Laboratory in March 1989.
236b. Host
237 A computer that is used to transfer data on the Internet.
238c. Domain name
239To store and make web pages available and ready for inquiries, or a computer
240that has a consistent connection to the Internet. e.g. www.google.com.
241d. DNS
242DNS (Domain Name System) is a large database of domain names and their
243correspondent Internet (IP Addresses) for example: www.widget.com corresponds to
244its unique number 207.168.6.12.
2451.3. Request and response model
246Request–response, or request–reply, is one of the basic methods computers use to
247communicate with each other, in which the first computer sends a request for some data
248and the second computer responds to the request. Usually, there is a series of such
249interchanges until the complete message is sent; browsing a web page is an example of
250request–response communication. Request–response can be seen as a telephone call, in
251which someone is called and they answer the call.
252Request–response is a message exchange pattern in which a requestor sends a
253request message to a replier system which receives and processes the request, ultimately
254returning a message in response. This is a simple, but powerful messaging pattern which
255allows two applications to have a two-way conversation with one another over a channel.
256This pattern is especially common in client–server architectures.
257a. HTTP
258The Hypertext Transfer Protocol (HTTP) is an application protocol for
259distributed, collaborative, hypermedia information systems. HTTP is the foundation
260of data communication for the World Wide Web. Hypertext is structured text that
261uses logical links (hyperlinks) between nodes containing text.
262b. HTTP methods
263The primary or most-commonly-used HTTP verbs (or methods, as they are
264properly called) are POST, GET, PUT, and DELETE. These correspond to create,
265read, update, and delete (or CRUD) operations, respectively. There are a number of
266other verbs, too, but are utilized less frequently.
26712 [Web Application Development I-ITDB201]
2681.4. Web Servers
269Web servers are computers that deliver (serves up) Web pages. Every Web server
270has an IP address and possibly a domain name. For example, if you enter the URL
271http://www.webopedia.com/index.html in your browser, this sends a request to the Web
272server whose domain name is webopedia.com. The server then fetches the page named
273index.html and sends it to your browser.
274The process is an example of the client/server model. All computers that host
275Web sites must have Web server programs. Leading Web servers include:
276a. Apache (the most widely-installed Web server)
277b. Microsoft's Internet Information Server (IIS)
278c. nginx (pronounced engine X) from NGNIX
279d. Novell's NetWare server
280e. Google Web Server (GWS)
281f. IBM's family of Domino servers.
282Any computer can be turned into a Web server by installing server software and
283connecting the machine to the Internet. There are many Web server software applications,
284including public domain software and commercial packages.
2851.5. Web Application Architectures
286A Web application is an application that can be accessed by the users through
287a Web browser or a specialized user agent. The browser creates HTTP requests for
288specific URLs that map to resources on a Web server. The server renders and returns
289HTML pages to the client, which the browser can display. The core of a Web
290application is its server-side logic. The application can contain several distinct layers.
291The typical example is a three-layered architecture comprised of presentation, business,
292and data layers. Figure 1.1 illustrates a typical Web application architecture with
293common components grouped by different areas of concern.
29413 [Web Application Development I-ITDB201]
295Figure 1.1: The typical structure of a Web application
296The figure above shows the typical structure of a web application. The
297presentation layer usually includes UI and presentation logic components; the business
298layer usually includes business logic, business workflow and business entities
299components, and optionally a façade; and the data layer usually includes data access and
300service agent components.
301Tiers represent the physical separation of the presentation, business, services, and
302data functionality of your design across separate computers and systems. Common tiered
303design patterns are two-tier, three-tier, and n-tier. The following sections explore each of
304these scenarios.
305a. 2-tier architecture
306The two-tier pattern represents a basic structure with two main
307components, a client and a server. In this scenario, the client and server may exist
308on the same machine, or may be located on two different machines. Figure 6
309illustrates a common Web application scenario where the client interacts with a
310Web server located in the client tier. This tier contains the presentation layer logic
31114 [Web Application Development I-ITDB201]
312and any required business layer logic. The Web application communicates with a
313separate machine that hosts the database tier, which contains the data layer logic.
314Figure 1.2: The two-tier deployment pattern
315b. 3-tier architecture
316In a three-tier design, the client interacts with application software deployed
317on a separate server, and the application server interacts with a database that is
318also located on a separate server. This is a very common pattern for most Web
319applications and Web services. Figure 7 illustrates the three-tier deployment
320pattern.
321Figure 1.3: The three-tier deployment pattern
322c. N-tier architecture
323In this scenario, the Web server (which contains the presentation layer logic)
324is physically separated from the application server that implements the business
325logic. This usually occurs for security reasons, where the Web server is deployed
326within a perimeter network and accesses the application server located on a
327different subnet through a firewall. It is also common to implement a firewall
328between the client and the Web tier. Figure 8 illustrates the n-tier deployment
329pattern.
33015 [Web Application Development I-ITDB201]
331Figure 1.4: The n-tier deployment pattern
3321.6. Dynamic and static web sites
333A dynamic website is a website that not only uses HTML and CSS, but includes
334website scripting as well. There are two main reasons why you‘d want to use website
335scripting on your site:
3361. you want an interactive web app that people can use, not just read
3372. you want to be able to share HTML code between your pages.
338A static website is the simplest kind of website you can build. Static websites are
339written in HTML and CSS only, with no scripting. The only form of interactivity on a
340static website is hyperlinks.
341If you intend your website to be a small one (3 pages or less), then a static website
342might be the easiest way to go. But if you want to share elements between pages (such as
343logos or menus), you‘ll have to duplicate the HTML on each page.
344Static websites are easier to make than dynamic websites, because they require less
345coding and technical knowledge. However, fully static websites are very uncommon
346these days, since there is so much that scripting can do.
347a. Advantages of static web sites
348ï‚· Quick to develop
349ï‚· Cheap to develop
350ï‚· Cheap to host
351b. Disadvantages of static web sites
352ï‚· Requires web development expertise to update site
353ï‚· Site not as useful for the user
354ï‚· Content can get stagnant
35516 [Web Application Development I-ITDB201]
356c. Advantages of dynamic web sites
357ï‚· Much more functional website
358ï‚· Much easier to update
359ï‚· New content brings people back to the site and helps in the search engines
360ï‚· Can work as a system to allow staff or users to collaborate
361d. Disadvantages of dynamic web sites
362ï‚· Slower / more expensive to develop
363ï‚· Hosting costs a little more
3641.7. Client-side and server-side scripting languages
365There are two main categories of coding, scripting and programming for creating
366Web Applications:
367a. Client Side Scripting / Coding - Client Side Scripting is the type of code that is
368executed or interpreted by browsers.
369Client Side Scripting is generally viewable by any visitor to a site (from the view
370menu click on "View Source" to view the source code).
371Below are some common Client Side Scripting technologies:
372ï‚· HTML (HyperText Markup Language)
373ï‚· CSS (Cascading Style Sheets)
374ï‚· JavaScript
375ï‚· Ajax (Asynchronous JavaScript and XML)
376ï‚· jQuery (JavaScript Framework Library - commonly used in Ajax development)
377ï‚· MooTools (JavaScript Framework Library - commonly used in Ajax
378development)
379ï‚· Dojo Toolkit (JavaScript Framework Library - commonly used in Ajax
380development)
381b. Server Side Scripting / Coding - Server Side Scripting is the type of code that is
382executed or interpreted by the web server.
383Server Side Scripting is not viewable or accessible by any visitor or general public.
384Below are the common Server Side Scripting technologies:
385ï‚· PHP (very common Server Side Scripting language - Linux / Unix based Open
386Source - free redistribution, usually combines with MySQL database)
387ï‚· Zend Framework (PHP's Object Oriented Web Application Framework)
388ï‚· ASP (Microsoft Web Server (IIS) Scripting language)
38917 [Web Application Development I-ITDB201]
390ï‚· ASP.NET (Microsoft's Web Application Framework - successor of ASP)
391ï‚· ColdFusion (Adobe's Web Application Framework)
392ï‚· Ruby on Rails (Ruby programming's Web Application Framework - free
393redistribution)
394ï‚· Perl (general purpose high-level programming language and Server Side
395Scripting Language - free redistribution - lost its popularity to PHP)
396ï‚· Python (general purpose high-level programming language and Server Side
397Scripting language - free redistribution)
3981.8. Emerging trends in web applications
399Recent advancement in technology and new development tools for web
400developers.
401a. Motion UI
402b. New Challenges for Responsive Design
403c. The rise of Node.js
404d. Foundation for Apps
405e. Web UI components
406f. Web API
407g. New JavaScript features
408h. The rise of Instagram
409i. The Internet of Things (IoT)
410 Chapter Summary:
411Web applications have become part of our daily lives in various aspects such as
412education, business and social media. It has greatly evolved over the years with respect
413to technologies used to develop such applications. Web applications has become a
414fundamental approach of businesses in leveraging their online presence and be able reach
415wide range of market. However, from a technical point of view, a web application
416requires diverse knowledge on web application architectures, development tools, security
417protocols and most importantly keeping abreast of the ever changing requirements of the
418customers and stakeholders.
41918 [Web Application Development I-ITDB201]
420Assignments:
421a. The table below shows some of the major classifications of web applications classified
422according to its purpose and usability. In the second column, give two specific examples
423of websites that falls on the corresponding web application type.
424Web Application Type Website
425Online Banking
426Example 1: https://www.bankmuscatonline.com/
427Social Networking
428Online Reservations
429Shopping Cart Applications
430Interactive Games
431Online Training
432Blogs
433Online Forums
434Content Management Systems
435b. Give an example of a URL. List the three main components of a URL, stating how their
436boundaries are denoted and illustrating each one from your example.
437_______________________________________________________________________
438_______________________________________________________________________
439_______________________________________________________________________
440_______________________________________________________________________
441_______________________________________________________________________
44219 [Web Application Development I-ITDB201]
443c. What is the difference between a web application and a desktop application? Which do
444you think of the two has more impact in terms of customer satisfaction or service?
445Explain your answer.
446_______________________________________________________________________
447_______________________________________________________________________
448_______________________________________________________________________
449_______________________________________________________________________
450_______________________________________________________________________
451Laboratory Exercises:
452Learning Outcome: At the end of this activity, the students should be able to:
453a. Illustrate how a client-server model works.
454b. Identify the different components in a client-server model.
4551. Research on Client-server model.
456Guided-Discovery Learning / Student Research
457Category: Critical Thinking, Problem-based Learning
458Suggested
459duration:
46030-90 minutes (more if used as an out of class activity as well)
461Intent: Let the students learn about ―Client-Server Model‖ through video
462presentations.
463Implementation: 1. This activity may be done individually or in a group depending on your
464teacher‘s instruction.
4652. Research from the Internet (possibly from https://www.youtube.com)
466videos relating to ―Client-Server Model‖. Your teacher may give you an
467example video or you may research yourself. You may as well visit this
468link: https://www.youtube.com/watch?v=L5BlpPU_muY&t=4s
4693. Answer the guide questions below based from the video.
4704. Present your answers to the rest of the class.
47120 [Web Application Development I-ITDB201]
472Activity Guide Questions:
473a. What are the respective roles of the client and server in the client-server model?
474_______________________________________________________________________
475_______________________________________________________________________
476_______________________________________________________________________
477_______________________________________________________________________
478_______________________________________________________________________
479_______________________________________________________________________
480_______________________________________________________________________
481_______________________________________________________________________
482_______________________________________________________________________
483_______________________________________________________________________
484b. What are the differences between a client-server model and a peer-to-peer model?
485Give examples of a peer-to-peer model.
486_______________________________________________________________________
487_______________________________________________________________________
488_______________________________________________________________________
489_______________________________________________________________________
490_______________________________________________________________________
491_______________________________________________________________________
492_______________________________________________________________________
493_______________________________________________________________________
494_______________________________________________________________________
495_______________________________________________________________________
49621 [Web Application Development I-ITDB201]
497c. The diagram below shows a client-server model. Write the correct label for each
498component.
499References:
500[1]T. Peham, "12 web development trends you must know about in 2016", Usersnap Blog,
5012016. [Online]. Available: http://usersnap.com/blog/web-development-trends-2016/.
502[Accessed: 19- Nov- 2016].
503[2]"Chapter 21: Designing Web Applications", Msdn.microsoft.com, 2017. [Online].
504Available: https://msdn.microsoft.com/en-us/library/ee658099.aspx. [Accessed: 03- Mar2017].
505[3]"What is a Web Server? Webopedia Definition", Webopedia.com, 2017. [Online].
506Available: http://www.webopedia.com/TERM/W/Web_server.html. [Accessed: 03- Mar2017].
507[4]"What is Web server? - Definition from WhatIs.com", WhatIs.com, 2017. [Online].
508Available: http://whatis.techtarget.com/definition/Web-server. [Accessed: 03- Mar- 2017].
509[5]"Application Architecture Guide - Chapter 9 - Layers and Tiers - Guidance Share",
510Guidanceshare.com, 2017. [Online]. Available:
511http://www.guidanceshare.com/wiki/Application_Architecture_Guide_-_Chapter_9_-
512_Layers_and_Tiers#Layers. [Accessed: 03- Mar- 2017].
5131.
5142.
5153.
5164.
5177.
5185. 6.
51922 [Web Application Development I-ITDB201]
520Chapter 2: Web Development Environment
521 Objectives
522At the end of this module, the students will be able to:
523ï‚· Distinguish development versus production environment.
524ï‚· Identify the different components that comprise the web development
525environment.
526ï‚· Enumerate the various software stacks available in web environment.
527ï‚· Install and configure a local web server.
528Overview
529In software deployment, an environment or tier is a computer system in which a
530computer program or software component is deployed and executed. In simple cases,
531such as developing and immediately executing a program on the same machine, there
532may be a single environment, but in industrial use the development environment (where
533changes are originally made) and production environment (what end users use) are
534separated, often with several stages in between, in order to allow phased deployment
535(rollout), testing, and rollback in case of problems.
5362.1. Development vs Production Environment
537The development environment (dev) is the environment in which changes to
538software are developed, most simply an individual developer's workstation. This differs
539from the ultimate target environment in various ways – the target may not be a desktop
540computer (it may be a smartphone, embedded system, headless machine in a data center,
541etc.), and even if otherwise similar, the developer's environment will include
542development tools like a compiler, integrated development environment, different or
543additional versions of libraries and support software, etc., which are not present in a
544user's environment.
545The production environment (prod) is also known as live, particularly for servers, as
546it is the environment that users directly interact with.
54723 [Web Application Development I-ITDB201]
5482.2. Web Development Environment Components
549The following are needed in developing a web application.
5502.2.1. Web Server - A Web server is a program that uses HTTP (Hypertext
551Transfer Protocol) to serve the files that form Web pages to users, in response to
552their requests, which are forwarded by their computers' HTTP clients.
553Examples of web servers:
554a. Apache HTTP Server
555b. Microsoft Internet Information Services (IIS)
5562.2.2. Code Editors - A source code editor is a text editor program designed
557specifically for editing source code of computer programs by programmers. It
558may be a standalone application or it may be built into an integrated
559development environment (IDE) or web browser. There are a lot of code
560editors available on the Internet for free or for a low price.
561Examples of Code Editors:
562a. Notepad++
563b. Sublime Text
5642.2.3. Integrated Development Environment (IDE) - An integrated development
565environment (IDE) is a software application that provides comprehensive
566facilities to computer programmers for software development. An IDE normally
567consists of a source code editor, build automation tools and a debugger.
568Examples of IDE:
569a. Aptana Studio PHP Editor(Free)
570b. NetBeans IDE(Free)
571c. Eclipse PDT
572d. Zend Studio
5732.2.4. Scripting Language - In developing a web application, both client-side and
574server-side scripting languages are required.
575Examples of Client-Side Programming Languages and Frameworks
576a. HTML and CSS
577b. AngularJS: An incredibly robust JavaScript framework for dataheavy
578sites
579c. JQuery, jQuery Mobile: A fast, small, JS object library that
580streamlines how JavaScript behaves across different browsers
58124 [Web Application Development I-ITDB201]
582d. Node.js: A server-side platform that uses JavaScript, and is
583changing the way real-time applications can communicate with the
584server for faster response times and a more seamless user
585experience. It works with another JavaScript framework, Express.js,
586to build server-side Web applications.
587e. Bootstrap: A mobile-first framework that uses HTML, CSS, and
588JavaScript to facilitate rapid responsive app development
589f. React, for user interface design
590g. Express.js, Backbone.js, Ember.js, MeteorJS, and more
591h. TypeScript: A compile-to-JavaScript language that is a superset of
592JavaScript, created by Microsoft
593i. AJAX (JavaScript + XML)—a technology that allows specific parts
594of a site to be updated without a full-page refresh by asynchronously
595connecting to the database and pulling JSON– or XML-based
596chunks of data.
597j. VBScript & JScript are Microsoft‘s front-end scripts that run on the
598ASP.NET framework. JScript is Microsoft‘s reverse-engineered
599version of JavaScript.
600k. ActionScript, which creates animated interactive web applications
601for Adobe Flash Play
602l. Java (as ―applets‖) snippets of back-end code that run independently
603with a run-time environment in the browser
604Server-Side Programming Languages
605ï‚· PHP, Ruby on Rails, ASP, Python and many others
606b. PHP Frameworks
607Building software applications can be a complex, time consuming process,
608however utilizing a framework can help you develop projects faster (by reusing
609generic components and modules), and work better (building on one unified
610structural foundation). Using a framework also facilitates scalability and long-term
611maintenance by complying with development standards, keeping your code organized
612and allowing your application to evolve and grow over time.
613By removing the time and effort required to build generic components, you can
614dedicate more time to specific tasks and functionality, and focus on sustainable, highquality
615code.
61625 [Web Application Development I-ITDB201]
617Examples of PHP Frameworks:
618ï‚· Laravel
619ï‚· CodeIgniter
620ï‚· CakePHP
621ï‚· Symphony
622ï‚· Zend Framework
623c. Database Management System (DBMS) - A database management system
624(DBMS) is a computer software application that interacts with the user, other
625applications, and the database itself to capture and analyze data.
626Examples of DBMS:
627a. MySQL
628b. Oracle
629c. SQL Server,
630d. Microsoft Access
6312.3. What is a Software Stack?
632―Stacks‖ are bundles of software that comprise your site‘s back end—everything
633from the operating system and web servers to APIs and programming frameworks.
634Each component provides a layer for their compatibility, and bundling them makes
635them easier to download and deploy all at once.
636a. Parts of a Software Stack
637Figure 2.1: Software Stack
63826 [Web Application Development I-ITDB201]
639Applications have four tiers, three of which are on the server-side. This graphic explains
640the inner workings of a stack: the client is where it all starts and ends.
641 The client tier—this is the only component in the browser
642 The web tier—the web server, or HTTP server
643 The business tier—the application server, including the development
644platform, frameworks, and server-side programming languages
645 The database tier—the database server you choose, which can often depend
646on the business tier
647ï‚· The tiers each include an operating system, server, database and server-side
648scripting language. You‘re not limited to the components in a stack—they‘re
649interchangeable based on your needs and customizable.
650Examples of solution stacks
651One of the earliest stacks to get traction is the LAMP( LAMP:
652Linux/Apache/MySQL/PHP) stack, made up of all free, open-source software
653components that work especially well for dynamic web sites and applications. It includes:
654the Linux operating system, the Apache web server, PHP application software, and
655MySQL database. It‘s the most traditional stack model, and incredibly solid. Note: PHP
656is interchangeable with the languages Python and Perl.
657LAMP benefits: It‘s flexible, customizable, easy to develop, easy to deploy,
658secure, and comes with a huge support community since it‘s open-source. Also, SQL
659databases are great for organizing massive amounts of highly structured data.
660Variations include:
661a. WAMP (Windows/Apache/MySQL/PHP): A Microsoft Windows OS
662equivalent, it‘s all-inclusive and easy to get started with. The WIMP
663stack is similar but has the IIS server.
664b. LAPP (Linux/Apache/PostgreSQL/PHP): a PostgreSQL database
665variation that‘s optimized for enterprise-level projects.
666c. MAMP (Mac OS X/Apache/MySQL/PHP): A MacOS X operating
667system variation, it‘s available for both Windows and Mac.
668d. XAMPP (Linux, Mac OS X, Windows/Apache/MySQL/PHP, Perl): A
669more complete bundle, it includes an FTP server, which is crossplatform,
670able to run on Linux, Windows, and Mac operating systems.
67127 [Web Application Development I-ITDB201]
6722.4. Setting Up Local Web Server
673a. WAMPSERVER
674WampServer is a Windows web development environment. It allows you to
675create web applications with Apache2, PHP and a MySQL database. Alongside,
676PhpMyAdmin allows you to manage easily your databases.
677b. Downloading and Installing WampServer
678WampServer is available for free (under GPML license) in two distinct versions:
67932 and 64 bits. Wampserver 2.5 is not compatible with Windows XP, neither with
680SP3, nor Windows Server 2003. Older WampServer versions are available on
681SourceForge.
682c. Steps in installing WampServer
6831. Go to Downloads in the WampServer website :
684Figure 2.2: WampServer Website
6852. Check the System type of your computer in the System Properties if it is
68632-bit or 64-bit.
687Figure 2.3: System Properties – System Type
68828 [Web Application Development I-ITDB201]
6893. Download the appropriate installer for your computer.
690Figure 2.4: Downloading WampServer Installer
6914. Follow the instructions in the installer.
6922.5. Testing the Installation
693a. Accessing the localhost
694Localhost is a hostname that means this computer. It is used to access the
695network services that are running on the host via its loopback network interface.
696Localhost resolves to the IP address 127.0.0.1, which is the most commonly used
697IPv4 loopback address. You can open a browser and type: http://localhost or
698http://127.0.01 to check if you have successfully installed the web server.
699Figure 2.5: Running the Localhost
70029 [Web Application Development I-ITDB201]
701b. Executing phpinfo()
702Because every system is setup differently, phpinfo() is commonly used to check
703configuration settings and for available predefined variables on a given system.
704phpinfo() is also a valuable debugging tool as it contains all EGPCS
705(Environment, GET, POST, Cookie, Server) data. It is advisable to run phpinfo()
706before starting any development so you will be aware of the settings of your
707development environment.
708Methods of executing phpinfo():
7091. Creating your own phpinfo file. Create a new php script executing
710the phpinfo() function and save in your document root. Open the
711browser and load the phpinfo() file.
712Figure 2.6: Loading phpinfo()
71330 [Web Application Development I-ITDB201]
7142. Using WampServers Tools. WampServer has Tools section which
715provides a link to a phpinfo() script. You can click on this link and
716the phpinfo() will be loaded.
717Figure 2.7: WampServer Tools
7182.6. APACHE WEB SERVER CONFIGURATION
719a. HTTD.CONF
720Apache HTTP Server is configured by placing directives in plain text
721configuration files. The main configuration file is usually called httpd.conf. The
722location of this file if using WAMPSERVER in Windows environment is:
723C:\wamp\bin\apache\Apache2.4.4\conf. Any directive may be placed in any
724of these configuration files. Changes to the main configuration files are only
725recognized by httpd when it is started or restarted.
726b. Default Page / Index Page
727This option will tell Apache which file to serve/load if a directory is being
728requested. For example, if you want your index.php as the first page to open when
729your folder is requested from the browser, you would include index.php in this
730option.
731Figure 2.7: Directory Index Settings ( httpd.conf)
73231 [Web Application Development I-ITDB201]
733c. Changing Document Root
734You can change the location where Apache stores your web pages by modifying
735two configurations. The default location is C:/wamp/www. Suppose you want to
736save your files in D:\www, you have to change the two settings.
7371. DocumentRoot
738Figure 2.8: Document Settings (php.ini)
7392. Directory
740Figure 2.9: Directory Settings (php.ini)
741 Chapter Summary:
742In developing web applications, it is vital to maintain development environment
743and production environment. The development environment is where developers do their
744work and write codes. The production environment is sometimes called ―live‖
745environment since this is where the users are directly interacting with. To build a web
746application, the development environment needs to have several components for the
747developers to utilize. These are web servers, code editors, integrated development
748environment (IDE), scripting languages and DBMS. There are a lot of options for
749developers to choose from ranging from open source to license software and tools to
750develop applications. A software stack is a term used to refer to the bundles of software
75132 [Web Application Development I-ITDB201]
752from which your application will run. Likewise, there are a lot of software stack bundles
753that can be configured each has each own advantages and disadvantages.
754Assignments:
7551. List the current top 10 programming languages used for web development.
756_______________________________________________________________________
757_______________________________________________________________________
758_______________________________________________________________________
759_______________________________________________________________________
760_______________________________________________________________________
7612. Complete the table below for programming languages used in most popular websites.
762Website
763Front-end
764(Client-side)
765Back-end
766(Server-Side)
767Database
768Youtube.com
769Facebook.com
770Google.com
771Ebay.com
772Wikipedia.org
773Laboratory Exercises:
774Learning Outcome: At the end of this activity, the students should be able to:
775a. Know what software, where to acquire the software and latest version to be used
776in developing in a web application.
777b. Classify each software according to its source code availability model (opensourced
778or closed-sourced).
77933 [Web Application Development I-ITDB201]
7801. Web application development tools activity matrix.
781Activity Matrix
782Category: Problem-based Learning
783Suggested
784duration:
785Ongoing, throughout a class session as appropriate
786Intent: Allows students to map the different tools/software required in
787developing web applications.
788Implementation: 1. In the first column, shows some tools/software for web application
789development.
7902. In the next columns, write the description, website/URL where the
791software may be acquired, state the latest version and identify if the
792software is open source or close source.
793Software Description Website
794Latest
795Version
796(Open Source or
797Close-Source)
798Apache
799HTTP Server
800WampServer
801PHP
802MySql
803Notepad++
804Sublime
805Text
806Microsoft
807Expression
808Web 4
80934 [Web Application Development I-ITDB201]
810References:
811[1]"Source code editor", En.wikipedia.org, 2017. [Online]. Available:
812https://en.wikipedia.org/wiki/Source_code_editor. [Accessed: 07- Feb- 2017].
813[2]"Integrated development environment", En.wikipedia.org, 2017. [Online]. Available:
814https://en.wikipedia.org/wiki/Integrated_development_environment. [Accessed: 07- Feb- 2017].
815[3]"Scripting language", En.wikipedia.org, 2017. [Online]. Available:
816https://en.wikipedia.org/wiki/Scripting_language. [Accessed: 07- Feb- 2017].
817[4]G. Smith, "13 PHP Frameworks to Help Build Agile Applications", Mashable, 2017. [Online].
818Available: http://mashable.com/2014/04/04/php-frameworks-build-applications. [Accessed: 07- Feb2017].
819[5]H. Home, W. Development and C. Stack, "What is a Software Stack? Choose the right stack for
820your project", Hiring | Upwork, 2017. [Online]. Available:
821https://www.upwork.com/hiring/development/choosing-the-right-software-stack-for-your-website/.
822[Accessed: 07- Feb- 2017].
823[6]"PHP: phpinfo - Manual", Php.net, 2017. [Online]. Available:
824http://php.net/manual/en/function.phpinfo.php. [Accessed: 07- Feb- 2017].
825[7]"Deployment environment", En.wikipedia.org, 2017. [Online]. Available:
826https://en.wikipedia.org/wiki/Deployment_environment. [Accessed: 07- Feb- 2017].
827[8]"Configuration Files - Apache HTTP Server Version 2.4", Httpd.apache.org, 2017. [Online].
828Available: https://httpd.apache.org/docs/2.4/configuring.html. [Accessed: 07- Feb- 2017].
82935 [Web Application Development I-ITDB201]
830Chapter 3: Front-End Web Development
831 Objectives
832At the end of this module, the students will be able to:
833ï‚· Recognize the principles of web design.
834ï‚· Apply the principles of web design in developing web applications to
835achieve effective results.
836ï‚· Design a responsive website.
837ï‚· Use the different components of Bootstrap framework in creating a
838responsive website.
8393.1 Principles of Effective Web Design Principles
840Like the phrase ‗beauty is in the eye of the beholder‘, effective web design is judged
841by the users of the website and not the website owners. There are many factors that affect the
842usability of a website, and it is not just about form (how good it looks), but also function
843(how easy is it to use).
844Figure 3.1: Principles of Web Design
84536 [Web Application Development I-ITDB201]
846Websites that are not well designed tend to perform poorly and have sub-optimal
847Google Analytics metrics (e.g. high bounce rates, low time on site, low pages per visit
848and low conversions). So what makes good web design? Below we explore the top 10
849web design principles that will make your website aesthetically pleasing, easy to use,
850engaging, and effective.
8513.1.1 Purpose
852Good web design always caters to the needs of the user. Are your web visitors
853looking for information, entertainment, some type of interaction, or to transact with your
854business? Each page of your website needs to have a clear purpose, and to fulfill a
855specific need for your website users in the most effective way possible.
8563.1.2 Communication
857People on the web tend to want information quickly, so it is important to
858communicate clearly, and make your information easy to read and digest. Some effective
859tactics to include in your web design include: organising information using headlines and
860sub headlines, using bullet points instead of long windy sentences, and cutting the waffle.
8613.1.3 Typefaces
862In general, Sans Serif fonts such as Arial and Verdana are easier to read online (Sans
863Serif fonts are contemporary looking fonts without decorative finishes). The ideal font
864size for reading easily online is 16px and stick to a maximum of 3 typefaces in a
865maximum of 3 point sizes to keep your design streamlined.
866Figure 3.2: Typefaces
86737 [Web Application Development I-ITDB201]
8683.1.4 Colours
869A well thought out colour palette can go a long way to enhance the user
870experience. Complementary colours create balance and harmony. Using contrasting
871colours for the text and background will make reading easier on the eye. Vibrant colours
872create emotion and should be used sparingly (e.g. for buttons and call to actions). Last but
873not least, white space/ negative space is very effective at giving your website a modern
874and uncluttered look.
8753.1.5 Images
876A picture can speak a thousand words, and choosing the right images for your
877website can help with brand positioning and connecting with your target audience. If you
878don‘t have high quality professional photos on hand, consider purchasing stock photos to
879lift the look of your website. Also consider using infographics, videos and graphics as
880these can be much more effective at communicating than even the most well written
881piece of text.
8823.1.6 Navigation
883Navigation is about how easy it is for people to take action and move around your
884website. Some tactics for effective navigation include a logical page hierarchy, using
885bread crumbs, designing clickable buttons, and following the ‗three click rule‘ which
886means users will be able to find the information they are looking for within three clicks.
8873.1.7 Grid based layouts
888Placing content randomly on your web page can end up with a haphazard appearance
889that is messy. Grid based layouts arrange content into sections, columns and boxes that
890line up and feel balanced, which leads to a better looking website design.
8913.1.8 “F†Pattern design
892Eye tracking studies have identified that people scan computer screens in an ―F‖
893pattern. Most of what people see is in the top and left of the screen and the right side of
894the screen is rarely seen. Rather than trying to force the viewer‘s visual flow, effectively
89538 [Web Application Development I-ITDB201]
896designed websites will work with a reader‘s natural behaviour and display information in
897order of importance (left to right, and top to bottom).
898Figure 3.3: “F†Pattern Design
8993.1.9. Load time
900Everybody hates a website that takes ages to load. Tips to make page load times
901more effective include optimizing image sizes (size and scale), combining code into a
902central CSS or JavaScript file (this reduces HTTP requests) and minify HTML, CSS,
903JavaScript (compressed to speed up their load time).
9043.1.10 Mobile friendly
905It is now commonplace to access websites from multiple devices with multiple screen
906sizes, so it is important to consider if your website is mobile friendly. If your website is
907not mobile friendly, you can either rebuild it in a responsive layout (this means your
908website will adjust to different screen widths) or you can build a dedicated mobile site (a
909separate website optimized specifically for mobile users).
91039 [Web Application Development I-ITDB201]
911Figure 3.4: Examples of Devices
912It is easy to create a beautiful and functional website, simply by keeping these
913design elements in mind. Have you got a website design that needs reviewing or
914optimising? Or perhaps, you are planning a website and you are looking to get the design
915right from the ground up. Either way, these principles of effective web design can help
916your website be more engaging, useful, and memorable for visitors.
9173.2 Responsive Web Design
918Responsive Web design is the approach that suggests that design and
919development should respond to the user‘s behavior and environment based on screen
920size, platform and orientation. The practice consists of a mix of flexible grids and layouts,
921images and an intelligent use of CSS media queries. As the user switches from their
922laptop to iPad, the website should automatically switch to accommodate for resolution,
923image size and scripting abilities. In other words, the website should have the technology
924to automatically respond to the user‘s preferences. This would eliminate the need for a
925different design and development phase for each new gadget on the market.
92640 [Web Application Development I-ITDB201]
927Figure 3.5: Responsive Web Design
9283.3 Bootstrap
929Bootstrap uses mobile first approach to create responsive websites. As per
930mobile first approach, bootstrap emphasises to first create the website for
931mobile devices and later enhancing and enriching the website render it on
932other large devices as well.
933ï‚· Bootstrap is a free front-end framework for faster and easier web
934development
935ï‚· Bootstrap includes HTML and CSS based design templates for
936typography, forms, buttons, tables, navigation, modals, image
937carousels and many other, as well as optional JavaScript plugins.
938ï‚· Bootstrap also gives you the ability to easily create responsive
939designs.
940ï‚· Bootstrap is completely free to download and use from
941http://getbootstrap.com/.
9423.3.1 Bootstrap Get Started
943There are two ways to start using Bootstrap on your own web site. You can:
944ï‚· Download Bootstrap from getbootstrap.com
945ï‚· Include Bootstrap from a Content Delivery Network (CDN)
946Place your screenshot here
947Place your screenshot
948here
949Place your
950screenshot
951here
952Place your screenshot here
95341 [Web Application Development I-ITDB201]
954MaxCDN:
955One advantage of using the Bootstrap CDN:
956Many users already have downloaded Bootstrap from MaxCDN when visiting
957another site. As a result, it will be loaded from cache when they visit your site, which
958leads to faster loading time. Also, most CDN's will make sure that once a user
959requests a file from it, it will be served from the server closest to them, which also
960leads to faster loading time.
9613.3.2 Bootstrap Grid System
962Bootstrap's grid system allows up to 12 columns across the page. If you do not
963want to use all 12 columns individually, you can group the columns together to create
964wider columns:
965Figure 3.6: Bootstrap Grid System
966<!-- Latest compiled and minified CSS -->
967<link
968rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
969bootstrap.min.css">
970<!-- jQuery library -->
971<script
972src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></s
973cript>
974<!-- Latest compiled JavaScript -->
975<script
976src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
977</script>
97842 [Web Application Development I-ITDB201]
979Bootstrap's grid system is responsive, and the columns will re-arrange
980automatically depending on the screen size.
9813.3.3 Bootstrap Text/Typography
982a. Bootstrap's Default Settings
983Bootstrap's global default font-size is 14px, with a line-height of 1.428.
984This is applied to the <body> and all paragraphs.
985In addition, all <p> elements have a bottom margin that equals half their
986computed line-height (10px by default).
987b. Bootstrap vs. Browser Defaults
988We will look at some HTML elements that will be styled a little bit differently
989by Bootstrap than browser defaults.
990c. <h1> - <h6>
991By default, Bootstrap will style the HTML headings (<h1> to <h6>) in the
992following way:
993Figure 3.7: Bootstrap HTML Headings
994d. <small>
995In Bootstrap the HTML <small> element is used to create a lighter,
996secondary text in any heading:
99743 [Web Application Development I-ITDB201]
998Figure 3.8: Bootstrap <small>
999e. <mark>
1000Bootstrap will style the HTML <mark> element in the following way:
1001Figure 3.9: Bootstrap <mark>
1002f. <abbr>
1003Bootstrap will style the HTML <abbr> element in the following way:
1004Figure 3.10: Bootstrap <abbr>
1005g. <blockquote>
1006Bootstrap will style the HTML <blockquote> element in the following way:
1007Figure 3.11: Bootstrap < blockquote >
100844 [Web Application Development I-ITDB201]
1009h. Contextual Colors and Backgrounds
1010Bootstrap also has some contextual classes that can be used to provide "meaning
1011through colors".
1012The classes for text colors are:.text-muted, .text-primary, .text-success, .textinfo,
1013.text-warning, and .text-danger:
1014Figure 3.11: Bootstrap Text Color Classes
1015The classes for background colors are:.bg-primary, .bg-success, bginfo,
1016bg-warning, and .bg-danger:
1017Figure 3.11: Bootstrap Background Color Classes
10183.3.4 Bootstrap Tables
1019a. Bootstrap Basic Table
1020A basic Bootstrap table has a light padding and only horizontal dividers.
1021The .table class adds basic styling to a table:
1022Figure 3.12: Bootstrap Basic Table
102345 [Web Application Development I-ITDB201]
1024Here is the code:
1025b. Striped Rows
1026The .table-striped class adds zebra-stripes to a table:
1027Figure 3.13: Bootstrap Table Striped
102846 [Web Application Development I-ITDB201]
1029Here is the code:
1030c. Bordered Table
1031The .table-bordered class adds borders on all sides of the table and cells:
1032Figure 3.14: Bootstrap Bordered Table
1033d. Responsive Tables
1034The .table-responsive class creates a responsive table. The table will then
1035scroll horizontally on small devices (under 768px). When viewing on anything
1036larger than 768px wide, there is no difference:
1037Figure 3.15: Bootstrap Responsive Table
103847 [Web Application Development I-ITDB201]
10393.3.5 Bootstrap Image Shapes
1040Figure 3.16: Bootstrap Images
1041a. Rounded Corners
1042The .img-rounded class adds rounded corners to an image (IE8 does not support
1043rounded corners):
1044b. Circle
1045The .img-circle class shapes the image to a circle (IE8 does not support rounded
1046corners):
1047c. Thumbnail
1048The .img-thumbnail class shapes the image to a thumbnail:
1049d. Responsive Images
1050Images come in all sizes. So do screens. Responsive images automatically adjust
1051to fit the size of the screen.
105248 [Web Application Development I-ITDB201]
1053Create responsive images by adding an .img-responsive class to the <img> tag.
1054The image will then scale nicely to the parent element.
1055The .img-responsive class applies display: block; and max-width:
1056100%; and height: auto; to the image:
10573.3.6 Bootstrap Form Inputs
1058Bootstrap supports the following form controls:
1059ï‚· input
1060ï‚· textarea
1061ï‚· checkbox
1062ï‚· radio
1063ï‚· select
1064a. Bootstrap Input
1065Bootstrap supports all the HTML5 input types: text, password, datetime, datetimelocal,
1066date, month, time, week, number, email, url, search, tel, and color.
1067Note: Inputs will NOT be fully styled if their type is not properly declared!
1068Figure 3.17: Bootstrap Input
1069The following example contains two input elements; one of type text and one of type
1070password:
107149 [Web Application Development I-ITDB201]
1072b. Bootstrap Textarea
1073Figure 3.18: Bootstrap Textarea
1074c. Bootstrap Checkboxes
1075Figure 3.19: Bootstrap Checkboxes
1076d. Bootstrap Radio Buttons
1077Figure 3.20: Bootstrap Radio Buttons
107850 [Web Application Development I-ITDB201]
1079e. Bootstrap Select List
1080Figure 3.21: Bootstrap Select List
10813.3.7 Bootstrap Forms
1082Form controls automatically receive some global styling with Bootstrap:
1083All textual <input>, <textarea>, and <select> elements with class .form-control have
1084a width of 100%.
1085a. Bootstrap Form Layouts
1086Bootstrap provides three types of form layouts:
1087ï‚· Vertical form (this is default)
1088ï‚· Horizontal form
1089ï‚· Inline form
1090Standard rules for all three form layouts:
109151 [Web Application Development I-ITDB201]
1092ï‚· Wrap labels and form controls in <div class="form-group"> (needed for
1093optimum spacing)
1094ï‚· Add class .form-control to all textual <input>, <textarea>,
1095and <select> elements
1096b. Bootstrap Vertical Form (default)
1097Figure 3.22: Bootstrap Vertical Form
1098c. Bootstrap Inline Form
1099Figure 3.22: Bootstrap Inline Form
1100In an inline form, all of the elements are inline, left-aligned, and the labels are
1101alongside.
1102Note: This only applies to forms within viewports that are at least 768px wide!
1103Additional rule for an inline form:
1104Add class .form-inline to the <form> element
110552 [Web Application Development I-ITDB201]
1106The following example creates an inline form with two input fields, one checkbox,
1107and one submit button:
11083.3.8 Bootstrap Horizontal Form
1109Figure 3.23: Bootstrap Horizontal Form
1110A horizontal form stands apart from the other forms both in the amount of markup,
1111and in the presentation of the form.
1112Additional rules for a horizontal form:
1113ï‚· Add class .form-horizontal to the <form> element
1114ï‚· Add class .control-label to all <label> elements
1115Tip: Use Bootstrap's predefined grid classes to align labels and groups of form
1116controls in a horizontal layout.
1117The following example creates a horizontal form with two input fields, one checkbox,
1118and one submit button:
111953 [Web Application Development I-ITDB201]
11203.3.9 Bootstrap Glyphicons
1121Bootstrap provides 260 glyphicons from the Glyphicons Halflings set.
1122Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc.
1123Here are some examples of glyphicons:
1124Figure 3.24: Bootstrap Glyphicon
1125Glyphicon Syntax
1126A glyphicon is inserted with the following syntax:
112754 [Web Application Development I-ITDB201]
11283.2.10 Bootstrap Wells
1129The .well class adds a rounded border around an element with a gray
1130background color and some padding:
1131Figure 3.25: Bootstrap Wells
1132Well Size
1133Figure 3.25: Bootstrap Well Size
1134Change the size of the well by adding the .well-sm class for small wells or .well-lg class
1135for large wells:
11363.2.11 Bootstrap Buttons
1137Button Styles
1138Bootstrap provides seven styles of buttons:
113955 [Web Application Development I-ITDB201]
1140Figure 3.26: Bootstrap Buttons
1141a. Button Sizes
1142Bootstrap provides four button sizes:
1143Figure 3.27: Bootstrap Button Sizes
1144b. Block Level Buttons
1145A block level button spans the entire width of the parent element.
1146Button 1Button 2
1147Figure 3.28: Bootstrap Block Level Buttons
114856 [Web Application Development I-ITDB201]
1149c. Active/Disabled Buttons
1150A button can be set to an active (appear pressed) or a disabled
1151(unclickable) state:
1152Figure 3.29: Bootstrap Active/Disabled Buttons
11533.2.12 Bootstrap Dropdowns
1154a. Basic Dropdown
1155A dropdown menu is a toggleable menu that allows the user to choose one value
1156from a predefined list:
1157Figure 3.30: Bootstrap Basic Dropdown
115857 [Web Application Development I-ITDB201]
1159b. Dropdown Divider
1160The .divider class is used to separate links inside the dropdown menu with a thin
1161horizontal border:
1162c. Disable and Active items
1163Highlight a specific dropdown item with the .active class (adds a blue background
1164color).
1165To disable an item in the dropdown menu, use the .disabled class (gets a lightgrey
1166text color and a "no-parking-sign" icon on hover):
11673.2.13 Bootstrap Tabs and Pills
1168a. Tabs
1169Tabs are created with <ul class="nav nav-tabs">:
1170Tip: Also mark the current page with <li class="active">.
117158 [Web Application Development I-ITDB201]
1172The following example creates navigation tabs:
1173Figure 3.31: Bootstrap Tabs
1174b. Pills
1175Pills are created with <ul class="nav nav-pills">. Also mark the current page
1176with <li class="active">:
1177Figure 3.32: Bootstrap Pills
11783.2.14 Bootstrap Carousel Plugin
1179The Carousel plugin is a component for cycling through elements, like a carousel
1180(slideshow).
118159 [Web Application Development I-ITDB201]
11823.2.15 Bootstrap Navigation Bar
1183a. Navigation Bars
1184A navigation bar is a navigation header that is placed at the top of the page:
1185Figure 3.33: Bootstrap Navigation Bars
1186With Bootstrap, a navigation bar can extend or collapse, depending on the
1187screen size.
1188A standard navigation bar is created with <nav class="navbar navbar-default">.
1189The following example shows how to add a navigation bar to the top of the page:
119060 [Web Application Development I-ITDB201]
1191b. Right-Aligned Navigation Bar
1192Figure 3.34: Bootstrap b. Right-Aligned Navigation Bar
1193The .navbar-right class is used to right-align navigation bar buttons.
1194In the following example we insert a "Sign Up" button and a "Login" button to the
1195right in the navigation bar. We also add a glyphicon on each of the two new
1196buttons:
119761 [Web Application Development I-ITDB201]
1198 Chapter Summary:
1199Front-end web development is an area in web application development that has a very big
1200impact on user experience and user acceptability because users interact with the application
1201through the front end interfaces and web page designs. The demand for effective front end has
1202increase so much in demand with users using different kinds of devices in accessing web
1203applications. Thus, the concept of responsive web design has been a must for web applications.
1204Bootstrap is one of the many front end development frameworks that enables responsive web
1205pages.
1206Assignments:
12071. When talking about responsive web design, what are the differences between the Mobile First
1208and the Desktop First approaches?
1209_______________________________________________________________________
1210_______________________________________________________________________
1211_______________________________________________________________________
1212_______________________________________________________________________
1213_______________________________________________________________________
12142. How does Responsive Website Design helps businesses attract more customers and increase
1215customer satisfaction?
1216_______________________________________________________________________
1217_______________________________________________________________________
1218_______________________________________________________________________
1219_______________________________________________________________________
1220_______________________________________________________________________
12213. How does frameworks such as Bootstrap helps in web application development?
1222_______________________________________________________________________
1223_______________________________________________________________________
1224_______________________________________________________________________
1225_______________________________________________________________________
1226_______________________________________________________________________
122762 [Web Application Development I-ITDB201]
12284. Front-end vs Back-end Web Developers
1229Table 1:
1230A. Must know the three main
1231languages: HTML, CSS,
1232and Javascript
1233programming
1234B. Maintains the database of
1235the application.
1236C. Familiar with frameworks
1237like Bootstrap, Foundation,
1238Backbone, AngularJS, and
1239EmberJS,
1240D. Experienced with Ajax E. Identify specific issues in
1241user experience
1242F. Ability to learn quickly
1243G. Use server-side languages
1244like PHP, Ruby, Python,
1245Java, and .Net
1246H. Ability to solve problems
1247efficiently
1248I. Responsible for writing
1249codes that interacts with
1250database.
1251J. Strong communication
1252skills
1253K. Team player L. Work closely with
1254designers or user experience
1255analysts to bring mockups
1256Table 2:
1257Front-end Web Developers Back-end Web Developers
12585. What is a web page template? How do templates help developers in developing web
1259applications?
1260_______________________________________________________________________
1261_______________________________________________________________________
1262_______________________________________________________________________
1263_______________________________________________________________________
1264_______________________________________________________________________
1265Categorizing Grid
1266Category: Critical Thinking
1267Suggested
1268duration:
1269Ongoing in and/or out of class as appropriate
1270Intent: To have students identify the skills, technologies and tools required for a
1271front-end and back-end web developers.
1272Implementation: 1. This activity may be done in the group or as instructed by your teacher.
12732. Table 1 shows a list of skills/tools required for a front-end or back-end
1274web developer.
12753. Categorize these lists by writing the letter in the appropriate column in
1276Table 2. Note: You may write the same letter in both the columns if you
1277think that it is required in both.
12784. Discuss your answers to the class.
127963 [Web Application Development I-ITDB201]
1280Laboratory Exercises:
1281Learning Outcome: At the end of this activity, the students should be able to:
1282a. Create responsive web pages using the different Bootstrap components.
1283b. Use responsive design testing tools to test the responsiveness of a web page.
12841. Use the responsive grid classes in Bootstrap to create the following web page layout.
1285Name the sections properly. Save this as web_template.php.
1286HEADER
1287BOOSTRAP CAROUSEL
1288About Salalah
1289Search form
1290IMAGE IMAGE IMAGE
1291FOOTER
129264 [Web Application Development I-ITDB201]
12932. In continuation to exercise 1, design the web page below. Your page should have the
1294following Bootstrap components:
1295a. Navigation Bar
1296b. Bootstrap Carousel
1297c. Responsive Images
1298d. Forms
129965 [Web Application Development I-ITDB201]
1300References:
1301[1] Mark Otto, "Bootstrap · The world's most popular mobile-first and responsive front-end
1302framework.", Getbootstrap.com, 2016. [Online]. Available: http://getbootstrap.com/. [Accessed:
130319- Nov- 2016].
1304[2]"Bootstrap 3 Tutorial - An Ultimate Guide for Beginners", Tutorialrepublic.com, 2016.
1305[Online]. Available: http://www.tutorialrepublic.com/twitter-bootstrap-tutorial/. [Accessed: 19-
1306Nov- 2016].
1307[3]"Web Style Guide", Webstyleguide.com, 2016. [Online]. Available:
1308http://webstyleguide.com/index.html. [Accessed: 19- Nov- 2016].
1309[4]S. Woods, "10 Top Principles of Effective Web Design - Shortie Designs", Shortie Designs,
13102016. [Online]. Available: http://shortiedesigns.com/2014/03/10-top-principles-effective-webdesign/.
1311[Accessed: 19- Nov- 2016].
1312[5]"Bootstrap 3 Tutorial", W3schools.com, 2017. [Online]. Available:
1313http://www.w3schools.com/bootstrap/default.asp. [Accessed: 04- Mar- 2017].
1314[6]"Bootstrap Get Started", W3schools.com, 2017. [Online]. Available:
1315https://www.w3schools.com/bootstrap/bootstrap_get_started.asp. [Accessed: 04- Mar- 2017].
1316[7]"Bootstrap Get Started", W3schools.com, 2017. [Online]. Available:
1317https://www.w3schools.com/bootstrap/bootstrap_get_started.asp. [Accessed: 04- Mar- 2017].
1318[8]"Bootstrap Grid System", W3schools.com, 2017. [Online]. Available:
1319https://www.w3schools.com/bootstrap/bootstrap_grid_system.asp. [Accessed: 04- Mar- 2017].
1320[9]"Bootstrap Text/Typography", W3schools.com, 2017. [Online]. Available:
1321https://www.w3schools.com/bootstrap/bootstrap_typography.asp. [Accessed: 04- Mar- 2017].
1322[10]"Bootstrap Images", W3schools.com, 2017. [Online]. Available:
1323https://www.w3schools.com/bootstrap/bootstrap_images.asp. [Accessed: 04- Mar- 2017].
1324[11]"Bootstrap Form Inputs", W3schools.com, 2017. [Online]. Available:
1325https://www.w3schools.com/bootstrap/bootstrap_forms_inputs.asp. [Accessed: 04- Mar- 2017].
1326[12]"Bootstrap Forms", W3schools.com, 2017. [Online]. Available:
1327https://www.w3schools.com/bootstrap/bootstrap_forms.asp. [Accessed: 04- Mar- 2017].
1328[14]"Bootstrap Navigation Bar", W3schools.com, 2017. [Online]. Available:
1329https://www.w3schools.com/bootstrap/bootstrap_navbar.asp. [Accessed: 04- Mar- 2017].
133066 [Web Application Development I-ITDB201]
1331Chapter 4: PHP Basics
1332 Objectives
1333At the end of this module, the students will be able to:
1334ï‚· Declare and use a variable in writing PHP scripts.
1335ï‚· Write PHP scripts that uses conditional statements.
1336ï‚· Explain the characteristics of an array in PHP.
1337ï‚· Create PHP scripts that manipulates array.
13384.1 PHP for Web Applications Development
1339With the increase in the use of internet for every purpose; right from leisure to
1340business, the number of websites getting developed is increasing each day. We have moved
1341from static to dynamic websites and PHP has made it easier for us to develop such dynamic
1342websites. PHP, a server side scripting language has got a plethora of benefits, which have
1343become the reasons of it being extensively used across the world for developing high class
1344websites. PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open
1345source general-purpose scripting language that is especially suited for web development and
1346can be embedded into HTML. Let us take a look at some of the most important reasons to
1347use PHP in web application development.
13481. Easy: This server side scripting language is extremely easy to learn, as compared to other
1349languages. Also, if you are familiar with the syntax of C or Perl, you will learn PHP
1350easily and quickly; all thanks to easy to understand syntax!
13512. Control: While other languages need long scripts, PHP can do the same work in a few
1352lines of code; having the maximum control over the websites. Also, whenever you want
1353to make changes, you can edit is easily.
13543. Cost efficient: As you know, PHP is open source, it is free of cost. You need not buy
1355expensive software for it. Your website will be developed in the minimal cost.
13564. Efficient: As you know you can enhance the performance of the website built in PHP, as
1357it is scalable when writing the code as well as reliable too when you need to deal with a
1358lot of web pages.
135967 [Web Application Development I-ITDB201]
13605. Access to support: As PHP is being used by a huge number of people, a large
1361community is formed. So, you need not worry if you get stuck somewhere. You will
1362easily get the support from them.
13636. Platform independent: Whether it is Windows, MacOS, Linux or UNIX; it supports all
1364the major web browsers.
13657. Supports all servers: PHP also supports all the major web servers; be it Apache or
1366Microsoft IIS. It also supports Netscape and personal web server.
13678. Speedy: PHP uses its own memory, so the workload of the server and loading time gets
1368reduced automatically, which results into the faster processing speed. So, it reduces the
1369development time when it comes to the web apps like eCommerce or CRM.
13709. Secured: It is one of the most secured way of developing websites and web applications;
1371as it has got a security layer to protect against viruses and threats.
137210. Tested, proven and trusted: As it has been used for over 2 decades by millions of
1373people, its capabilities have been tested and proven and thus trusted by the most
1374developers.
13754.2 PHP Basics
1376a. Variable
1377Variables are "containers" for storing information. A variable is simply a
1378container that‘s used to store both numeric and non-numeric information. And just as
1379with any container, you can move it from place to place, add stuff to it, or empty it
1380out on the floor in a pile and fill it with something completely different. A variable
1381can have a short name (like x and y) or a more descriptive name (age,
1382carname,total_volume).
1383b. Rules for PHP variable
1384PHP has some simple rules for naming variables. Every variable name must be
1385preceded with a dollar ($) symbol
1386ï‚· A variable starts with the $ sign, followed by the name of the variable
1387ï‚· A variable name must start with a letter or the underscore character
1388ï‚· A variable name cannot start with a number
1389ï‚· A variable name can only contain alpha-numeric characters and underscores (A-z,
13900-9, and _)
1391ï‚· Variable names are case-sensitive ($age and $AGE are two different variables)
139268 [Web Application Development I-ITDB201]
1393Note: Remember that PHP variable names are case-sensitive!
1394After the execution of the statements above, the variable $txt will hold the
1395value Hello world!, the variable $x will hold the value 5, and the variable $y will
1396hold the value 10.5.
1397Note: When you assign a text value to a variable, put quotes around the value.
1398Note: Unlike other programming languages, PHP has no command for declaring a
1399variable. It is created the moment you first assign a value to it.
1400c. echo and print statement in PHP
1401In PHP there are two basic ways to get output: echo and print. echo and print are
1402more or less the same. They are both used to output data to the screen.
1403The differences are small: echo has no return value while print has a return value
1404of 1 so it can be used in expressions. echo can take multiple parameters (although
1405such usage is rare) while print can take one argument. echo is marginally faster than
1406print.
1407d. Display text with echo statement
1408The following example shows how to output text with the echo command
1409(notice that the text can contain HTML markup):
1410Example:
1411<?php
1412$txt= "Helloworld!";
1413$x= 5;
1414$y= 10.5;
1415?>
1416Example:
1417<?php
1418echo "<h2>PHP is Fun!</h2>";
1419echo "Hello Rayyan!<br>";
1420echo "I am about to learn PHP!<br>";
1421echo "This ", "string ", "was ", "made ", "with
1422multiple parameters.";
1423?>
142469 [Web Application Development I-ITDB201]
1425Output:
1426Figure 4.1 – Writing Output in PHP using echo()
1427e. Display variable with echo statement
1428Output:
1429Figure 4.2 – Display Variable with echo statement
1430f. Data types in PHP
1431Variables can store data of different types, and different data types can do different
1432things.
1433Example:
1434<?php
1435$txt1 = "Learn PHP";
1436$txt2 = "W3Schools.com";
1437$x = 5;
1438$y = 4;
1439echo "<h2>$txt1</h2>";
1440echo "Study PHP at $txt2<br>";
1441echo $x + $y;
1442?>
144370 [Web Application Development I-ITDB201]
1444PHP supports the following data types:
1445ï‚· String
1446ï‚· Integer
1447ï‚· Float (floating point
1448numbers - also called
1449double)
1450ï‚· Boolean
1451ï‚· Array
1452ï‚· Object
1453ï‚· NULL
1454ï‚· Resource
1455g. Conditional Statements
1456Very often when you write code, you want to perform different actions for
1457different conditions. You can use conditional statements in your code to do this.
1458In PHP we have the following conditional statements:
1459ï‚· if statement - executes some code if one condition is true
1460ï‚· if...else statement - executes some code if a condition is true and another
1461code if that condition is false
1462ï‚· if...elseif....else statement - executes different codes for more than two
1463conditions
1464ï‚· switch statement - selects one of many blocks of code to be executed
1465h. The if statement
1466The if statement executes some code if one condition is true.
1467Syntax:
1468if (condition) {
1469code to be executed if condition is true;
1470}
1471The example below will output "Have a good day!" if the current time (HOUR) is
1472less than 20
1473Example:
1474<?php
1475$t = date("H");
1476if ($t < "20") {
1477echo "Have a good day!";
1478}
1479?>
148071 [Web Application Development I-ITDB201]
1481i. The if ….else statement
1482The if....else statement executes some code if a condition is true and another code if
1483that condition is false.
1484Syntax:
1485if (condition) {
1486code to be executed if condition is true;
1487} else {
1488code to be executed if condition is false;
1489}
1490The example below will output "Have a good day!" if the current time is less than 20
1491and "Have a good night!" otherwise:
1492j. The if...elseif....else Statement
1493The if....elseif...else statement executes different codes for more than two conditions.
1494Syntax:
1495if (condition) {
1496code to be executed if this condition is true;
1497} elseif (condition) {
1498code to be executed if this condition is true;
1499} else {
1500code to be executed if all conditions are false;
1501}
1502Example:
1503<?php
1504$t = date("H");
1505if ($t < "20") {
1506echo "Have a good day!";
1507} else {
1508echo "Have a good night!";
1509}
1510?>
151172 [Web Application Development I-ITDB201]
1512The example below will output "Have a good morning!" if the current time is less
1513than 10, and "Have a good day!" if the current time is less than 20. Otherwise it will
1514output "Have a good night!".
1515k. The switch statement
1516The switch statement is used to perform different actions based on different
1517conditions.
1518Use the switch statement to select one of many blocks of code to be executed.
1519Syntax:
1520switch (n) {
1521case label1:
1522code to be executed if n=label1;
1523break;
1524case label2:
1525code to be executed if n=label2;
1526break;
1527case label3:
1528code to be executed if n=label3;
1529break;
1530...
1531default:
1532code to be executed if n is different from all labels;
1533}
1534Example:
1535<?php
1536$t = date("H");
1537if ($t < "10") {
1538echo "Have a good morning!";
1539} elseif ($t < "20") {
1540echo "Have a good day!";
1541} else {
1542echo "Have a good night!";
1543}
1544?>R
154573 [Web Application Development I-ITDB201]
1546This is how it works: First we have a single expression n (most often a
1547variable), that is evaluated once. The value of the expression is then compared with
1548the values for each case in the structure. If there is a match, the block of code
1549associated with that case is executed. Use break to prevent the code from running
1550into the next case automatically. The default statement is used if no match is found.
1551l. Loops
1552In PHP, we have the following looping statements:
1553ï‚· while - loops through a block of code as long as the specified condition is true
1554ï‚· do...while - loops through a block of code once, and then repeats the loop as
1555long as the specified condition is true
1556ï‚· for - loops through a block of code a specified number of times
1557ï‚· foreach - loops through a block of code for each element in an array
1558Example:
1559<?php
1560$favcolor = "red";
1561switch ($favcolor) {
1562case "red":
1563echo "Your favorite color is red!";
1564break;
1565case "blue":
1566echo "Your favorite color is blue!";
1567break;
1568case "green":
1569echo "Your favorite color is green!";
1570break;
1571default:
1572echo "Your favorite color is neither red, blue, nor
1573green!";
1574}
1575?>
157674 [Web Application Development I-ITDB201]
1577m. while loop
1578The while loop executes a block of code as long as the specified condition is true.
1579Syntax:
1580while (condition is true) {
1581code to be executed;
1582}
1583The example below first sets a variable $x to 1 ($x = 1). Then, the while loop
1584will continue to run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase
1585by 1 each time the loop runs ($x++):
1586n. do…..while loop
1587The do...while loop will always execute the block of code once, it will then check the
1588condition, and repeat the loop while the specified condition is true.
1589Syntax:
1590do {
1591code to be executed;
1592} while (condition is true);
1593The example below first sets a variable $x to 1 ($x = 1). Then, the do while
1594loop will write some output, and then increment the variable $x with 1. Then the
1595condition is checked (is $x less than, or equal to 5?), and the loop will continue to run
1596as long as $x is less than, or equal to 5:
1597Example:
1598<?php
1599$x = 1;
1600while($x <= 5) {
1601echo "The number is: $x <br>";
1602$x++;
1603}
1604?>
160575 [Web Application Development I-ITDB201]
1606Notice that in a do while loop the condition is tested AFTER executing the statements
1607within the loop. This means that the do while loop would execute its statements at
1608least once, even if the condition is false the first time.
1609The example below sets the $x variable to 6, then it runs the loop, and then
1610the condition is checked:
1611o. for loop
1612The for loop is used when you know in advance how many times the script should
1613run.
1614Syntax:
1615for (init counter; test counter; increment counter) {
1616code to be executed;
1617}
1618Example:
1619<?php
1620$x = 1;
1621do {
1622echo "The number is: $x <br>";
1623$x++;
1624} while ($x <= 5);
1625?>
1626Example:
1627<?php
1628$x = 6;
1629do {
1630echo "The number is: $x <br>";
1631$x++;
1632} while ($x <= 5);
1633?>
163476 [Web Application Development I-ITDB201]
1635Parameters:
1636ï‚· init counter: Initialize the loop counter value
1637ï‚· test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
1638continues. If it evaluates to FALSE, the loop ends.
1639ï‚· increment counter: Increases the loop counter value
1640The example below displays the numbers from 0 to 10:
1641Example:
1642p. foreach loop
1643The foreach loop works only on arrays, and is used to loop through each key/value
1644pair in an array.
1645Syntax:
1646foreach ($array as $value) {
1647code to be executed;
1648}
1649For every loop iteration, the value of the current array element is assigned to $value
1650and the array pointer is moved by one, until it reaches the last array element.
1651The following example demonstrates a loop that will output the values of the given
1652array ($colors):
1653Example:
1654<?php
1655for ($x = 0; $x <= 10; $x++) {
1656 echo "The number is: $x <br>";
1657}
1658?>
165977 [Web Application Development I-ITDB201]
16604.3 PHP functions
1661Besides the built-in PHP functions, we can create our own functions.
1662A function is a block of statements that can be used repeatedly in a program.
1663A function will not execute immediately when a page loads.
1664A function will be executed by a call to the function.
1665a. User defined function in PHP
1666A user defined function declaration starts with the word "function":
1667Syntax:
1668function functionName( ) {
1669code to be executed;
1670}
1671Note: A function name can start with a letter or underscore (not a number).
1672Tip: Give the function a name that reflects what the function does!
1673Function names are NOT case-sensitive.
1674In the example below, we create a function named "writeMsg()". The opening curly
1675brace ( { ) indicates the beginning of the function code and the closing curly brace ( }
1676) indicates the end of the function. The function outputs "Hello world!". To call the
1677function, just write its name:
1678Example:
1679<?php
1680$colors = array("red", "green", "blue", "yellow");
1681foreach ($colors as $value) {
1682echo "$value <br>";
1683}
1684?>
1685Example:
1686<?php
1687function writeMsg( ) {
1688echo "Hello world!";
1689}
1690writeMsg( ); // call the function
1691?>
169278 [Web Application Development I-ITDB201]
1693b. PHP function arguments
1694Information can be passed to functions through arguments. An argument is just like a
1695variable.
1696Arguments are specified after the function name, inside the parentheses. You can add
1697as many arguments as you want, just separate them with a comma.
1698The following example has a function with one argument ($fname). When the
1699familyName() function is called, we also pass along a name (e.g. Jani), and the name
1700is used inside the function, which outputs several different first names, but an equal
1701last name:
1702The following example has a function with two arguments ($fname and $year):
1703Example:
1704<?php
1705function familyName($fname) {
1706echo "$fname Refsnes.<br>";
1707}
1708familyName("Jani");
1709familyName("Hege");
1710familyName("Stale");
1711familyName("Kai Jim");
1712familyName("Borge");
1713?>
1714Example:
1715<?php
1716function familyName($fname, $year) {
1717echo "$fname Refsnes. Born in $year <br>";
1718}
1719familyName("Hege", "1975");
1720familyName("Stale", "1978");
1721familyName("Kai Jim", "1983");
1722?>
172379 [Web Application Development I-ITDB201]
1724c. PHP default argument value
1725The following example shows how to use a default parameter. If we call the function
1726setHeight() without arguments it takes the default value as argument:
1727d. PHP functions - Returning value
1728To let a function return a value, use the return statement:
1729e. Strings
1730A string is a sequence of characters, like "Hello world!"
1731ï‚· Get The Length of a String:
1732The PHP strlen() function returns the length of a string.
1733The example below returns the length of the string "Hello world!":
1734Example:
1735<?php
1736function setHeight($minheight = 50) {
1737echo "The height is : $minheight <br>";
1738}
1739setHeight(350);
1740setHeight(); // will use the default value of 50
1741setHeight(135);
1742setHeight(80);
1743?>
1744Example:
1745<?php
1746function sum($x, $y) {
1747$z = $x + $y;
1748return $z;
1749}
1750echo "5 + 10 = " . sum(5, 10) . "<br>";
1751echo "7 + 13 = " . sum(7, 13) . "<br>";
1752echo "2 + 4 = " . sum(2, 4);
1753?>
175480 [Web Application Development I-ITDB201]
1755ï‚· Count The Number of Words in a String:
1756The PHP str_word_count() function counts the number of words in a string:
1757ï‚· Reverse a String:
1758The PHP strrev() function reverses a string:
1759The output of the code above will be: !dlrow olleH.
1760ï‚· Search For a Specific Text Within a String:
1761The PHP strpos() function searches for a specific text within a string.
1762If a match is found, the function returns the character position of the first match.
1763If no match is found, it will return FALSE.
1764The example below searches for the text "world" in the string "Hello world!":
1765Example:
1766<?php
1767echo strpos("Hello world!", "world"); // outputs 6
1768?>
1769Example:
1770<?php
1771echo strrev("Hello world!"); // outputs !dlrow olleH
1772?>
1773Example:
1774<?php
1775echo str_word_count("Hello world!"); // outputs 2
1776?>
1777Example:
1778<?php
1779echo strlen("Hello world!"); // outputs 12
1780?>
178181 [Web Application Development I-ITDB201]
1782Tip: The first character position in a string is 0 (not 1).
1783ï‚· Replace Text Within a String:
1784The PHP str_replace() function replaces some characters with some other
1785characters in a string.
1786The example below replaces the text "world" with "Dolly":
1787The output of the code above will be: Hello Mueez!
17884.4. Arrays
1789An array stores multiple values in one single variable or An array is a special
1790variable, which can hold more than one value at a time.
1791If you have a list of items (a list of car names, for example), storing the cars in single
1792variables could look like this:
1793$cars1 = "Volvo";
1794$cars2 = "BMW";
1795$cars3 = "Toyota";
1796However, what if you want to loop through the cars and find a specific one? And
1797what if you had not 3 cars, but 300?
1798The solution is to create an array!
1799An array can hold many values under a single name, and you can access the values by
1800referring to an index number.
1801Example:
1802<?php
1803echo str_replace("world", "Mueez", "Hello
1804world!"); // outputs Hello Mueez!
1805?>
1806Example:
1807<?php
1808$cars = array("Volvo", "BMW", "Toyota");
1809echo "I like " . $cars[0] . ", " . $cars[1] . " and
1810" . $cars[2] . ".";
1811?>
181282 [Web Application Development I-ITDB201]
1813a. Create an Array in PHP:
1814In PHP, the array() function is used to create an array:
1815array();
1816b. In PHP, there are three types of arrays:
1817ï‚· Indexed arrays - Arrays with a numeric index
1818ï‚· Associative arrays - Arrays with named keys
1819ï‚· Multidimensional arrays - Arrays containing one or more arrays
1820c. PHP Indexed Arrays:
1821There are two ways to create indexed arrays:
1822The index can be assigned automatically (index always starts at 0), like this:
1823$cars = array("Volvo", "BMW", "Toyota");
1824or the index can be assigned manually:
1825$cars[0] = "Volvo";
1826$cars[1] = "BMW";
1827$cars[2] = "Toyota";
1828The following example creates an indexed array named $cars, assigns three elements
1829to it, and then prints a text containing the array values:
1830d. Get The Length of an Array - The count() Function:
1831The count() function is used to return the length (the number of elements) of an
1832array:
1833Example:
1834<?php
1835$cars = array("Volvo", "BMW", "Toyota");
1836echo "I like " . $cars[0] . ", " . $cars[1] . "
1837and " . $cars[2] . ".";
1838?>
1839Example:
1840<?php
1841$cars = array("Volvo", "BMW", "Toyota");
1842echo count($cars);
1843?>
184483 [Web Application Development I-ITDB201]
1845e. Loop Through an Indexed Array:
1846To loop through and print all the values of an indexed array, you could use a
1847for loop, like this:
1848f. PHP Associative Arrays:
1849Associative arrays are arrays that use named keys that you assign to them.
1850There are two ways to create an associative array:
1851$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
1852or:
1853$age['Peter'] = "35";
1854$age['Ben'] = "37";
1855$age['Joe'] = "43";
1856The named keys can then be used in a script:
1857Example:
1858<?php
1859$cars = array("Volvo", "BMW", "Toyota");
1860$arrlength = count($cars);
1861for($x = 0; $x < $arrlength; $x++) {
1862echo $cars[$x];
1863echo "<br>";
1864}
1865?>
1866Example:
1867<?php
1868$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
1869echo "Peter is " . $age['Peter'] . " years old.";
1870?>
187184 [Web Application Development I-ITDB201]
1872g. Loop Through an Associative Array:
1873To loop through and print all the values of an associative array, you could use
1874a foreach loop, like this:
1875h. PHP Multidimensional Array
1876A multidimensional array is an array containing one or more arrays.
1877PHP understands multidimensional arrays that are two, three, four, five, or more
1878levels deep. However, arrays more than three levels deep are hard to manage for most
1879people.
1880The dimension of an array indicates the number of indices you need to select an
1881element.
1882For a two-dimensional array you need two indices to select an element
1883For a three-dimensional array you need three indices to select an element
1884PHP - Two-dimensional Arrays:
1885A two-dimensional array is an array of arrays (a three-dimensional array is an array
1886of arrays of arrays).
1887Example:
1888<?php
1889$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
1890foreach($age as $x => $x_value) {
1891echo "Key=" . $x . ", Value=" . $x_value;
1892echo "<br>";
1893}
1894?>
189585 [Web Application Development I-ITDB201]
1896First, take a look at the following table:
1897Name Stock Sold
1898Volvo 22 18
1899BMW 15 13
1900Saab 5 2
1901Land Rover 17 15
1902We can store the data from the table above in a two-dimensional array, like this:
1903$cars = array
1904(
1905array("Volvo",22,18),
1906array("BMW",15,13),
1907array("Saab",5,2),
1908array("Land Rover",17,15)
1909);
1910Now the two-dimensional $cars array contains four arrays, and it has two indices:
1911row and column.
1912To get access to the elements of the $cars array we must point to the two indices (row
1913and column):
1914We can also put a For loop inside another For loop to get the elements of the $cars
1915array (we still have to point to the two indices):
1916Example:
1917<?php
1918echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
1919echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
1920echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
1921echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
1922?>
192386 [Web Application Development I-ITDB201]
1924 Chapter Summary:
1925PHP is one of the widely used tool in developing web applications such as content
1926management systems, social networking site and E-Commerce applications. Some of the
1927reasons why PHP it is widely used are: it is free, cross platform, powerful, flexible and
1928scalable. Other than that PHP also has a vast range of community support for developers. In
1929addition, PHP frameworks are steadily becoming stronger and mature in helping developers
1930develop effective and flexible web applications.
1931Assignments:
19321. Another server side programming language which can be an alternative to PHP is Python. In
1933this activity, compare and contrast Python and PHP by identifying their respective
1934characteristics or features in the table.
1935PHP Python
1936Example:
1937<?php
1938for ($row = 0; $row < 4; $row++) {
1939echo "<p><b>Row number $row</b></p>";
1940echo "<ul>";
1941for ($col = 0; $col < 3; $col++) {
1942echo "<li>".$cars[$row][$col]."</li>";
1943}
1944echo "</ul>";
1945}
1946?>
194787 [Web Application Development I-ITDB201]
1948In your opinion, which between the two is better tool in developing web application? Why?
1949_______________________________________________________________________
1950_______________________________________________________________________
1951_______________________________________________________________________
1952_______________________________________________________________________
19532. What is a framework? Give at least 10 PHP Frameworks currently used by the industry.
1954Rank them according to mostly used by in developing web application.
1955_______________________________________________________________________
1956_______________________________________________________________________
1957_______________________________________________________________________
1958_______________________________________________________________________
1959_______________________________________________________________________
1960Laboratory Exercises:
1961Learning Outcome: At the end of this activity, the students should be able to:
1962a. Write PHP scripts utilizing conditional statements.
1963b. Declare, access and manipulate arrays in PHP.
19641. Write a PHP script that displays the remarks using conditional statements based on the
1965following criteria:
1966Age Remarks
19670-17 Young
196818-49 Adult
196950-above Matured
197088 [Web Application Development I-ITDB201]
1971Write your code here:
1972Declare arrays, access and output data from the array. Save and execute your PHP scripts in the
1973web server.
19743. Numeric Array Exercise
1975a. Save the name of countries (“Omanâ€,â€UAEâ€, “Qatarâ€) in an array and name it as
1976$countries.
1977b. Add the countries ―Kuwait‖, ―Saudi Arabia‖ to the array.
1978c. Use the function count() to count the size of the array and store in the variable $num.
1979d. Output all the countries in the array.
1980e. Output the number of countries in the array.
198189 [Web Application Development I-ITDB201]
1982Write your code here:
19832. Associative Array Exercise
1984a. Make the associative array $fruits with the information
1985(name=―Apple‖, color=‖red‖, price = 7)
1986b. Add another information ―size‖ with a value of ―big‖.
1987c. Display all the information about the fruit using foreach loop.
1988Write your code here:
198990 [Web Application Development I-ITDB201]
19904. Write a program which will count the "r" characters in the text "w3resource".
1991Write your code here:
199291 [Web Application Development I-ITDB201]
1993References:
1994[1]"PHP: Control Structures - Manual", Php.net, 2017. [Online]. Available:
1995http://php.net/manual/en/language.control-structures.php. [Accessed: 07- Mar- 2017].
1996[2]"PHP: What is PHP? - Manual", Php.net, 2017. [Online]. Available:
1997http://php.net/manual/en/intro-whatis.php. [Accessed: 07- Mar- 2017].
1998[3]"Top 10 Benefits of Using PHP in Web Development", Eliteinfoworld.com, 2017.
1999[Online]. Available: http://www.eliteinfoworld.com/blog/top-10-benefits-using-php-webdevelopment/.
2000[Accessed: 07- Mar- 2017].
2001[4]"PHP: Control Structures - Manual", Php.net, 2017. [Online]. Available:
2002http://php.net/manual/en/language.control-structures.php. [Accessed: 07- Mar- 2017].
2003[5]"PHP 5 Variables", W3schools.com, 2017. [Online]. Available:
2004https://www.w3schools.com/php/php_variables.asp. [Accessed: 07- Mar- 2017].
2005[6]"PHP 5 if...else...elseif Statements", W3schools.com, 2017. [Online]. Available:
2006https://www.w3schools.com/php/php_if_else.asp.[Accessed: 07- Mar- 2017].
2007[7]"PHP 5 for loops", W3schools.com, 2017. [Online]. Available:
2008https://www.w3schools.com/php/php_looping_for.asp. [Accessed: 07- Mar- 2017].
2009[8]"PHP 5 Echo and Print Statements", W3schools.com, 2017. [Online]. Available:
2010https://www.w3schools.com/php/php_echo_print.asp. [Accessed: 07- Mar- 2017].
2011[9]"PHP 5 switch Statement", W3schools.com, 2017. [Online]. Available:
2012https://www.w3schools.com/php/php_switch.asp. [Accessed: 07- Mar- 2017].
2013[10]"PHP 5 for loops", W3schools.com, 2017. [Online]. Available:
2014https://www.w3schools.com/php/php_looping_for.asp. [Accessed: 07- Mar- 2017].
2015[11]"PHP 5 Functions", W3schools.com, 2017. [Online]. Available:
2016https://www.w3schools.com/php/php_functions.asp. [Accessed: 07- Mar- 2017].
2017[12]"PHP 5 Strings", W3schools.com, 2017. [Online]. Available:
2018https://www.w3schools.com/php/php_string.asp. [Accessed: 07- Mar- 2017].
2019[13]"PHP 5 Arrays", W3schools.com, 2017. [Online]. Available:
2020https://www.w3schools.com/php/php_arrays.asp. [Accessed: 07- Mar- 2017].
2021[14]"PHP 5 Multidimensional Arrays", W3schools.com, 2017. [Online]. Available:
2022https://www.w3schools.com/php/php_arrays_multi.asp. [Accessed: 07- Mar- 2017].
202392 [Web Application Development I-ITDB201]
2024Chapter 5: FILES AND DIRECTORIES
2025 Objectives
2026At the end of this module, the students will be able to:
2027ï‚· Write PHP scripts that performs file handling.
2028ï‚· Manipulate directories using PHP scripts.
20295.1 Working With Files
2030You may well be familiar with databases such as MySQL and Access which are
2031an ever-increasingly common means of storing data. But data is also stored in files, like
2032Word documents, event logs, spreadsheets, image files, and so on. Databases generally
2033require a special query language to retrieve information, whereas files are ‗flat‘ and
2034usually appear as a stream of text.
2035Most often when working with files you‘ll read from or write to them. When you
2036want to read the contents of a file you first have to open it, then read as much of the
2037contents as you want, then close the file when you‘re finished. When writing to a file, it
2038also needs to be opened (or perhaps created if it doesn‘t already exist), then you write
2039your data to it, and close the file when you have finished. In PHP5 there are some built-in
2040wrapper functions that handle the opening and closing automatically for you, but it still
2041happens under the hood.
2042a. Create a File
2043We can create a new file by using the fopen function. The first parameter of fopen()
2044contains the name of the file to be opened and the second parameter specifies in
2045which mode the file should be opened.
2046<?php
2047$my_file = 'file.txt';
2048$handle = fopen($my_file, 'w') or
2049die('Cannot open file: '.$my_file);
2050?>
205193 [Web Application Development I-ITDB201]
2052A list of possible modes for fopen() using mode
2053modeDescription
2054'r' Open for reading only; place the file pointer at the beginning of the file.
2055'r+' Open for reading and writing; place the file pointer at the beginning of the
2056file.
2057'w' Open for writing only; place the file pointer at the beginning of the file and
2058truncate the file to zero length. If the file does not exist, attempt to create it.
2059'w+' Open for reading and writing; place the file pointer at the beginning of the
2060file and truncate the file to zero length. If the file does not exist, attempt to
2061create it.
2062'a' Open for writing only; place the file pointer at the end of the file. If the file
2063does not exist, attempt to create it. In this mode, fseek() has no effect,
2064writes are always appended.
2065'a+' Open for reading and writing; place the file pointer at the end of the file. If
2066the file does not exist, attempt to create it. In this mode, fseek() only affects
2067the reading position, writes are always appended.
2068'x' Create and open for writing only; place the file pointer at the beginning of
2069the file. If the file already exists, the fopen() call will fail by
2070returning FALSE and generating an error of level E_WARNING. If the
2071file does not exist, attempt to create it. This is equivalent to
2072specifying O_EXCL|O_CREAT flags for the underlying open(2) system
2073call.
2074'x+' Create and open for reading and writing; otherwise it has the same behavior
2075as 'x'.
2076'c' Open the file for writing only. If the file does not exist, it is created. If it
2077exists, it is neither truncated (as opposed to 'w'), nor the call to this function
2078fails (as is the case with 'x'). The file pointer is positioned on the beginning
2079of the file. This may be useful if it's desired to get an advisory lock
2080(see flock()) before attempting to modify the file, as using 'w' could
2081truncate the file before the lock was obtained (if truncation is
2082desired, ftruncate() can be used after the lock is requested).
2083'c+' Open the file for reading and writing; otherwise it has the same behavior
2084as 'c'.
2085'e' Set close-on-exec flag on the opened file descriptor. Only available in PHP
2086compiled on POSIX.1-2008 conform systems.
2087b. Write to a File
2088The fwrite() function is used to write to a file. The first parameter of fwrite()
2089contains the name of the file to write to and the second parameter is the string to be
2090written.
2091<?php
2092$my_file = 'file.txt';
2093$handle = fopen($my_file, 'w') or die('Cannot
2094open file: '.$my_file);
2095$data = 'This is the data';
2096fwrite($handle, $data);
2097?>
209894 [Web Application Development I-ITDB201]
2099c. Append to a File
2100The following code opens the file to append new data.
2101d. Closing a file
2102To close a file, use fclose().
2103e. Delete a File
2104To delete a file, use unlink().
21055.2 Working with Directories
2106PHP provides number of functions that can be used to perform tasks such as
2107identifying and changing the current directory, creating new directories, deleting
2108existing directories and listing the contents of a directory.
2109a. Creating Directories in PHP
2110A new directory can be created in PHP using the mkdir() function. This function
2111takes a path to the directory to be created.
2112<?php
2113$my_file = 'file.txt';
2114$handle = fopen($my_file, 'a') or die('Cannot
2115open file: '.$my_file);
2116$data = "New data line 1 \n";
2117fwrite($handle, $data);
2118$new_data = "New data line 2";
2119fwrite($handle, $new_data);
2120?>
2121<?php
2122$my_file = 'file.txt';
2123$handle = fopen($my_file, 'w') or die('Cannot
2124open file: '.$my_file);
2125//write some data here
2126fclose($handle);
2127?>
2128$my_file = 'file.txt';
2129unlink($my_file);
213095 [Web Application Development I-ITDB201]
2131A second, optional argument allows the specification of permissions on the directory
2132(controlling such issues as whether the directory is writable):
2133b. Deleting a Directory
2134Directories are deleted in PHP using the rmdir() function. The rmdir() takes
2135a single argument, the name of the directory to be deleted. The deletion will only be
2136successful if the directory is empty. If the directory contains files or other subdirectories
2137the deletion cannot be performed until those files and sub-directories are
2138also deleted.
2139c. Finding and Changing the Current Working Directory
2140It is unlikely that a web application will be able to perform all of its file
2141related tasks in a single directory. For this reason, it is vital to be able to both find out
2142the current working directory, and change to another directory from within a PHP
2143script.
2144The current working directory can be identified using the getCwd() function:
2145The current working directory can be changed using the chdir() function. chdir()
2146takes as the only argument the path of the new directory:
2147<?php
2148$result = mkdir ("directory", "0777");
2149?>
2150<?php
2151$result = rmdir("directory");
2152?>
2153<?php
2154$current_dir = getCwd();
2155echo "Current directory is $current_dir";
2156?>
2157<?php
2158$current_dir = getCwd();
2159echo "Current directory is $current_dir <br>";
2160mkdir ("temp");
2161chdir ("temp");
2162$current_dir = getCwd();
2163echo "Current directory is now $current_dir <br>";
2164?>
216596 [Web Application Development I-ITDB201]
2166d. Listing Files in a Directory
2167The files in a directory can be read using the PHP scandir() function which takes
2168two arguments. The first argument is the path the directory to be scanned. The second
2169optional argument specifies how the directory listing is to be sorted. If the argument is 1
2170the listing is sorted reverse-alphabetically. If the argument is omitted or set to 0 the list is
2171sorted alphabetically:
2172 Chapter Summary:
2173File handling is an important part of any web application. You often need to open and
2174process a file for different tasks. File is another way of saving data permanently as an alternative
2175to database. In many instances, files handling come in very handy when performing some
2176functions or transactions in a web application. In addition, managing and accessing directories is
2177also a common functionalities required in a lot of web applications.
2178Assignments:
2179Defining Features Matrix
2180Category: Classroom Assessment Technique
2181Suggested
2182duration:
218310-30 minutes or as an assignment
2184Intent: Enable students to identify what the significant features of ―Files and
2185Database‖ for data storage in a web application.
2186Implementation: 1. List the important characteristics of the “Files and Databaseâ€
2187as method of storing data in a web application.
21882. Generate a matrix. Create a table which shows the comparison
2189of the two.
2190<?php
2191$current_dir = getCwd();
2192echo "Current directory is now $current_dir";
2193$array = scandir(".", 1);
2194print_r($array);
2195?>
219697 [Web Application Development I-ITDB201]
2197Files vs Database Matrix
2198Files Database
2199Advantages Disadvantages Advantages Disadvantages
2200Laboratory Exercises:
2201Learning Outcome: At the end of this activity, the students should be able to:
2202a. Write PHP scripts that perform file handling functions.
2203b. Write PHP scripts that implement directory related functions.
2204Instruction: Perform the activities and save your files in the Web Server. Execute your scripts
2205and check if the output is correct.
22061. Design a web page using HTML5 forms that accepts user information (Name, mobile number
2207and country). When user submits the form, save the information into a file:user.text.
22082. Continue the exercise 1 and create a web page the retrieves/reads the information saved in the
2209file and output the information in the web page.
22103. Write a PHP script to count lines in a file.
2211Note : Store a text file name into a variable and count the number of lines of text it has.
22124. Write a PHP script which lists all files in directory.
22135. Write a PHP script to count the number of file in current directory.
22146. Write a PHP script to move on specific directory and count the number of file.
22157. Write a PHP scripts to delete all file in current directory. But before deleting, a confirmation
2216message must be displayed first asking the user to confirm the delete.
22178. Write a PHP script to get last modified information of a file.
2218Sample filename : php-basic-exercises.php
2219Sample Output : Last modified Monday, 09th June, 2014, 06:45am
222098 [Web Application Development I-ITDB201]
2221References:
2222[1]"Working with Directories in PHP - Techotopia", Techotopia.com, 2017. [Online].
2223Available: http://www.techotopia.com/index.php/Working_with_Directories_in_PHP.
2224[Accessed: 16-Nov- 2017].
2225[2]"PHP: fopen - Manual", Php.net, 2017. [Online]. Available:
2226http://php.net/manual/en/function.fopen.php. [Accessed: 16-Nov-2017].
2227[3]"PHP Tutorial - File Write", Tizag.com, 2017. [Online]. Available:
2228http://www.tizag.com/phpT/filewrite.php. [Accessed: 16-Nov-2017].
2229[4]"PHP: fopen - Manual", Php.net, 2017. [Online]. Available:
2230http://php.net/manual/en/function.fopen.php. [Accessed: 07- Mar- 2017].
2231[5]"Working with Files in PHP", SitePoint, 2017. [Online]. Available:
2232https://www.sitepoint.com/working-with-files-in-php/. [Accessed: 07- Mar- 2017].
2233[6]"PHP 5 File Open/Read/Close", W3schools.com, 2017. [Online]. Available:
2234https://www.w3schools.com/php/php_file_open.asp. [Accessed: 08- March- 2017].
223599 [Web Application Development I-ITDB201]
2236Chapter 6: FORMS AND DATA VALIDATIONS
2237 Objectives
2238At the end of this module, the students will be able to:
2239ï‚· Process form data using PHP.
2240ï‚· Enumerate the differences of HTTP methods.
2241ï‚· Validate forms using HTML and Javascript.
22426.1. PHP Forms
2243It‘s easy to process forms with PHP, as the form parameters are available in the
2244$_GET and $_POST arrays. There are many tricks and techniques for working with
2245forms.
2246The example below displays a simple HTML form with two input fields and a submit
2247button:
2248form.php
2249Example:
2250<html>
2251<body>
2252<form action="welcome.php" method="post">
2253Name: <input type="text" name="name"><br>
2254E-mail: <input type="text" name="email"><br>
2255<input type="submit">
2256</form>
2257</body>
2258</html>
2259100 [Web Application Development I-ITDB201]
2260Output:
2261Figure 6.1: Example HTML Form
2262When the user fills out the form above and clicks the submit button, the form data is sent
2263for processing to a PHP file named "welcome.php". The form data is sent with the HTTP
2264POST method. The figure below shows interaction of the form with the processing script.
2265Figure 6.2: HTML Form Submitting Data to a PHP Script
2266Figure 6.2 shows the form with example input.
2267Figure 6.2: Example HTML Form with User Input
2268form.php welcome.php
2269(Form Data)
2270HTTP Method
2271101 [Web Application Development I-ITDB201]
2272To display the submitted data you could simply echo all the variables. The
2273"welcome.php" looks like this:
2274welcome.php
2275The output could be something like this:
2276Figure 6.3: Retrieve User Input and Output in Web Page
2277The same result could also be achieved using the HTTP GET method:
2278and "welcome_get.php" looks like this:
2279<html>
2280<body>
2281Welcome <?php echo $_POST["name"]; ?><br>
2282Your email address is: <?php echo $_POST["email"]; ?>
2283</body>
2284</html>
2285Example:
2286<html>
2287<body>
2288<form action="welcome_get.php" method="get">
2289Name: <input type="text" name="name"><br>
2290E-mail: <input type="text" name="email"><br>
2291<input type="submit">
2292</form>
2293</body>
2294</html>Run example »
2295102 [Web Application Development I-ITDB201]
2296The code above is quite simple. However, the most important thing is
2297missing. You need to validate form data to protect your script from malicious code.
22986.2. HTTP Methods and Retrieving submitted data
2299The HTML form tag has two important attributes that enables the processing of submitted
2300form data:
2301a. Action-The action attribute specifies where to send the form-data when a form is
2302submitted.
2303b. Method - The method attribute specifies how to send form-data (the form-data is sent
2304to the page specified in the action attribute).
2305Example: <form action="insert.php" method="post">
2306There are two HTTP methods that a client can use to pass form data to the server: GET
2307and POST. The method that a particular form uses is specified with the method attribute to
2308the form tag. In theory methods are case-insensitive in the HTML, but in practice some
2309broken browsers require the method name to be in all uppercase.
2310a. The GET Method
2311Before the browser sends the information, it encodes it using a scheme called URL
2312encoding. In this scheme, name/value pairs are joined with equal signs and different pairs
2313are separated by the ampersand.
2314name1=value1&name2=value2&name3=value3
2315Spaces are removed and replaced with the + character and any other nonalphanumeric
2316characters are replaced with a hexadecimal values. After the information is encoded it is
2317sent to the server.
2318The GET method sends the encoded user information appended to the page request. The
2319page and the encoded information are separated by the ? character.
2320http://www.test.com/index.htm?name1=value1&name2=value2
2321<html>
2322<body>
2323Welcome <?php echo $_GET["name"]; ?><br>
2324Your email address is: <?php echo $_GET["email"];
2325?>
2326</body>
2327</html>
2328103 [Web Application Development I-ITDB201]
2329• The GET method produces a long string that appears in your server logs, in the
2330browser's Location: box.
2331• The GET method is restricted to send up to 1025 characters only.
2332• Never use GET method if you have password or other sensitive information to be
2333sent to the server.
2334• GET can't be used to send binary data, like images or word documents, to the server.
2335• The data sent by GET method can be accessed using QUERY_STRING environment
2336variable.
2337• The PHP provides $_GET associative array to access all the sent information using
2338GET method.
2339b. The POST Method
2340The POST method transfers information via HTTP headers. The information is
2341encoded as described in case of GET method and put into a header called
2342QUERY_STRING.
2343• The POST method does not have any restriction on data size to be sent.
2344• The POST method can be used to send ASCII as well as binary data.
2345• The data sent by POST method goes through HTTP header so security depends on
2346HTTP protocol. By using Secure HTTP you can make sure that your information is
2347secure.
2348• The PHP provides $_POST associative array to access all the sent information using
2349POST method.
2350c. The $_REQUEST variable
2351The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and
2352$_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies.
2353The PHP $_REQUEST variable can be used to get the result from form data sent with
2354both the GET and POST methods.
23556.3. HTML5 Validation
2356Validations can be performed on the server side or on the client side ( web browser). The
2357user input validation take place on the Server Side during a post back session is called Server
2358Side Validation and the user input validation take place on the Client Side (web browser) is
2359called Client Side Validation.
2360Since the initial time of web designing, we have been in compulsion to validate
2361our form in terms of preventing spammers or for getting appropriate input from users.
2362104 [Web Application Development I-ITDB201]
2363Before the development of HTML5 we were using the JavaScript or the other Back End
2364language to validate our form. But the HTML5 has changed the entire things in programming
2365technology. For validating a form a library (H5F) has been introduced to giving better
2366performance with HTML5.
2367a. Input Text Field Validation – to validate a text field to check a required field is
2368simply by putting the required attribute as show in the code below.
2369Output:
2370When user clicks the submit button and no input is given in the required text field and error
2371message will be displayed.
2372Figure 6.4: Input Text Field Validation
2373<fieldset>
2374<legend>Input Text Field Validation</legend>
2375<ol>
2376<li>
2377<label for="firstname">First Name *</label>
2378<input type="text" id="firstname" name="firstname" placeholder="First
2379Name" required />
2380</li>
2381<li>
2382<label for="lastname">Last Name *</label>
2383<input type="text" id="lastname" name="lastname" placeholder="Last
2384Name" required />
2385</li>
2386</ol>
2387</fieldset>
2388<input type="submit" value="Sign up" />
2389105 [Web Application Development I-ITDB201]
2390b. EMAIL AND URL VALIDATION
2391Figure 6.5: Email Validation
2392Figure 6.6: URL Validation
2393<fieldset>
2394<legend>Email and URL Validation</legend>
2395<ol>
2396<li>
2397<label for="email">Email *</label>
2398<input type="email" id="email" name="email" placeholder="e.g.
2399swapnil@example.com" title="Please enter a valid email" required />
2400<p class="validation01">
2401<span class="invalid">Please enter a valid email address e.g.
2402swapnil@example.com</span>
2403<span class="valid">Your email address is now valid</span>
2404</p>
2405</li>
2406<li>
2407<label for="url">Website *</label>
2408<input type="url" name="url" id="url"
2409placeholder="e.g. http://www.html5andcss3.org" title="Please enter a
2410valid URL" required />
2411<input type="submit" value="Sign up" />
2412</fieldset>
2413106 [Web Application Development I-ITDB201]
2414c. Mobile or Phone Validation
2415Figure 6.7: Phone Validation
24166.4. JavaScript Validation
2417JavaScript Form Validation
2418HTML form validation can be done by JavaScript.
2419If a form field (fname) is empty, this function alerts a message, and returns false, to prevent
2420the form from being submitted:
2421<fieldset>
2422<legend>Mobile or Phone Number Validation</legend>
2423<ol>
2424<li>
2425<label for="tel">Mobile *</label>
2426<input type="tel" id="tel" name="tel" pattern="d{10}"
2427placeholder="Please enter a ten digit phone number" required />
2428<p class="validation01">
2429<span class="invalid">No spaces or brackets e.g.
24309999999999</span>
2431<span class="valid">Your mobile number is valid</span>
2432</p>
2433</li>
2434</ol>
2435</fieldset>
2436<input type="submit" value="Sign up" />
2437107 [Web Application Development I-ITDB201]
2438The function can be called when the form is submitted:
2439Output:
2440When user clicks the button without entering value on the text field, the alert message will be
2441displayed.
2442Figure 6.8: JavaScript Required Field Validation
2443<!Doctype html>
2444<html>
2445<script type="text/javascript">
2446function validateForm() {
2447 var x = document.forms["myForm"]["fname"].value;
2448 if (x == "") {
2449 alert("Name must be filled out");
2450 return false;
2451 }
2452}
2453</script>
2454<body>
2455<form name="myForm" action="/action_page_post.php" onsubmit="return
2456validateForm()" method="post">
2457Name: <input type="text" name="fname">
2458<input type="submit" value="Submit">
2459</form>
2460</body>
2461</html>
2462function validateForm() {
2463 var x = document.forms["myForm"]["fname"].value;
2464 if (x == "") {
2465 alert("Name must be filled out");
2466 return false;
2467 }
2468}
2469108 [Web Application Development I-ITDB201]
2470 Chapter Summary:
2471When building web applications, it is important you take security seriously,
2472especially when it has to do with collecting data from users. These user inputs are collected
2473using forms and retrieved by using HTTP methods and processed by the server side scripts.
2474However, before these data are processed in the server, validations in the client side should
2475be performed first to prevent malicious and incorrect data. When it comes to validating form
2476values, it can be done on the client-side (web browser) and on the server-side (using your
2477preferred server-side language). This client-side validation can be implemented using
2478HTML5 and JavaScript.
2479Assignments:
24801. Give the three types of HTML5 constraint validation.
2481_______________________________________________________________________
2482_______________________________________________________________________
2483_______________________________________________________________________
2484_______________________________________________________________________
2485_______________________________________________________________________
24862. Different client-side validation versus server-side validation.
2487_______________________________________________________________________
2488_______________________________________________________________________
2489_______________________________________________________________________
2490_______________________________________________________________________
2491_______________________________________________________________________
24923. Why is it important to have client-side validation aside from server-side validation?
2493_______________________________________________________________________
2494_______________________________________________________________________
2495_______________________________________________________________________
2496_______________________________________________________________________
2497_______________________________________________________________________
2498109 [Web Application Development I-ITDB201]
2499Laboratory Exercises:
2500Learning Outcome: At the end of this activity, the students should be able to:
2501a. Create HTML forms and implement client side validation.
2502b. Use JavaScript to validate forms.
25031. Create a page that uses HTML forms to allow users to input marks and validate that marks
2504inputted should be from 1 to 100 only.
25052. Create a page uses a <SELECT> or a drop down box to display the courses. Validate that the
2506user selected an option from the drop down box when the user clicks the submit button.
25073. Create a page that accepts user comments using a textarea. Make the text area a required
2508field and display error message when no comments are given when submit is clicked.
25094. Create a student registration form as shown and provide the appropriate validation for each
2510information.
25115. Write a JavaScript function that checks the following: Password must be entered and must be
2512longer than 4 characters.
2513110 [Web Application Development I-ITDB201]
2514References:
2515[1]"PHP: Form", php.net, 2016. [Online]. Available: http://php.net/manual/en/tutorial.forms.php.
2516[Accessed: 19- Nov- 2016].
2517[2] "PHP: Form", W3schools.com, 2016. [Online]. Available:
2518https://www.w3schools.com/php/php_forms.asp. [Accessed: 19- Nov- 2016].
2519[3] "PHP: Form", tizag.com, 2016. [Online]. Available:
2520http://www.tizag.com/phpT/examples/formex.php. [Accessed: 19- Nov- 2016].
2521https://www.w3schools.com/js/js_validation.asp
2522[4]"JavaScript Form Validation", W3schools.com, 2017. [Online]. Available:
2523https://www.w3schools.com/js/js_validation.asp. [Accessed: 07- Mar- 2017].
2524111 [Web Application Development I-ITDB201]
2525Chapter 7: INTRODUCTION TO MYSQL
2526 Objectives
2527At the end of this module, the students will be able to:
2528ï‚· Create and manage MySQL databases using phpMyadmin.
2529ï‚· Export and import MySQL databases.
2530ï‚· Identify the different data types in MySQL.
2531ï‚· Designate the appropriate data type for a field.
25327.1 MySQL Overview
2533MySQL is a database management system based on Structured Query Language
2534(SQL) which is used in web applications. It consists of the server, utility programs that
2535help in the administration of MySQL databases and supporting software. The server
2536handles all database instructions, such as creating, accessing or changing data. To interact
2537with a database you send a message to the server. It is used commonly in websites, where
2538there are large databases of data to be managed.
25397.2 Advantages of MySQL
2540It's easy to use: While a basic knowledge of SQL is required—and most relational
2541databases require the same knowledge—MySQL is very easy to use. With only a few
2542simple SQL statements, you can build and interact with MySQL.
2543It's secure: MySQL includes solid data security layers that protect sensitive data from
2544intruders. Rights can be set to allow some or all privileges to individuals. Passwords are
2545encrypted.
2546It's inexpensive: MySQL is included for free with NetWare® 6.5 and available by free
2547download from MySQL Web site.
2548It's fast: In the interest of speed, MySQL designers made the decision to offer fewer
2549features than other major database competitors, such as Sybase* and Oracle*. However,
2550112 [Web Application Development I-ITDB201]
2551despite having fewer features than the other commercial database products, MySQL still
2552offers all of the features required by most database developers.
2553It's scalable: MySQL can handle almost any amount of data, up to as much as 50 million
2554rows or more. The default file size limit is about 4 GB. However, you can increase this
2555number to a theoretical limit of 8 TB of data.
2556It manages memory very well: MySQL server has been thoroughly tested to prevent
2557memory leaks.
25587.3 Communicating with MySQL Server
2559All your interaction with the database is accomplished by passing messages to the
2560MySQL server. The MySQL server must be able to understand the instructions that you
2561send it. You communicate using Structured Query Language (SQL), which is a standard
2562computer language understood, at least in some form, by most database management
2563systems.
2564You can send a SQL query to MySQL several ways. Here are three methods of sending
2565queries:
2566a. Command Line
2567You use your command line to connect to the mysql server and build SQL statement
2568and send it to the MySQL server.
2569shell> mysql -h host -u user -p
2570Enter password: ********
2571b. MySQL GUI Tools – MySQL Workbench
2572MySQL Workbench is a unified visual tool for database architects, developers, and
2573DBAs. MySQL Workbench provides data modeling, SQL development, and
2574comprehensive administration tools for server configuration, user administration,
2575backup, and much more. You can download the application here in this address:
2576http://www.mysql.com/products/workbench/
2577113 [Web Application Development I-ITDB201]
2578Figure 7.1: MySQL Workbench
2579c. Web-based Client Tools - phpMyAdmin
2580phpMyAdmin is a free and open source tool written in PHP intended to handle
2581the administration of MySQL with the use of a web browser. Frequently used
2582operations (managing databases, tables, columns, relations, indexes, users,
2583permissions, etc) can be performed via the user interface, while you still have the
2584ability to directly execute any SQL statement. You can download the application
2585here in this address: https://www.phpmyadmin.net/
2586114 [Web Application Development I-ITDB201]
2587Figure 7.2: phpMyAdmin
25887.4 Building SQL Queries
2589SQL is almost English put together into strings of words that sound similar to English
2590sentences. In general, you do not need to understand any technical language to write SQL
2591queries that work.
2592The first word of each query is its name, which is an action word that tells MySQL
2593what you want to do. The query name is followed by words and phrases, some required
2594and some optional, that tell MySQL how to perform the action. For instance, you always
2595need to tell MySQL what to create, and you always need to tell it which table to insert
2596data into or to select data from.
25977.5 Creating a New Database
2598Consider the following table. We shall be creating corresponding table out from this.
2599Figure 7.3: Example Table Structure
2600115 [Web Application Development I-ITDB201]
2601To create a database click the New, type the name of the database and click the CREATE
2602button.
2603Figure 7.4: Creating a MySQL Database
26047.6 Creating a Table
2605To create table, click the database you created earlier, type the name of the table in
2606the textbox. Input the number of columns and then click GO button.
2607Figure 7.4: Creating a Table
26087.7 Set the Field Name
2609As a practice, it is good to use lower case in field names. Also, make sure that there
2610are no spaces in your field names. Chose the appropriate type and type the length of the
2611field. Then set your primary key. As noted, you cannot represent your foreign key in
2612myPHPAdmin so leave it as it is.
2613116 [Web Application Development I-ITDB201]
2614Figure 7.5: Adding Field/Column
26157.8 Table Operations
2616Below summarizes the different operations you can do with your tables.
2617Figure 7.6: Table Operations
2618117 [Web Application Development I-ITDB201]
26197.9 Exporting and Importing MySQL database
2620To export and import MySql Database do the following:
2621a. Exporting
26221. Select the database you want to export.
2623Figure 7.7: Exporting Database
26242. Click the EXPORT in your menu bar.
2625Figure 7.8: Exporting Database to .sql File
26263. Click GO. The .sql file will be exported in your DOWNLOAD folder.
2627Browse and copy it in your desired storage location.
2628b. Importing
2629To import the database, you just need to click IMPORT from your menu bar.
2630Then browse your computer to choose the file. Click go.
2631118 [Web Application Development I-ITDB201]
2632Figure 7.9: Export Database as .sql File
26337.10 Dropping a Database
2634To delete a database, go to OPERATION and clik Drop the database.
2635There are other operations that you can do also in this tab like copying database,
2636renaming etc.
2637Figure 7.9: Dropping a Database
2638119 [Web Application Development I-ITDB201]
2639 Chapter Summary:
2640One component of a web application is the database which stores data required by
2641the application. Databases stores information such as customer information, user login,
2642shopping cart information, bank account information and many other kinds of
2643information that ranges from simple to complex and most especially sensitive
2644information. For this reason, databases must be designed properly and provided with
2645utmost security. MySQL is an open source relational database management system that
2646provides features for building a scalable and secured web application.
2647Assignments:
2648d. The table below shows some examples of fields/column names in a database table. You
2649have to identify what is the most appropriate MySql data type for the specific field.
2650Field/Column Name Data Type
2651credit_card_number
2652profile_image
2653video
2654flight_number
2655course_description
2656user_comments
2657car_model_name
2658country
2659encrypted_password
2660atm_pin_code
2661120 [Web Application Development I-ITDB201]
2662e. In most web application, database is considered as the most crucial and critical part. Do
2663you agree or not? Justify your answer.
2664_______________________________________________________________________
2665_______________________________________________________________________
2666_______________________________________________________________________
2667_______________________________________________________________________
2668_______________________________________________________________________
2669Laboratory Exercises:
2670Learning Outcome: At the end of this activity, the students should be able to:
2671a. Create MySql database and tables.
2672b. Export and import databases.
2673Perform the following instructions.
26741. Create a database student.
26752. Create the table student_info with the following structure.
2676Field Name Data Type Constraint
2677student_id Varchar(10) Primary key
2678student_name Varchar(60) Not Null
2679gender Varchar(6) Not Null
2680department Varchar(30) Not Null
2681email Varchar(30) Not Null
2682password Varchar(64) Not Null
2683birthdate Date Not Null
26843. Export the student database and save as student_db.sql.
26854. Drop the student database.
26865. Import the student_db.sql to recreate the database.
2687121 [Web Application Development I-ITDB201]
2688References:
2689[1]"What is MySQL? - Computer Business Review", Computer Business Review, 2017.
2690[Online]. Available: http://www.cbronline.com/news/enterprise-it/software/what-is-mysql4973424.
2691[Accessed: 05- Dec- 2016].
2692[2]"Novell Doc: NW 6.5 SP8: Novell MySQL Administration Guide - Benefits of MySQL",
2693Novell.com, 2017. [Online]. Available:
2694http://www.novell.com/documentation/nw65/web_mysql_nw/data/aj5bj52.html. [Accessed:
269505- Dec- 2016].
2696[3]p. contributors, "phpMyAdmin", phpMyAdmin, 2017. [Online]. Available:
2697https://www.phpmyadmin.net/. [Accessed: 05- Dec- 2016].
2698[4]"MySQL :: MySQL Workbench", Mysql.com, 2017. [Online]. Available:
2699http://www.mysql.com/products/workbench/. [Accessed: 08- Mar- 2017].
2700122 [Web Application Development I-ITDB201]
2701Chapter 8: DATABASE MANIPULATION using PHP
2702 Objectives
2703At the end of this module, the students will be able to:
2704ï‚· Write PHP scripts that can connect to a MySQL DBMS.
2705ï‚· Write PHP scripts that execute INSERT, SELECT, DELETE and UPDATE
2706SQL Queries.
2707ï‚· Differentiate POST and GET methods.
2708ï‚· Write PHP scripts that retrieves submitted form data.
2709ï‚· Retrieve data from a MySQL database and display in a web browser formatted
2710in Bootstrap Table.
2711ï‚· Automatically redirect a page using PHP.
2712ï‚· Count records from a query results.
2713Overview
2714With PHP, you can connect to and manipulate databases. PHP combined with
2715MySQL are cross-platform (you can develop in Windows and serve on a Unix platform).
2716Using PHP and MySql a secured and scalable database-driven web application can be
2717developed.
27188.1. Choosing an API to Connect to MySQL (mysql, mysqli and PDO extensions)
2719PHP 5 and later can work with a MySQL database using:
2720a. MySQLi extension (the "i" stands for improved). Characteristics of MySQLi
2721are:
2722a. Work only with MySQL databases,
2723b. Object-oriented but also offer procedural API.
2724c. Supports Prepared Statements
2725123 [Web Application Development I-ITDB201]
2726b. PDO (PHP Data Objects)
2727PDO will work on 12 different database systems. Therefore is good option if
2728the project requires using different kinds of databases since only the connection
2729string and a few queries needs to be changed. With MySQLi, you will need to
2730rewrite the entire code - queries included.
2731Earlier versions of PHP used the MySQL extension. However, this extension was
2732deprecated in 2012.
27338.2. CONNECTING TO MySQL DBMS
2734Before you can manipulate the database, a connection to the MySQL Server needs to
2735be established first. MySQLi supports both object-oriented and procedural
2736approaches. The script below establishes a connection to the database by
2737instantiating a new mysqli object.
2738Database connection script using MySQLi Object-Oriented approach
2739dbconnect.php
27408.3. Example: Student Information System
2741For discussion purposes, we will develop a basic web application that implements
2742that CRUD (Create-Read-Update-Delete) functionality. Any application from small to
2743large has functionalities that are derived from this basic CRUD concept implemented in
2744varied ways. The application that we will develop is a Student Information System.
2745<?php
2746$hostname = "localhost"; //MySQL hostname
2747$username = ""; //MySQL username
2748$password=""; //MySQL password
2749$databasename="student"; //MySQL database name
2750//connect to the database
2751$db=new mysqli($hostname,$username,$password, $databasename);
2752// If connection was not successful, handle the error
2753if($db->connect_errno > 0){
2754 die('Unable to connect to database '.$db->connect_error);
2755}
2756echo 'Connected successfully';
2757?>
2758124 [Web Application Development I-ITDB201]
2759The following are the functionalities for the Admin User:
2760a. Student Registration/Create Student
2761b. View All Students
2762c. Update Student
2763d. Delete Student
2764a. User Interface for Student Registration
2765Using Bootstrap, we create the student registration form with navigation bar as
2766shown in the figure.
2767register.php
2768Figure : User Interface Design for Student Registration
2769<input type=â€text†name=â€student_idâ€>
2770<input type=â€text†name=â€student_nameâ€>
2771<input type=â€radio†name=â€genderâ€
2772value=â€Maleâ€>
2773<input type=â€radio†name=â€genderâ€
2774value=â€Femaleâ€>
2775<input type=â€email†name=â€emailâ€>
2776<input type=â€password†name=â€passwordâ€>
2777<input type=â€date†name=â€birthdateâ€>
2778<select name=â€departmentâ€>
2779 <option value=â€ITâ€>IT</option>
2780 <option value=â€ITâ€>Business</option>
2781 <option value=â€ITâ€>Engineering</option>
2782 <option value=â€ITâ€>ELC</option>
2783</select>
2784<input type=â€submit†name=â€registerâ€
2785value=â€Registerâ€>
2786<input type=â€reset†name=â€cancel†value=â€Cancelâ€>
2787<FORM action=â€add_student.php†method=â€POSTâ€>
2788125 [Web Application Development I-ITDB201]
2789<div class="row-fluid">
2790<div class="col-md-6 col-md-offset-3">
2791<h1>Student Registration Form</h1>
2792<form class="form-horizontal" action="add_student.php" method="post">
2793 <div class="form-group">
2794 <label for="student_id">Student ID:</label>
2795 <input type="text" class="form-control" name="student_id" required>
2796 </div>
2797 <div class="form-group">
2798 <label for="student_name">Student Name:</label>
2799 <input type="text" class="form-control" name="student_name" required>
2800 </div>
2801 <div class="form-group">
2802 <label for="gender">Gender:</label>
2803 <input type="radio" name="gender" value="Male">Male
2804 <input type="radio" name="gender" value="Female">Female
2805 </div>
2806 <div class="form-group">
2807 <label for="department">Department:</label>
2808<select name="department">
2809<option value="IT">IT</option>
2810<option value="Business">Business</option>
2811<option value="Engineering">Engineering</option>
2812<option value="ELC">English Language Center</option>
2813</select>
2814 </div>
2815126 [Web Application Development I-ITDB201]
2816 <div class="form-group">
2817 <label for="email">Email:</label>
2818 <input type="email" class="form-control" name="email" required>
2819 </div>
2820 <div class="form-group">
2821 <label for="password">Password:</label>
2822 <input type="password" class="form-control" name="password" required>
2823 </div>
2824 <div class="form-group">
2825 <label for="birthdate">Birthdate:</label>
2826 <input type="date" class="form-control" name="birthdate" >
2827 </div>
2828<input type="submit" class="btn btn-info" name="register" value="Register">
2829 <input type="reset" class="btn btn-default" name="cancel" value="Cancel">
2830</form>
2831</div>
2832</div>
2833register.php
2834127 [Web Application Development I-ITDB201]
28358.4. Executing SQL Queries
2836The mysqli_query() is a PHP function that performs a query on the database. The
2837function Returns FALSE on failure. For successful INSERT, SELECT, SHOW,
2838DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result
2839object. The mysqli_result object represents the result set obtained from a query
2840against the database. In the script below, the result set is stored in the variable
2841$result. The code below shows an example of using the mysqli_query() function
2842to execute a SELECT statement.
28438.5. Adding Records
2844When implementing an add/insert transaction to a database, the inputted/selected
2845values from the form can be retrieved using FORM method and processed by the
2846server side script.
2847The following basic steps may be followed in Adding/inserting records to a database.
2848a. Design the user interface using HTML5 and CSS, implement client-side
2849validation using HTML5 and/or JavaScript. Make sure to name the input types
2850properly to reflect the data each will accept from user.
2851b. Create the database and database table for saving the data using the selected
2852DBMS.
2853<?php
2854include 'dbconnect.php'; //include the file for database server connection
2855$sql=â€SELECT * FROM student_infoâ€;
2856if(!$result = $db->query($sql)){ //execute the SQL query
2857 die('There was an error running the query ' .$db->error);
2858}
2859?>
2860128 [Web Application Development I-ITDB201]
2861c. Create a PHP Script which includes the database connection file and the
2862INSERT SQL Query. The figure below show the relationship of the different
2863components of a web application. It shows that from the user interface which
2864accepts the input from the user, the form data is passed to a server side script
2865using FORM Action and Method attributes. Then the server side script
2866processes the form and connects to the database and executes the INSERT
2867statement.
2868Figure:
2869User Interface Design
2870(register.php)
2871HTML5+CSS
2872JavaScript
2873Server-Side Script
2874(addstudent.php)
2875POST/GET
2876Form Variables
2877(PHP)
2878MySQL Database
2879(student database)
2880Server-Side Script
2881(dbconnect.php)
2882Database
2883Connection
2884Variable
2885Database Tables
2886(student_info,
2887lecturer_info,
2888courses)
2889Include the database
2890connection script
2891FORM
2892ACTION
2893and
2894METHOD
2895Connect
2896to
2897database
2898and save
2899in table
2900129 [Web Application Development I-ITDB201]
2901d. User Interface with User Input Data
2902The figure is an example for the user interface for the Student Registration
2903Form.
2904Figure : Student Registration Form with User Input
2905e. Table Structure viewed in phpMyAdmin
2906Using phpMyAdmin, create the database and the table student_info.
2907Database Name: student
2908Table name: student_info
2909130 [Web Application Development I-ITDB201]
2910f. INSERT SQL QUERY
2911The action and method attributes of the FORM tag are the two important attributes.
2912The action attribute specifies the script that will process the submitted form data
2913using the method specified. Example:
2914<form class="form-horizontal" action="add_student.php" method="post">
2915INSERT SQL QUERY:
2916“INSERT INTO table_name(column1, column2,…) VALUES(value1, value2,…)â€
2917PHP Script for inserting record to the database.
2918addstudent.php
2919Figure : Record successfully inserted in the database table
2920<?php
2921include 'dbconnect.php'; //include the file for database server connection
2922if(isset($_POST['register'])){
2923$studentid=$_POST['studentid'];
2924$studentname = $_POST['studentname'];
2925$gender = $_POST['gender'];
2926$department = $_POST['department'];
2927$email = $_POST['email'];
2928$password=hash ('sha256',$_POST['password']);
2929$birthdate=$_POST['birthdate']);
2930$sql="INSERT INTO student_info (studentid, studentname, gender,
2931department, email, password, birthdate) VALUES
2932('$studentid','$studentname','$gender','$department',
2933'$email','$password', '$birthdate')";
2934if(!$result = $db->query($sql)) {
2935 die ('There was an error running the query ' .$db->error);
2936}
2937header("Location:view_students.php");//redirect to view_students.php
2938}
2939?>
2940131 [Web Application Development I-ITDB201]
29418.6. Redirecting a to another Page
2942The header() function sends a raw HTTP header to a client. The header() must be
2943called before any actual output is sent to the browser.
2944Example:
2945header("Location:view_students.php");//redirect to view_students.php
29468.7. Retrieving Records
2947The SELECT statement is used to select data from one or more tables:
2948SELECT column_name(s) FROM table_name
2949or we can use the * character to select ALL columns from a table
2950Example:
2951SELECT * FROM student_info;
29528.8. Fetching Rows
2953The mysqli_fetch_array() function fetches a result row as an associative, a
2954numeric array, or both. The function accepts two parameters:
2955a. result -A result set identifier returned by mysqli_query().
2956b. result type - This optional parameter is a constant indicating what type of array
2957should be produced from the current row data. The possible values for this
2958parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or
2959MYSQLI_BOTH.
29608.9. Retrieving and Displaying Records in Bootstrap Tables
2961Tables are an easy and organized approach of displaying records retrieved from the
2962database. The following script is an example script that retrieves all records from the
2963student_info database and displays the records in a Bootstrap table.
2964132 [Web Application Development I-ITDB201]
2965Retrieving Records and Displaying in Bootstrap Table
2966view_students.php
2967<div class="table-responsive table-hover table-striped">
2968 <table class="table">
2969 <thead>
2970 <tr>
2971 <th>#</th>
2972 <th>Student ID</th>
2973 <th>Student Name</th>
2974 <th>Gender</th>
2975 <th>Department</th>
2976 <th>Email</th>
2977 <th>Birthdate</th>
2978<th colspan="2">Actions</th>
2979 </tr>
2980 </thead>
2981 <tbody>
2982 <?php
2983 include 'dbconnect.php';
2984 $sql="SELECT * FROM student_info";
2985 if(!$result = $db->query($sql)){ //execute the SQL query
2986 die('There was an error running the query ' .$db->error);
2987 }
2988 $count=1;
2989while($row =$result->fetch_array(MYSQL_BOTH)){
2990echo"<tr>";
2991echo"<td>$count</td>";
2992echo"<td>{$row['student_id']}</td>";
2993echo"<td>{$row['student_name']}</td>";
2994echo"<td>{$row['gender']}</td>";
2995echo"<td>{$row['department']}</td>";
2996echo"<td>{$row['email']}</td>";
2997echo"<td>{$row['birthdate']}</td>";
2998echo"</tr>";
2999$count++;
3000}
3001 ?>
3002</tbody>
3003</table>
3004</div>
3005133 [Web Application Development I-ITDB201]
3006Figure : View Students Output
30078.10. DELETING RECORDS
3008Deleting records from the database is implemented using the DELETE SQL Query.
3009DELETE SQL query:
3010"DELETE FROM table_name WHERE column_name=value";
3011The WHERE clause specifies which record or records that should be deleted.
3012Otherwise if not specified, all records in the table will be deleted.
3013On mouse over in the hyperlink, the following code retrieves the student_id on the
3014current row and passes it in the URL.
3015a. Retrieving the variables passed via the URL:
3016Data passed via the URL can be retrieved using the $_GET which is a superglobal
3017array of variables passed to the current script via the URL parameters.
3018Figure : Hyperlink to retrieve row values and pass to the URL
3019echo"<td><a
3020href='delete_student.php?id={$row['student_id']}'>Delete</a></td>"
3021;
3022134 [Web Application Development I-ITDB201]
3023The id variable in the URL contains the current row‘s student_id on mouse over
3024which is accessible in the delete_student.php.
3025PHP script for deleting record
3026delete_student.php
3027b. CONFIRM DELETE
3028Before deleting any record or records from the database, it is good practice to display
3029a confirmation message box. The JavaScript confirm() function may be used.
3030echo"<td><a href='delete_student.php?id={$row['student_id']}' onclick=\"return
3031confirm('Are you sure?');\">Delete</a></td>";
3032Figure : Confirm Box on Delete
30338.11. UPDATING RECORDS
3034Using the same method with implementing the delete, the current row‘s
3035primary key can be passed via the URL and retrieved in the
3036update_student_form.php .
3037<?php
3038include 'dbconnect.php';
3039if(isset($_GET['id'])){
3040 $id = $_GET['id']; //retrieve the value of the id from URL
3041$sql ="DELETE FROM student_info WHERE student_id='{$id}'";
3042if(!$result = $db->query($sql)){
3043 die('There was an error running the query '.$db->error);
3044}
3045header("Location:display_students.php");
3046}
3047?>
3048echo"<td><a
3049href='update_student_form.php?id={$row['student_id']}'>Update</a></td>
3050";
3051135 [Web Application Development I-ITDB201]
3052UPDATE SQL query:
3053"UPDATE table_name SET
3054column_name=value,
3055column_name=value,…
3056WHERE column_name=value"
3057a. Update Student User Interface
3058In the user interface for update student, the FORM action attribute specified is
3059the update_student.php which is responsible for retrieving the values from the
3060form and executing the UPDATE SQL Query statement.
3061Figure: Update User Interface and Server Side Script
3062User Interface Design
3063(update_student_form.php)
3064Server-Side Script
3065update_student.php
3066FORM ACTION
3067136 [Web Application Development I-ITDB201]
3068update_student_form.php
3069Figure : User Interface of Update Student with Values
3070137 [Web Application Development I-ITDB201]
3071b. Update Student Code
3072update_student.php
30738.12. COUNTING RECORDS
3074The mysqli_num_rows() function returns the number of rows in a result set.
3075Syntax: mysqli_num_rows(result);
3076Parameter Description
3077result Required. Specifies a result set identifier returned by mysqli_query(),
3078mysqli_store_result() or mysqli_use_result().
3079<?php
3080include 'dbconnect.php';
3081if(isset($_GET['id'])){
3082 $id=$_GET['id'];
3083$studentname = $_POST['student_id];
3084$studentname = $_POST['student_name'];
3085$gender = $_POST['gender'];
3086$department = $_POST['department'];
3087$email = $_POST['email'];
3088$password=$_POST['password'];
3089$birthdate=$_POST['birthdate'];
3090$sql="UPDATE student_info SET
3091student_id='$studentname',
3092student_name='$studentname',
3093gender='$gender',
3094department='$department',
3095email='$email',
3096password='$password',
3097birthdate='$birthdate' WHERE student_id={$id}";
3098if (!$result=$db->query($sql)) {
3099 die('Invalid query: '.$db->error);
3100}
3101header("Location:view_students.php");
3102}
3103?>
3104138 [Web Application Development I-ITDB201]
3105a. PHP CODE FOR COUNTING RECORDS
3106view_students.php
3107Figure : View Students Record Count
3108<?php
3109$sql="SELECT * FROM student_info";
3110if(!$result = $db->query($sql)){ //execute the SQL query
3111die('There was an error running the query ' .$db->error);
3112}
3113$num_rows=$result->num_rows;
3114echo "<h1>There are $num_rows record(s).</h1>";
3115?>
3116139 [Web Application Development I-ITDB201]
3117 Chapter Summary:
3118PHP is one of the popular scripting language for web development. It is free, open source
3119and server-side (the code is executed on the server). MySQL is a Relational Database
3120Management System (RDBMS) that uses Structured Query Language (SQL) like PHP it
3121is also free and open source. The combination of PHP and MySQL allows the
3122development of small applications to large applications.
3123Assignments:
31241. Enumerate the differences of the POST and GET method.
3125_______________________________________________________________________
3126_______________________________________________________________________
3127_______________________________________________________________________
3128_______________________________________________________________________
3129_______________________________________________________________________
31302. Which FORM method is best to use for actions that requires submitting sensitive or important
3131information to the server? Explain why.
3132_______________________________________________________________________
3133_______________________________________________________________________
3134_______________________________________________________________________
3135_______________________________________________________________________
3136_______________________________________________________________________
31373. List at least 5 examples of new database technologies and tools.
3138_______________________________________________________________________
3139_______________________________________________________________________
3140_______________________________________________________________________
3141_______________________________________________________________________
3142_______________________________________________________________________
3143140 [Web Application Development I-ITDB201]
3144Laboratory Exercises:
3145Learning Outcome: At the end of this activity, the students should be able to:
3146a. Write PHP scripts that perform transactions that interact with the database.
3147b. Design responsive web pages using Bootstrap and integrate PHP scripts to
3148display output using Bootstrap components.
3149Instruction: Using the example application discussed in this chapter, implement the following
3150functionalities:
31511. Check for existing student ID. User registers and submits the form; your script
3152should check if the student ID already exists the database. If such ID exist or has
3153already been registered in the system, display a message saying that the ID already
3154exists.
31552. Search student. Implement the search functionality by providing two search options:
3156Search by ID and Search by Student Name. If the searched keyword matches any
3157record/s in the database, display the results and also count the number of results.
31583. User Login. Design a user login page where users will login using their email and
3159password. If login is successful, redirect to the view_students.php page, if not
3160redirect back to the login page and display error message.
31614. Create table for course. Create a new table in MySql named course. Use the
3162following table structure:
3163Field Name Data Type Constraint
3164course_id Int Primary key, auto
3165increment
3166course_Code Varchar(15) Not Null
3167course_description Text Not Null
3168lecture_hrs Int
3169theory_hrs Int
31705. CRUD for Lecturers. Write PHP scripts that will manage the lecturer table.
3171Implement the Create/Add Lecturer, List /Read all Lecturers, Update Lecture and
3172Delete Lecturer.
3173141 [Web Application Development I-ITDB201]
3174References:
3175[1]"'MySQLi' for Beginners - Codular", Codular.com, 2017. [Online]. Available:
3176http://codular.com/php-mysqli. [Accessed: 26- Feb- 2017].
3177[2]"PHP: MySQL Database", W3schools.com, 2017. [Online]. Available:
3178http://www.w3schools.com/php/php_mysql_intro.asp. [Accessed: 26- Feb- 2017].
3179[3]"PHP: mysqli::query - Manual", Php.net, 2017. [Online]. Available:
3180http://php.net/manual/en/mysqli.query.php. [Accessed: 26- Feb- 2017].
3181[4]"PHP GET and POST Method", www.tutorialspoint.com, 2017. [Online]. Available:
3182https://www.tutorialspoint.com/php/php_get_post.htm. [Accessed: 26- Feb- 2017].
3183[5]"PHP mysqli_fetch_object() Function", W3schools.com, 2017. [Online]. Available:
3184https://www.w3schools.com/php/func_mysqli_fetch_object.asp. [Accessed: 25- Feb- 2017].
3185142 [Web Application Development I-ITDB201]
3186Chapter 9: SESSION MANAGEMENT
3187 Objectives
3188At the end of this module, the students will be able to:
3189ï‚· Illustrate how a session works in a web environment.
3190ï‚· Create and destroy a session.
3191ï‚· Retrieve and modify session variable.
3192ï‚· Implement user authentication using sessions.
3193Overview
3194A session is a method to maintain information (in variables) that is accessible across
3195multiple pages. For instance, you are building an E-Commerce site or a social
3196networking website, one of the primary features of the application will be to create a
3197login authentication. Once, the user logs to the system with their login credentials such
3198as username and password, the application must keep track of user actions until they log
3199out of the application, this concept is called as ―session tracking‖. We need to track the
3200sessions because HTTP is state less protocol. HTTP is called as a stateless protocol
3201because each command request is executed independently, without any knowledge of the
3202requests that were executed before it. Due to this nature of the protocol, neither the client
3203nor the browser can retain information between different requests across the web pages.
3204This problem can be solves by storing user information to be used across multiple pages
3205(e.g. username, order_id, etc) in Session variables. Session variables are available until
3206the browser is closed.
3207A PHP session stores data on the server rather than user's computer. In a session based
3208environment, every user is identified through a unique number called session identifier or
3209SID. This unique session ID is used to link each user with their own information on the
3210server like emails, posts, etc.
3211143 [Web Application Development I-ITDB201]
3212The following table shows the most common session functions.
3213Function Explanation
3214session_start()
3215Starts new session if one does not exist. Continues current session if
3216one exists.
3217session_unset() Unsets all session variables.
3218session_destroy() Kills session.
3219The figure below shows that a session is started in the login page and same session is
3220maintained in the home page. Thus, session variables created in the login page can be
3221accessed in the home page and any other pages in the website until a session destroy function
3222is executed.
3223Figure 9.1: Start and destroy session
32249.1 Start a PHP Session
3225A PHP session is easily started by making a call to the session_start() function. It
3226will create a new session and generate a unique session ID for the user. Session variables are
3227stored in associative array called $_SESSION[]. These variables can be accessed during
3228lifetime of a session. The session_start() function first checks for an existing session ID. If it
3229finds one, i.e. if the session is already started, it sets up the session variables and if doesn't, it
3230starts a new session by creating a new session ID. A session creates a file in a temporary
3231session_start() session_start()
3232login.php home.php
3233logout.php
3234session_destroy()
3235144 [Web Application Development I-ITDB201]
3236directory on the server where registered session variables and their values are stored. This
3237data will be available to all pages on the site during that visit. The location of the temporary
3238file is determined by a setting in the php.ini file called session.save_path. Before using any
3239session variable make sure you have setup this path.
3240When a session is started following things happen −
3241ï‚· PHP first creates a unique identifier for that particular session which is a random
3242string of 32 hexadecimal numbers such as 3c7foj34c3jj973hjkop2fc937e3443.
3243ï‚· A cookie called PHPSESSID is automatically sent to the user's computer to store
3244unique session identification string.
3245ï‚· A file is automatically created on the server in the designated temporary directory and
3246bears the name of the unique identifier prefixed by sess_ ie
3247sess_3c7foj34c3jj973hjkop2fc937e3443.
3248When a PHP script wants to retrieve the value from a session variable, PHP
3249automatically gets the unique session identifier string from the PHPSESSID cookie and then
3250looks in its temporary directory for the file bearing that name and a validation can be done by
3251comparing both values.
3252A session ends when the user loses the browser or after leaving the site, the server
3253will terminate the session after a predetermined period of time, commonly 30 minutes
3254duration.
3255You can store all your session data as key-value pairs in
3256the $_SESSION[] superglobal array. The stored data can be accessed during lifetime of a
3257session. Consider the following script, which creates a new session and registers two session
3258variables.
3259145 [Web Application Development I-ITDB201]
3260session1.php
3261Note: The session_start() must be called at the beginning of the page before any
3262output is generated by your script in the browser.
32639.2 Accessing PHP Session Variables
3264To access the session data we set on our previous example from any other page on
3265the same web domain — simply recreate the session by calling session_start()
3266and then pass the corresponding key to the $_SESSION associative array.
3267session2.php
3268<?php
3269session_start(); //start a session
3270?>
3271<!DOCTYPE html>
3272<html>
3273<head>
3274<title>Example Session </title>
3275</head>
3276<body>
3277<?php
3278$_SESSION['name']="Ahmed";
3279$_SESSION['mark']=5;
3280?>
3281</body>
3282</html>
3283<?php
3284session_start();
3285?>
3286<!DOCTYPE html>
3287<html>
3288<head>
3289<title>Example Session </title>
3290</head>
3291<body>
3292<?php
3293echo "Student name is ".$_SESSION['name'];
3294echo "<br>Mark is ".$_SESSION['mark'];
3295print_r($_SESSION);
3296$_SESSION['mark'] = 20; //modifying a session variable.
3297print_r($_SESSION);
3298?>
3299</body>
3300</html>
3301146 [Web Application Development I-ITDB201]
3302Figure: Accessing Session Variables
33039.3 Retrieving the session id and destroying a PHP Session
3304Most sessions set a user-key on the user's computer that looks something like
3305this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on
3306another page, it scans the computer for a user-key. If there is a match, it accesses
3307that session, if not, it starts a new session.
3308session3.php
3309The examples above illustrate the following points.
3310ï‚· Pages that are part of the session should begin with a call to session_start().
3311ï‚· Session variables are created in the $_SESSION array.
3312ï‚· Session variables are deleted in the same way as other variables - using
3313the unset() function.
3314ï‚· All session variables can be unset with the session_unset() function. This should
3315be called before calling session_destroy().
3316ï‚· Sessions are killed with a call to session_destroy().
3317<?php
3318session_start();
3319?>
3320<!DOCTYPE html>
3321<html>
3322<body>
3323<?php
3324print_r(session_id()); //output the session id
3325session_unset();// remove all session variables
3326session_destroy();// destroy the session
3327?>
3328</body>
3329</html>
3330147 [Web Application Development I-ITDB201]
3331Chapter Summary:
3332One of the challenges in developing web based application is the lack of state in a web
3333environment. It is because HTTP is a stateless protocol and therefore maintaining data across pages
3334is definitely a challenge. This situation is resolved through the use and implementation of sessions.
3335Session support in PHP consists of a way to preserve certain data across subsequent accesses. This
3336enables you to build more customized applications and increase the appeal of your web site.
3337Assignments:
33381. What‘s the difference between a cookie and a session in PHP?
3339_______________________________________________________________________
3340_______________________________________________________________________
3341_______________________________________________________________________
3342_______________________________________________________________________
3343_______________________________________________________________________
33442. Identify if the following statement if True or False.
3345a. _______ The very first task executed by a session enabled page is session_start().
3346b. _______ Session variables will be lost when the browser is closed.
3347c. _______ HTTP is a stateless protocol therefore without sessions data cannot be accessed
3348across multiple pages.
3349d. _______ When a new session is created, the same session ID is generated for all users.
3350e. _______ Sessions variables can only be destroyed solely by executing the
3351session_destroy() function.
33523. Discuss how will you check if session variable is already set or not in PHP?
3353_______________________________________________________________________
3354_______________________________________________________________________
3355_______________________________________________________________________
3356_______________________________________________________________________
3357_______________________________________________________________________
3358148 [Web Application Development I-ITDB201]
3359Laboratory Exercises:
3360Learning Outcome: At the end of this activity, the students should be able to:
3361a. Implement user login functionality and using sessions to display on browser the
3362currently logged user.
3363b. Write PHP scripts that use the different PHP Session functions.
3364Instruction: Using the example application discussed in this chapter, implement the following
3365functionalities:
33661. Display currently logged user. Use PHP session functions to establish a new session
3367every time user logs to the system. If log in is successful, create a new session and store
3368the user details in the $_SESSION superglobal array. Retrieve these user details in the
3369succeeding pages and execute a session destroy method when the users log out.
33702. Block access to other pages when user is not logged in. If a user tries to access directly
3371the other pages(home.php and view_student.php) without going to the login page, block
3372the access by using a session variable to check if the user is logged or not. If not logged
3373in, redirect the user to the login page.
3374References:
3375[1]"PHP 5 Sessions", W3schools.com, 2017. [Online]. Available:
3376http://www.w3schools.com/php/php_sessions.asp. [Accessed: 01- Mar- 2017].
3377[2]"PHP: Introduction - Manual", Php.net, 2017. [Online]. Available:
3378http://php.net/manual/en/intro.session.php. [Accessed: 01- Mar- 2017].
3379[3]"Session handling in php | Codeforgeek", Codeforgeek, 2017. [Online]. Available:
3380https://codeforgeek.com/2014/08/session-handling-php/. [Accessed: 01- Mar- 2017].
3381[4]"HTTP Overview", www.tutorialspoint.com, 2017. [Online]. Available:
3382https://www.tutorialspoint.com/http/http_overview.htm. [Accessed: 01- Mar- 2017].
3383[5]2017. [Online]. Available: https://www.quora.com/Why-is-HTTP-protocol-called-statelessprotocol.
3384[Accessed: 01- Mar- 2017].
3385[6]A. Bradley, "Cookies vs. Sessions. Learn the Difference.", About.com Tech, 2017. [Online].
3386Available: http://php.about.com/od/phpfunctions/g/session_start.htm. [Accessed: 01- Mar- 2017].
3387149 [Web Application Development I-ITDB201]
3388[7]"How to Create, Access and Destroy Sessions in PHP - Tutorial Republic", Tutorialrepublic.com,
33892017. [Online]. Available: http://www.tutorialrepublic.com/php-tutorial/php-sessions.php.
3390[Accessed: 01- Mar- 2017].
3391[8]"PHP Sessions", www.tutorialspoint.com, 2017. [Online]. Available:
3392https://www.tutorialspoint.com/php/php_sessions.htm. [Accessed: 01- Mar- 2017].
3393[9]"PHP: Sessions - Manual", Php.net, 2017. [Online]. Available:
3394http://php.net/manual/en/features.sessions.php. [Accessed: 01- Mar- 2017].
3395[10]"Sessions | Tutorial | Webucator", Webucator, 2017. [Online]. Available:
3396https://www.webucator.com/tutorial/learnphp/session-control-cookies/sessions-reading.cfm.
3397[Accessed: 01- Mar- 2017].
3398150 [Web Application Development I-ITDB201]
3399Chapter 10: WEB APPLICATION SECURITY
3400 Objectives
3401At the end of this module, the students will be able to:
3402ï‚· Appreciate the value of implementing security in web applications.
3403ï‚· Distinguish the different security elements.
3404ï‚· Identify the different kinds of threats, vulnerabilities and types of attacks.
3405ï‚· Write PHP scripts that protects web application from threats.
3406Overview
3407Web application security is a branch of Information Security that deals
3408specifically with security of websites, web applications and web services. At a high
3409level, Web application security draws on the principles of application security but
3410applies them specifically to Internet and Web systems.
341110.1. The Foundations of Security
3412Security is fundamentally about protecting assets. Assets may be tangible items,
3413such as a Web page or your customer database — or they may be less tangible, such as
3414your company's reputation. Security relies on the following elements:
3415a. Authentication
3416Authentication addresses the question: who are you? It is the process of uniquely
3417identifying the clients of your applications and services. These might be end users,
3418other services, processes, or computers. In security parlance, authenticated clients
3419are referred to as principals.
3420b. Authorization
3421Authorization addresses the question: what can you do? It is the process that
3422governs the resources and operations that the authenticated client is permitted to
3423151 [Web Application Development I-ITDB201]
3424access. Resources include files, databases, tables, rows, and so on, together with
3425system-level resources such as registry keys and configuration data. Operations
3426include performing transactions such as purchasing a product, transferring money
3427from one account to another, or increasing a customer's credit rating.
3428c. Auditing
3429Effective auditing and logging is the key to non-repudiation. Non-repudiation
3430guarantees that a user cannot deny performing an operation or initiating a
3431transaction. For example, in an e-commerce system, non-repudiation mechanisms
3432are required to make sure that a consumer cannot deny ordering 100 copies of a
3433particular book.
3434d. Confidentiality
3435Confidentiality, also referred to as privacy, is the process of making sure that data
3436remains private and confidential, and that it cannot be viewed by unauthorized users
3437or eavesdroppers who monitor the flow of traffic across a network. Encryption is
3438frequently used to enforce confidentiality. Access control lists (ACLs) are another
3439means of enforcing confidentiality.
3440e. Integrity
3441Integrity is the guarantee that data is protected from accidental or deliberate
3442(malicious) modification. Like privacy, integrity is a key concern, particularly for
3443data passed across networks. Integrity for data in transit is typically provided by
3444using hashing techniques and message authentication codes.
3445f. Availability
3446From a security perspective, availability means that systems remain available for
3447legitimate users. The goal for many attackers with denial of service attacks is to
3448crash an application or to make sure that it is sufficiently overwhelmed so that other
3449users cannot access the application.
345010.2. Threats, Vulnerabilities, and Attacks Defined
3451A threat is any potential occurrence, malicious or otherwise, that could harm an
3452asset. In other words, a threat is any bad thing that can happen to your assets.
3453Vulnerability is a weakness that makes a threat possible. This may be because of
3454poor design, configuration mistakes, or inappropriate and insecure coding techniques.
3455Weak input validation is an example of an application layer vulnerability, which can
3456result in input attacks.
3457152 [Web Application Development I-ITDB201]
3458An attack is an action that exploits vulnerability or enacts a threat. Examples of
3459attacks include sending malicious input to an application or flooding a network in an
3460attempt to deny service.
3461To summarize, a threat is a potential event that can adversely affect an asset, whereas a
3462successful attack exploits vulnerabilities in your system.
3463Types of Web Application Vulnerabilities
3464a. Cross-Site Scripting(XSS)
3465Cross-site scripting (XSS) is a type of computer security vulnerability typically
3466found in web applications. XSS enables attackers to inject client-side scripts into web
3467pages viewed by other users.
3468Suppose you have a comment form in your application that allows users to enter
3469data, and on successful submission it shows all the comments. The user could
3470possibly enter a comment that contains malicious JavaScript code in it. When the
3471form is submitted, the data is sent to the server and stored into the database.
3472Afterward, the comment is fetched from database and shown in the HTML page and
3473the JavaScript code will run. The malicious JavaScript might redirect the user to a bad
3474web page or a phishing website.
3475Example:
3476comment.php
3477<?php
3478if(isset($_POST['comment']))
3479echo $_POST['comment'];
3480?>
3481<!DOCTYPE html>
3482<html>
3483<head>
3484<title></title>
3485</head>
3486<body>
3487<h1>XSS Attack Example</h1>
3488<form action="post.php" method="post">
3489<input type="text" name="comment" value="" size=100>
3490<input type="submit" name="submit" value="Submit Comment">
3491</form>
3492</body>
3493</html>
3494153 [Web Application Development I-ITDB201]
3495Figure : Comment.php rowser Output
3496Here we have a simple form in which there is a text box for data input and a submit
3497button. Once the form is submitted, it will submit the data to post.php for processing.
3498Let‘s say all post.php does is output the data inputted.
3499Methods Preventing Against XSS Attacks: Escape Output
3500ï‚· Using htmlspecialchars()
3501For the majority of PHP applications, htmlspecialchars() will be your
3502best friend. htmlspecialchars() supplied with no arguments will convert special
3503characters to HTML entities, below shows the conversions performed:
3504'&' (ampersand) becomes '&'
3505'"' (double quote) becomes '"'
3506'<' (less than) becomes '<'
3507'>' (greater than) becomes '>'
3508154 [Web Application Development I-ITDB201]
3509ï‚· htmlspecialchars() vs htmlentities()
3510Another function exists which is almost identical to htmlspecialchars().
3511htmlenities() performs the same functional sanitization on dangerous characters,
3512however, encodes all character entities when one is available. This may lead to
3513excessive encoding and cause some content to display incorrectly if character sets
3514change.
3515post.php
3516b. SQL Injection Attacks
3517When working with databases, one of the most common security vulnerabilities in
3518web applications is definitely SQL injection attack. Malicious users can insert SQL query
3519into the input data you‘re using in your SQL queries and instead unwanted behavior
3520happens.
3521Example login page with user input.
3522ï‚· SQL Injection Based on 1=1 is Always True
3523<?php
3524if(isset($_POST['comment']))
3525$comments=$_POST['comment'];
3526// This can be solved with htmlspecialchars
3527echo htmlspecialchars($comments, ENT_QUOTES, 'UTF-8');
3528?>
3529155 [Web Application Development I-ITDB201]
3530Refer to the example above again. The objective of the code was to create
3531an SQL statement to that will select a user with a given user id. If there is no
3532validation that prevents the user from entering "wrong" input, the user can enter
3533some "smart" input like this:
3534UserID: 105 or 1=1
3535SQL Query:
3536$userid=$_POST[„userid‟];
3537$query =â€SELECT * FROM users WHERE userid=$useridâ€;
3538Resulting Query:
3539SELECT * FROM user WHERE username=105 or 1=1
3540The SQL above is valid. It will return all rows from the table Users, since
3541WHERE 1=1 is always true.
3542ï‚· SQL Injection Based on ""="" is Always True
3543By simple entering " or ""=" into the user name or password text box, an
3544intruder might get access to user names and passwords in a database as
3545shown in the example below.
3546SQL Query:
3547$username=$_POST['username'];
3548$password=$_POST['password'];
3549$query ='SELECT * FROM users WHERE username ="' . $username . '"
3550AND password ="' . $password . '"';
3551156 [Web Application Development I-ITDB201]
3552Resulting Query:
3553SELECT * FROM users WHERE username ="" or ""="" AND password =""
3554or ""=""
3555The result SQL is valid. It will return all rows from the table Users, since WHERE ""=""
3556is always true.
3557Preventing Against SQL Injection
3558ï‚· Using mysql_escape_string()
3559Developers usually use php function mysql_real_escape_string to filter input
3560data. As of PHP 5.5.0 mysql_real_escape_string and the mysql extension are
3561deprecated. So we shall use mysqli extension and mysqli::escape_string function
3562instead. Where the unnecessary extra characters are removed and then passed to
3563the execution.
3564Using the instantiated database connection variable ($db) from database
3565connection (dbconnect.php) to use the mysqli::escape_string function.
3566$username=$db->escape_string($_POST['username']);
3567$password=$db->escape_string($_POST['password']);
3568$query ='SELECT * FROM users WHERE username ="' . $username . '"
3569AND password ="' . $password . '"';
3570ï‚· Using PDO Prepared Statements
3571As of PHP 5.1, there's a better way, it‘s using PDO i.e. PHP Data
3572Objects. It is a database access layer providing a uniform method of access to
3573multiple databases. It provides methods for prepared statements and working with
3574objects that will make you far more productive!
3575157 [Web Application Development I-ITDB201]
3576c. Unsecured Passwords
3577When you must save user‘s password in a database you should never ever store
3578them in plain text because of security precautions and privacy protection. Database
3579where users‘ passwords are stored might get compromised and by hashing them at
3580least there is another safety mechanism for not revealing them to the attacker.
3581Ways of securing passwords:
3582ï‚· Hashing Password
3583One of the most used but wrong way of hashing password was once using md5()
3584which calculates md5 hash of a string. Hashing passwords with md5 (or sha1 or
3585even sha256) is note safe anymore because these hashes can get decrypted very
3586fast.
3587hash.php
3588ï‚· Using SALT
3589In addition to hashing the password, using of password SALT is also encouraged
3590to provide another level of protection.
3591<?php
3592// plain text password
3593$password = 'secretcode';
3594// hash the password with md5
3595$password_md5 = md5($password);
3596// another way is to hash the password with sha256
3597$password_sha256=hash(‘sha256’,$password);
3598?>
3599158 [Web Application Development I-ITDB201]
3600salt.php
3601d. CSRF Attacks
3602Cross-Site Request Forgery (CSRF) is an attack that forces an end user to
3603execute unwanted actions on a web application in which they're currently
3604authenticated. CSRF attacks specifically target state-changing requests, not theft of
3605data, since the attacker has no way to see the response to the forged request. With a
3606little help of social engineering (such as sending a link via email or chat), an attacker
3607may trick the users of a web application into executing actions of the attacker's
3608choosing. If the victim is a normal user, a successful CSRF attack can force the user
3609to perform state changing requests like transferring funds, changing their email
3610address, and so forth. If the victim is an administrative account, CSRF can
3611compromise the entire web application.
3612Preventing Against CSRF:
3613ï‚· Creating Synchronizer (CSRF) Tokens
3614Any state changing operation requires a secure random token (e.g., CSRF token)
3615to prevent CSRF attacks
3616Characteristics of a CSRF Token:
3617 Unique per user session
3618 Large random value
3619<?php
3620// plain text password
3621$password = 'secretcode';
3622// add random number of random characters - the salt
3623$salt = '3x%%$bf83#dls2qgdf';
3624// hash salt and password together
3625$password_md5 = md5($salt.$password);
3626// another way is to hash the password with sha256
3627$password_sha256=hash(‘sha256’,$salt.$password);
3628?>
3629159 [Web Application Development I-ITDB201]
3630 Generated by a cryptographically secure random number generator
3631The CSRF token is added as a hidden field for forms or within the URL if the
3632state changing operation occurs via a GET.
3633The server rejects the requested action if the CSRF token fails validation.
3634Examples:
363510.3. Proper Error Handling
3636It‘s good to know about all the errors that occur while we‘re developing an application,
3637but when we make the application accessible to end users we should take care to hide the
3638errors. If errors are shown to users, it may make our application vulnerable. So, the best
3639public function check_valid($method) {
3640 if($method == 'post' || $method == 'get') {
3641 $post = $_POST;
3642 $get = $_GET;
3643if(isset(${$method}[$this->get_token_id()]) &&
3644(${$method}[$this->get_token_id()] == $this->get_token())) {
3645 return true;
3646 } else {
3647 return false;
3648 }
3649 } else {
3650 return false;
3651 }
3652}
3653public function get_token() {
3654 if(isset($_SESSION['token_value'])) {
3655 return $_SESSION['token_value'];
3656 } else {
3657 $token = hash('sha256', $this->random(500));
3658 $_SESSION['token_value'] = $token;
3659 return $token;
3660 }
3661}
3662160 [Web Application Development I-ITDB201]
3663approach is configuring your server differently for development and production
3664environments.
3665In production mode we need to turn off display_errors and display_start_up_errors
3666settings. error_reporting and log_errors should be on so that we can log errors while
3667hiding those from end users.
3668In php.ini in Production environment:
3669display_errors = off
3670display_startup_errors = off
3671Changing configuration option in runtime using:
3672ini_set — Sets the value of a configuration option
3673ini_set('display_errors', 1);
3674ini_set('display_startup_errors', 1);
3675error_reporting(E_ALL);
3676 Chapter Summary:
3677Web application security is not a considered a feature for any web application but it is a must
3678and a priority. It is considered to be a very vital component of any web application regardless of
3679the size of the application or the business itself. Attention and focus must be given in securing
3680web applications to ensure the safety, consistency and availability of data. Web developers must
3681be aware of vulnerabilities and risks and be assertive in addressing these issues.
3682Assignments:
3683Student-Centered Activity – Article/Website Abstract
3684Category: Critical Thinking
3685Suggested
3686duration:
3687Assignment
3688Intent: Provides active strategy for students to read and analyze the role of W3C in
3689Web Security.
3690Implementation: 1. Visit and go through the website of W3C: https://www.w3.org/Security/.
36912. Find a partner to collaborate with for this activity and answer the
3692questions as a team.
3693161 [Web Application Development I-ITDB201]
36941. What is W3C and what is its Mission?
3695_______________________________________________________________________
3696_______________________________________________________________________
3697_______________________________________________________________________
3698_______________________________________________________________________
3699_______________________________________________________________________
37002. What are the different Active Groups in the Web Security umbrella of W3C?
3701_______________________________________________________________________
3702_______________________________________________________________________
3703_______________________________________________________________________
3704_______________________________________________________________________
3705_______________________________________________________________________
37063. W3C standards define an Open Web Platform for different aspects in application development.
3707The standards can be viewed in this URL: https://www.w3.org/standards. Select one standard and
3708discuss the focus and purpose of such standard.
3709_______________________________________________________________________
3710_______________________________________________________________________
3711_______________________________________________________________________
3712_______________________________________________________________________
3713_______________________________________________________________________
3714Laboratory Exercises:
3715Learning Outcome: At the end of this activity, the students should be able to:
37161. Implement basic web application security.
37172. Realize the importance of web security.
3718Instruction: Using the example application discussed in this chapter, implement the following
3719functionalities:
37201. Adding SALT to user Password. Implement web security to the application by adding
3721SALT to the user password. Add the column SALT in the user‘s table and create a SALT
3722upon user registration. When user logs in to the application, compare the user‘s password
3723and the SALT saved in the database.
3724162 [Web Application Development I-ITDB201]
37252. Prevent SQL Injection. Update your script in user registration and use
3726mysql_escape_string() in every user input before saving to the database.
3727References:
3728[1]"How to Secure PHP Web Applications and Prevent Attacks?", World Wide PHP Facebook
3729Group, 2016. [Online]. Available: https://wwphp-fb.github.io/faq/security/php-security-issues/.
3730[Accessed: 19- Nov- 2016].
3731[2]"OWASP", Owasp.org, 2016. [Online]. Available: https://www.owasp.org/index.php/Main_Page.
3732[Accessed: 19- Nov- 2016].
3733[3]"PHP Master | 8 Practices to Secure Your Web App", SitePoint, 2016. [Online]. Available:
3734https://www.sitepoint.com/8-practices-to-secure-your-web-app/. [Accessed: 19- Nov- 2016].
3735[4]2016. [Online]. Available: https://www.butterfly.com.au/blog/website-development/webapplication-security-essentials-for-php-developers-the-art-of-not-getting-hacked.
3736[Accessed: 19-
3737Nov- 2016].
3738[5]M. Yadav, "Basic principles of Web application security - ScriptArticle.com", ScriptArticle.com,
37392016. [Online]. Available: http://www.scriptarticle.com/basic-principles-web-application-security/.
3740[Accessed: 19- Nov- 2016].
3741[6]"Web application security", En.wikipedia.org, 2016. [Online]. Available:
3742https://en.wikipedia.org/wiki/Web_application_security. [Accessed: 26- Nov- 2016].
3743[7]"Web Application Security Fundamentals", Msdn.microsoft.com, 2016. [Online]. Available:
3744https://msdn.microsoft.com/en-us/library/ff648636.aspx. [Accessed: 26- Nov- 2016].
3745[8]"Preventing Cross-site Scripting in PHP - Virtue Security", Virtue Security, 2016. [Online].
3746Available: https://www.virtuesecurity.com/blog/preventing-cross-site-scripting-php/. [Accessed: 26-
3747Nov- 2016].
3748[9]"Cross-Site Scripting Attacks (XSS)", SitePoint, 2016. [Online]. Available:
3749https://www.sitepoint.com/php-security-cross-site-scripting-attacks-xss/. [Accessed: 26- Nov- 2016].
3750[10]"What is SQL injection and how to prevent it?", World Wide PHP Facebook Group, 2016.
3751[Online]. Available: https://wwphp-fb.github.io/faq/security/sql-injection/. [Accessed: 26- Nov2016].
3752163 [Web Application Development I-ITDB201]
3753[11]"SQL Injection", W3schools.com, 2016. [Online]. Available:
3754http://www.w3schools.com/Sql/sql_injection.asp. [Accessed: 26- Nov- 2016].
3755[12]K. Teja, "Preventing SQL Injection in PHP", Packetcode.com, 2017. [Online]. Available:
3756http://packetcode.com/article/preventing-sql-injection-php-security. [Accessed: 01- Mar- 2017].
3757[13]"How to Work With Users‘ Passwords and How to Securely Hash Passwords in PHP?", World
3758Wide PHP Facebook Group, 2017. [Online]. Available: https://wwphpfb.github.io/faq/security/passwords/.
3759[Accessed: 01- Mar- 2017].
3760[14]"Cross-Site Request Forgery (CSRF) - OWASP", Owasp.org, 2017. [Online]. Available:
3761https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF). [Accessed: 01- Mar- 2017].
3762[15]"Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet - OWASP", Owasp.org, 2017.
3763[Online]. Available: https://www.owasp.org/index.php/CrossSite_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet.
3764[Accessed: 01- Mar- 2017].
3765[16]"How to Prevent Cross Site Request Forgery (CSRF) Attacks in PHP", wikiHow, 2017. [Online].
3766Available: http://www.wikihow.com/Prevent-Cross-Site-Request-Forgery-(CSRF)-Attacks-in-PHP.
3767[Accessed: 01- Mar- 2017].
3768164 [Web Application Development I-ITDB201]
3769Chapter 11: TESTING AND APPLICATION DEPLOYMENT
3770 Objectives
3771At the end of this module, the students will be able to:
3772ï‚· Enumerate the different kinds of testing web applications.
3773ï‚· Perform basic web application testing.
3774ï‚· Identify and decide appropriately the best deployment option for the web
3775application.
377611.1. Web Application Testing
3777We‘re now living in a time where users expect as much functionality, reliability and
3778flexibility from Web apps as desktop programs. All our data is slowly but surely
3779moving into the cloud, and businesses are looking to the Web for software to easily
3780implement and deploy across the board – whether it‘s accounting, CRM or inventory
3781management. That puts a lot of pressure on developers to deliver rock-solid Web apps
3782that users can genuinely depend on for work and play.
3783That‘s why it‘s so important to thoroughly test your Web application before launch.
3784Presenting a quality web app that doesn‘t break, works efficiently and delights users
3785naturally builds a foundation of trust between you and your customers, and they‘ll be
3786happy to use it more often and even refer it to peers. Plus, you‘ll have far fewer
3787customer support issues to deal with, leading to savings on costs and manpower.
3788Some or all of the following testing types may be performed depending on your web
3789testing requirements.
3790a. Functionality Testing
3791This testing is used for checking all the links of the web pages; form testing, cookie
3792testing and database connection.
3793165 [Web Application Development I-ITDB201]
3794Users expect web apps to function accurately, quickly and consistently. Some
3795common functional elements that require thorough testing include:
3796Test for – all the links in web pages, database connection, forms used for submitting
3797or getting information from user in the web pages, Cookie testing etc.
3798Check all the links:
3799ï‚· Test the outgoing links from all the pages to specific domain under test.
3800ï‚· Test all internal links.
3801ï‚· Test links jumping on the same pages.
3802ï‚· Test links used to send email to admin or other users from web pages.
3803ï‚· Test to check if there are any orphan pages.
3804ï‚· Finally link checking includes, check for broken links in all above-mentioned
3805links.
3806Test forms in all pages:
3807Forms are the integral part of any website. Forms are used for receiving information
3808from users and to interact with them. So what should be checked on these forms?
3809ï‚· First check all the validations on each field.
3810ï‚· Check for default values of the fields.
3811ï‚· Wrong inputs in the forms to the fields in the forms.
3812ï‚· Options to create forms if any, form delete, view or modify the forms.
3813Let‘s take example of the search engine project currently I am working on, in this
3814project we have advertiser and affiliate signup steps. Each sign up step is different but
3815its dependent on the other steps. So sign up flow should get executed correctly. There
3816are different field validations like email Ids, User financial info validations etc. All
3817these validations should get checked in manual or automated web testing.
3818Cookies Testing:
3819Cookies are small files stored on the user machine. These are basically used to
3820maintain the session- mainly the login sessions. Test the application by enabling or
3821disabling the cookies in your browser options. Test if the cookies are encrypted
3822before writing to user machine. If you are testing the session cookies (i.e. cookies that
3823expire after the session ends) check for login sessions and user stats after session
3824ends. Check effect on application security by deleting the cookies. (I will soon write a
3825separate article on cookie testing as well)
3826166 [Web Application Development I-ITDB201]
3827Validate your HTML/CSS:
3828If you are optimizing your site for Search engines then HTML/CSS validation is the
3829most important one. Mainly validate the site for HTML syntax errors. Check if the
3830site is crawlable to different search engines.
3831Database testing:
3832Data consistency is also very important in web application. Check for data integrity
3833and errors while you edit, delete, modify the forms or do any DB related
3834functionality.
3835Check if all the database queries are executing correctly, data is retrieved and also
3836updated correctly. More on database testing could be load on DB,we will address this
3837in web load or performance testing below.
3838b. Usability Testing
3839This testing checks the navigation and user friendliness of the web pages. Through this
3840testing it is ensured whether the content is properly checked and is easily
3841understandable to the users. It also checks whether the anchor text links are working
3842properly, whether sitemaps and help files are having proper information and all the
3843links are working.
3844Usability testing has now become a vital part of any web based project. It can be
3845carried out by testers like you or a small focus group similar to the target audience
3846of the web application.
3847Test for navigation:
3848Navigation means how a user surfs the web pages, different controls like buttons,
3849boxes or how the user uses the links on the pages to surf different pages.
3850Usability testing includes the following:
3851ï‚· Website should be easy to use.
3852ï‚· Instructions provided should be very clear.
3853ï‚· Check if the instructions provided are perfect to satisfy its purpose.
3854ï‚· Main menu should be provided on each page.
3855ï‚· It should be consistent enough.
3856167 [Web Application Development I-ITDB201]
3857Content checking:
3858Content should be logical and easy to understand. Check for spelling errors. Usage
3859of dark colors annoys the users and should not be used in the site theme. You can
3860follow some standard colors that are used for web page and content building. These
3861are the common accepted standards like what I mentioned above about annoying
3862colours, fonts, frames etc.
3863Content should be meaningful. All the anchor text links should be working
3864properly. Images should be placed properly with proper sizes.
3865These are some of basic important standards that should be followed in web
3866development. Your task is to validate all for UI testing.
3867Other user information for user help:
3868Like search option, sitemap also help files etc. Sitemap should be present with all
3869the links in websites with proper tree view of navigation. Check for all links on the
3870sitemap.
3871―Search in the site‖ option will help users to find content pages that they are looking
3872for easily and quickly. These are all optional items and if present they should be
3873validated.
3874c. Interface Testing
3875This checks if the web server and application server interface, application server and
3876database server interface have proper interaction or not. This test ensures that the
3877users do not see any error messages.
3878The main interfaces are:
3879Web server and application server interface Application server and Database server
3880interface. Check if all the interactions between these servers are executed and errors
3881are handled properly. If database or web server returns any error message for any
3882query by application server then application server should catch and display these
3883error messages appropriately to the users. Check what happens if user interrupts any
3884transaction in-between? Check what happens if connection to the web server is reset
3885in between?
3886d. Compatibility testing
3887Compatibility Testing is very important as it checks browser compatibility,
3888operating system compatibility, mobile browsing and printing options.
3889168 [Web Application Development I-ITDB201]
3890Compatibility of your website is a very important testing aspect. See which
3891compatibility test to be executed:
3892ï‚· Browser compatibility
3893ï‚· Operating system compatibility
3894ï‚· Mobile browsing
3895ï‚· Printing options
3896e. Performance testing
3897Performance testing includes web load testing and web stress testing. Web load
3898testing technique checks if many users can access the same page at the same time
3899and whether a web page can handle heavy load on any specific page. Web stress
3900testing is done on the site to see that how will the site react and recover during the
3901stress time.
3902Web application should sustain to heavy load. Web performance testing should
3903include:
3904ï‚· Web Load Testing
3905ï‚· Web Stress Testing
3906Test application performance on different internet connection speed.
3907Web load testing: You need to test if many users are accessing or requesting the
3908same page. Can system sustain in peak load times? Site should handle many
3909simultaneous user requests, large input data from users, simultaneous connection to
3910DB, heavy load on specific pages etc.
3911Web Stress testing: Generally stress means stretching the system beyond its
3912specified limits. Web stress testing is performed to break the site by giving stress
3913and its checked as how the system reacts to stress and how it recovers from crashes.
3914Stress is generally given on input fields, login and sign up areas.
3915In web performance testing website functionality on different operating systems and
3916different hardware platforms is checked for software and hardware memory leakage
3917errors.
3918f. Security testing
3919This checks the security of the web applications. For security purposes, internal
3920pages should not open if you are not logged into the website. Other statistics should
3921169 [Web Application Development I-ITDB201]
3922not be seen even if the user is logged in. The files should only be given the option for
3923downloading and it should not be accessed without downloading. CAPTCHA for
3924automates scripts logins should be tested. SSL should be tested for security
3925measures.
3926Most Web apps capture and store data from users, including their personal details,
3927billing information and work/personal files — and these users trust you to keep that
3928data secure. Your app should:
3929ï‚· Keep private data private
3930ï‚· Insist on authentication before granting access to data, and limit/allow access
3931data as necessary
3932 Ensure that data integrity isn‘t compromised.
393311.2. Web Hosting
3934Part of the decision making in the development of a web application is the selection of a
3935web host. A web hosting service is a type of Internet hosting service that allows
3936individuals and organizations to make their website accessible via the World Wide Web.
3937Web hosts are companies that provide space on a server owned or leased for use by
3938clients, as well as providing Internet connectivity, typically in a data center. Majority of
3939web hosts offer different types of web hosting packages.
3940Different types of web hosting:
3941a. Shared hosting - Shared hosting is the budget option. It is extremely cheap, but also
3942not very good. As the name suggests, this is where you share a server with dozens,
3943hundreds or even thousands of other websites.
3944Shared hosting is the cheapest option and,
3945usually, the easiest to set up, because you‘re
3946not taking control of a computer, just adding
3947your files to one that‘s already set up. On the
3948other hand, the fact that you‘re sharing the
3949web server means your site‘s performance
3950can be compromised by the sheer weight of
3951traffic the server has to cope with. Even if
3952only a few people are trying to view your
3953pages, you‘re also affected by the number
3954Source: https://hostingfacts.com/differenttypes-of-web-hosting/
3955170 [Web Application Development I-ITDB201]
3956accessing the other sites that may be on the same server.
3957Examples of shared hosting servers:
3958ï‚· https://www.godaddy.com/
3959ï‚· https://www.dreamhost.com
3960b. Dedicated Server - A dedicated server is a physical machine leased in its entirety to
3961the customer. They get complete control over the machine through a browser-based
3962control panel and root/admin-level access. These computers usually run either Linux
3963or Windows Server.
3964c. Virtual Private Server(VPS) - VPS stands for Virtual Private Server and is probably
3965the most popular service to upgrade to and it can be the most well-balanced one as
3966well.
3967A VPS server is still a shared environment, but the way it is shared is very different.
3968In reality, a single computer is running several ―virtual servers‖. Each copy of the
3969server software thinks it‘s running on its own computer, but in fact the machine‘s
3970processor is handling them all at the same time, while each has its own hard disk
3971partition. Since the physical resources of the server are shared between the virtual
3972servers, you can expect to get less hard disk space, lower memory and some
3973competition for processor time, reducing performance. However, VPSs are an
3974excellent halfway house between shared hosting and dedicated servers.
3975d. Cloud Server - Cloud hosting is essentially the same as VPS hosting. Some
3976companies don‘t even call their service VPS anymore, the say Cloud or Cloud VPS.
3977Cloud based hosting allows you to use the resources of multiple servers in a network.
3978This makes it even more scalable, in addition to providing a host of additional
3979benefits, mainly based around security.
3980171 [Web Application Development I-ITDB201]
3981 Chapter Summary:
3982Today, millions of web applications exist to make our lives easier and much more interesting.
3983We can shop online, pay bills, chat with friends and relatives, or communicate with people all
3984over the world who have the same hobbies and interests as ours. Because of this of
3985inevitability of using web applications in almost all aspects of our daily lives, testing web
3986applications to prevent and mitigate various risk and threats is a must. To protect the interest
3987of customers as well the business owners and all stakeholders, a web application must
3988undergo a series and varied types of test before deploying to the live environment to ensure
3989its effectiveness, consistency and productivity.
3990Assignments:
39911. How is Web Application Testing different to Desktop Application Testing?
3992_______________________________________________________________________
3993_______________________________________________________________________
3994_______________________________________________________________________
3995_______________________________________________________________________
3996_______________________________________________________________________
39972. What is a Test Case? Why do we need to use test cases in testing web applications?
3998_______________________________________________________________________
3999_______________________________________________________________________
4000_______________________________________________________________________
4001_______________________________________________________________________
4002_______________________________________________________________________
40033. What is performance test? Does performance of a web site impact customer service? Why?
4004_______________________________________________________________________
4005_______________________________________________________________________
4006_______________________________________________________________________
4007_______________________________________________________________________
4008_______________________________________________________________________
4009172 [Web Application Development I-ITDB201]
4010Laboratory Exercises:
4011Learning Outcome: At the end of this activity, the students should be able to:
40121. Recognize the different web testing tools and classify them as to the type of web testing
4013the software can be used.
40142. Validate a webpage/website using the W3C validator to check the compatibility of the
4015webpage to the standards.
4016Instructions: Perform the following activities.
40172. Research on Web Testing Tools
4018Student Centered Activity - Activity Matrix
4019Category: Problem-based Learning
4020Suggested
4021duration:
4022Ongoing, throughout a class session as appropriate.
4023Intent: Allows students to map the different web testing tools, know the functions and
4024when to use such applications.
4025Implementation: 5. In the first column, give at least 5 web testing tools. One example is given
4026for you.
40276. In the second column, write a brief description about the tool.
40287. In the third column, identify what type of web testing the tool may be
4029used.
4030Application Description When to Use
4031(Type of web testing applicable)
4032a. JMeter open source software, a 100% pure Java
4033application
4034load test functional behavior and
4035measure performance
4036b.
4037c.
4038d.
4039e.
4040173 [Web Application Development I-ITDB201]
4041M. Go to the https://validator.w3.org/ and submit the application developed in this course
4042material. Check and correct the errors if there is any after validation. Write the steps you
4043performed in validating your website.
4044_______________________________________________________________________
4045_______________________________________________________________________
4046_______________________________________________________________________
4047_______________________________________________________________________
4048_______________________________________________________________________
4049References:
4050[1]"PHP: The Right Way", PHP: The Right Way, 2016. [Online]. Available:
4051http://www.phptherightway.com/#servers_and_deployment. [Accessed: 19- Nov- 2016].
4052[2]A. Ghoshal, "A Comprehensive Guide to Web Application Testing", The Next Web, 2016.
4053[Online]. Available: http://thenextweb.com/apps/2013/11/28/guide-testing-web-app-stepsapproach-testing-get-sessions/.
4054[Accessed: 19- Nov- 2016].
4055[3]"Web Testing: A Complete guide about testing web applications", Software Testing Help,
40562016. [Online]. Available: http://www.softwaretestinghelp.com/web-application-testing/.
4057[Accessed: 19- Nov- 2016].
4058[4]A. Ghahrai, "Web Application Testing | Web Testing Methods", Testing Excellence, 2017.
4059[Online]. Available: http://www.testingexcellence.com/web-application-testing-techniques/.
4060[Accessed: 01- Mar- 2017].
4061[5]"How to host your site: shared vs dedicated vs virtual", Alphr, 2017. [Online]. Available:
4062http://www.alphr.com/features/378952/how-to-host-your-site-shared-vs-dedicated-vs-virtual.
4063[Accessed: 01- Mar- 2017].
4064[6]"Web hosting service", En.wikipedia.org, 2017. [Online]. Available:
4065https://en.wikipedia.org/wiki/Web_hosting_service. [Accessed: 01- Mar- 2017].