Internet Programming Lab Manual
Internet Programming Lab Manual
Credit: 7 ECTS
Prepared By:
Yared Y. & Ermias T.
January 2022
Web Programming Lab Manual Debre Tabor University Computer Science Department
Table of Contents
Prologue: General Laboratory Instruction/Introduction ................................................................ 4
Chapter One: The Internet and World Wide Web ......................................................................... 7
Experiment 1.1: How to use Google to search ........................................................................... 7
Experiment 1.2: Domain, URL, HTTP, HTTPS, Parameter String Overview ................................. 7
Chapter Two: Hyper Text Mark Up Language (HTML) .................................................................... 9
Experiment 2.1: Hello World using HTML ................................................................................... 9
Experiment 2.2: Static Web page Designing ............................................................................. 10
Experiment 2.3 Validation ......................................................................................................... 33
Chapter Three: Cascading Style Sheet (CSS) ................................................................................. 38
Experiment 3.1 CSS Examples ................................................................................................... 38
Experiment 3.2: Inline Styles ..................................................................................................... 39
Experiment 3.3: Embedded Style Sheets .................................................................................. 40
Experiment 3.4: External Style Sheets ...................................................................................... 41
Chapter Four: JavaScript ............................................................................................................... 46
Experiment 4.1: Simple Calculator using JavaScript ................................................................ 46
Experiment 4.2: squares and cubes of numbers using JavaScript ........................................... 48
Experiment 4.3: Text-growing using JavaScript code and coloring .......................................... 49
Chapter Five: PHP ......................................................................................................................... 52
Experiment 5.1: Hello World using PHP scripts embedded in HTML ....................................... 52
Experiment 5.2: Declaration and Initialization in PHP .............................................................. 52
Experiment 5.3: Outputting text and variables with the print statement ................................ 53
Experiment 5.4: PHP comments, variables and strings ............................................................ 54
Experiment 5.5: Design HTML Form and retrieve the values in PHP Script ............................. 55
Experiment 5.6: PHP Variables and Arrays ............................................................................... 58
Experiment 5.7: PHP Functions: array, string, date-time and calendar ................................... 60
Experiment 5.8: WampServer Installation ................................................................................ 64
Experiment 5.9: MySQL connectivity, INSERT, DELETE, SELECT WITH PHP .............................. 72
Experiment 5.10: PHP MySQL connectivity .............................................................................. 75
Experiment 5.11: PHP Script for file uploading ......................................................................... 76
Experiment 5.12: PHP script for-Session Management (login form) ........................................ 78
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter Six: AJAX .......................................................................................................................... 84
Experiment 6.1: AJAX Script using XMLHttpRequest PHP. ....................................................... 84
Experiment 6.2: PHP update and retrieve using Ajax ............................................................... 85
Quizzes on the Subject .................................................................................................................. 90
Web Programming Lab Manual Debre Tabor University Computer Science Department
Prologue: General Laboratory Instruction/Introduction
What you should know
Before starting this lab, it is important that you have a basic understanding and experience in the
following:
So, in the first lab you should know and refresh yourself how to:
Web Programming Lab Manual Debre Tabor University Computer Science Department
II. Open notepad++ or other editor and type the CSS program and save the file with .css
extension for CSS program in your folder. (if it is external CSS and like to the html
page)
III. Then open the Internet Explorer /Mozilla web browser and type the URL as
directoryname:\foldername\filename.html Ex: E:\cs\pgmname.html
IV. Finally, output will display.
• The browser is responsible for running JavaScript. Thus, the output from JavaScript is
going to be more responsive as the data does not need to travel to or from server. A
web browser runs JavaScript when a web page is downloaded or in response to an
event.
• JavaScript code can be placed either in an HTML file or an external file. So how do
you decide where do you place your code? If your JavaScript code is small and
cannot be used in any other web page, then, you should consider placing your code
directly in the HTML document that uses it. If, on the other hand, your JavaScript is
long and/or used by many HTML documents, then, you should create a separate
JavaScript file.
• Because you can insert JavaScript code inside an HTML file, it needs to be
distinguished from the rest of the text or code on the page. To separate your
JavaScript commands from HTML commands or regular text on the page, insert your
JavaScript code inside the opening <script> and closing </script> tag. For example,
<script language="JavaScript">
JavaScript commands
</script>
• Because there are different client-side languages, we need to indicate to the browser
which language we are using in our scripts. To indicate the scripting language, we
added the language attribute to the <script> tag. Since we are using JavaScript, we set
the language tag to JavaScript. If you omit the language tag from your <script> tag,
the browser will assume that your code is written in JavaScript.
Web Programming Lab Manual Debre Tabor University Computer Science Department
• If you place your scripting code outside of the HTML page, you still use the <script>
tag but then just add the src attribute. The value of src attribute tells the browser
where your JavaScript code is located. For instance,
</script>
• The code fragment above indicates that we are using JavaScript language and the
JavaScript commands are located in a folder called JavaScript and a file called
displayDate.js. A ".js" file extension indicates a JavaScript file.
4. Steps to execute PHP Program.
I. Type the program in notepad++ and save it with .php extension in the C:\wamp\www
folder.
II. Next type the supported html & save it with .html extension in the same folder.
III. Start server (go to start->programs->Wamp server->start wamp server).
IV. Open the browser & type the URL as http://localhost, then it will display the welcome
web page
V. Then Open Browser and type the URL as http://localhost/prgramname.php Example:
http://localhost/p11.php
VI. Finally, output will display.
NB: If you have PHP inserted into your HTML and want the web browser to interpret it
correctly, then you must save the file with a .php extension, instead of the standard .html
extension. So be sure to check that you are saving your files correctly. Instead of index.html, it
should be index.php if there is PHP code in the file.
If you are writing PHP scripts and plan on distributing them, it is recommended that you use the
standard form (which includes the ?php) rather than the shorthand form. This will ensure that
your scripts will work, even when running on other servers with different settings.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter One: The Internet and World Wide Web
In this chapter students will be able to navigate the Internet world and browsers.
Step 2: Enter your search terms into the search box (try to discover concepts like ‘Google
Suggest’ or ‘Autocomplete’, ‘Google Instant’
Step 2: Enter “wikipedia.org” on the search bar. Discover concepts like parameter strings, URL,
https, web address, and other symbols like the colon and forward slashes.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 1.2: URL overview
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter Two: Hyper Text Mark Up Language (HTML)
This chapter deals with Web page Design and development, information Architecture &
visualization, and Hyper Text Markup Language. Use tools like Notepad, Notepad++, Sublime
Text, Komodo Edit
Tip: You can use either .htm or .html as file extension. There is no
difference, it is up to you.
3. View the HTML page in your Browser. Open the saved HTML file in your favorite
browser (double click on the file, or right-click - and choose "Open with"). The result
will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 2.1: Hello World using HTML
Note that the steps used in the previous exercises are also used here. You better use a
Sublime code editor and save the files as described below. Use Google Chrome for your
exercise to view the results. Opening the saved files is always by double clicking on the
file or writing the file path in the browser’s bar.
1. Homepage.html
1. <!DOCTYPE html>
2. <html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
3. <body>
4. <h2>Placement</h2>
5. <h4 color = "orange">Overview</h4>
6. <p>GhionTech’s Training, Placement and Development
Cell plays a critical role in networking graduating
students with the industry. It prepares the students for
the process of recruitment and simultaneously create
awareness among companies about the recruitment
opportunities at GhionTech. Potential recruiters are given
structural support for scheduling interviews, hosting
seminars, group discussions and written tests</p>
7. <br>
8. <ul>
9. <h4>Training of students</h4>
10. <p>
11. <li>
12. A special corporate training program is
conducted for final year students in resume building, group
discussions, general knowledge, current affairs, etc.
13. </li>
14. <li>
15. Mock interviews are conducted by inviting
HR Heads and Technical Experts from well-known companies.
16. </li>
17. <li>
18. For expose to real-world work culture,
short industrial tours to neighboring companies and
extended visits to distant industries / organizations of
national and international repute are conducted each year.
19. </li>
20. <li>
21. Regular training classes are conducted,
on campus, at the Digital English Language Lab to improve
Web Programming Lab Manual Debre Tabor University Computer Science Department
the communication skills of students. With a focus on
Campus Recruitment, special training classes are conducted
in association with professional training institutes and
specialists in personality development, etiquette, grooming
etc.
22. </li>
23. <li>
24. On campus training for competitive exams
like GRE, GATE, CAT, etc. is also offered.
25. In order to bridge the gap between the university
curriculum and industry needs, the college offers various
short-term training programs. These programs include CAD /
CAM, J2JEE, VLSI & Embedded systems.
26. </li>
27. <li>
28. Seminars and workshops are conducted on
entrepreneurship development.
29. </li>
30. <li>
31. Placement Services
32. </li>
33. <li>
34. Internships and summer placement are ensured.
35. </li>
36. <li>
37. Towards the end of the final year, an Ad
campaign is launched in leading newspapers and journals to
attract prospective recruiters. Recruitment advertisements
are also collected, after thoroughly checking eligibility
conditions. For the convenience of students, recruitment
application forms are supplied for free of cost.
38. </li>
39. </p>
Web Programming Lab Manual Debre Tabor University Computer Science Department
40. </ul>
41. </body>
42. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
2. Loginpage.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> Login Page</title>
5. </head>
6. <body bgcolor="pink">
7. <center>
8. <strong><h1> Training and
Placement</h1></strong>
9. </center>
10. <center>
Web Programming Lab Manual Debre Tabor University Computer Science Department
11. <h2> Login</h2>
12. </center>
13. <center>
14. <table align="middle">
15. <tr>
16. <td>
17. <h4> User Name </h4>
18. </td>
19. <td>
20. <input type="text">
21. </td>
22. <td></td>
23. </tr>
24. <tr>
25. <td>
26. <h4> Password </h4>
27. </td>
28. <td>
29. <input type="Password">
30. </td>
31. </tr>
32. <tr>
33. <td>
34. <form method="post" action="catalog.html">
35. <input type="submit" value="Submit">
36.
37. </form>
38. </td>
39. <td>
40. <form method="post" action="userpro.html">
41. <input type="submit" value="Register">
42.
43. <input type="reset" value="Reset">
Web Programming Lab Manual Debre Tabor University Computer Science Department
44. </form>
45. </td>
46. </tr>
47. </table>
48. </center>
49.
50. </body>
51. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
3. Registrationpage.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> Login Page</title>
5. </head>
6. <body bgcolor="pink">
Web Programming Lab Manual Debre Tabor University Computer Science Department
7. <center>
8. <center><strong><h1> Training and Placement
Cell</h1></strong></center>
9. <form method="post" action="catalog.html">
10. <right>
11. <table align="middle">
12. <tr>
13. <td>
14. <h4> User Name</h4>
15. </td>
16. <td>
17. <input type="text">
18. </td>
19. </tr>
20. <tr>
21. <td>
22. <h4> Password </h4>
23. </td>
24. <td>
25. <input type="Password">
26. </td>
27. </tr>
28. <tr>
29. <td>
30. <h4> Confirm Passowrd </h4>
31. </td>
32. <td>
33. <input type="Passowrd">
34. </td>
35. </tr>
36. <tr>
37. <td>
38. <h4> Male</h4>
Web Programming Lab Manual Debre Tabor University Computer Science Department
39.
40. <input type="radio" name="sex" id="male">
41. </td>
42. <td>
43. <h4> Female </h4>
44.
45. <input type="radio" name="sex" id="Female">
46. </td>
47. </tr>
48. <tr>
49. <td> Address </td>
50. <td>
51. <textarea name="Address" rows="5"
cols="19"></textarea>
52. </td>
53. </tr>
54. <tr>
55. <td>
56. <input type="submit" value="submit">
57. </td>
58. <td>
59. <input type="reset" value="reset">
60. </td>
61. </tr>
62. </table>
63. </form>
64. </center>
65. </body>
66. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 2.4: Registration page
Web Programming Lab Manual Debre Tabor University Computer Science Department
17. GCS recognized as a TOP 100 brand
in Ethiopia by Ministry of Finance <br>
18. <u> read More</u>
19. </h2>
20. </p>
21. <p>
22. <h2>
23. <u> HBR Report: </u>
24. </h2>
25. </p>
26. <p>
27. <h2> How smart connected products are
transforming competition</h2>
28. </p>
29. <p> <h3><u> About Us: </u></h3></p>
30. <p><h2> GCS is a global leader in IT services
digital and business solution that partners with its
clients to simplify strengthen and transform their
business<br>
31. <u> read more</u></h2>
32. <h2>Careers word wide</h2>
33. <pre>
34. <h2>
35. Ethiopia
36. Africa
37. Asia
38. Australia
39. <u> read more</u>
40. </h2>
41. </pre>
42. </p>
43. </body>
44. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
1. <!DOCTYPE html>
2. <html>
3. <body bgcolor="pink">
4. <h2>Ghion Alumni Details</h2>
5. <h4> Overview</h4>
6. <p>
7. Welcome to Alumni Association Website of Ghion.
The Ghion-ALUMNI Association endeavours to involve alumni
with the Insitute, while also providing current students
access to a network of well-employed graduates. Members are
encouraged to inform Ghion's Training & Placement Cell
about potential job opportunities in their organisations.
They are also welcome to visit the Institute to deliver
special lectures in their respective fields. This
Web Programming Lab Manual Debre Tabor University Computer Science Department
interaction helps students bridge the gap between industry
experience and academic learning
8. </p>
9. <br>
10. <center>
11. <h2> Login </h2>
12. </center>
13. <center>
14. <table align="middle">
15. <tr>
16. <td>
17. <h4> User Name </h4>
18. </td>
19. <td>
20. <input type="text">
21. </td>
22. <td></td>
23. </tr>
24. <tr>
25. <td>
26. <h4> Password </h4>
27. </td>
28. <td>
29. <input type="Password">
30. </td>
31. <td></td>
32. </tr>
33. <tr>
34. <td>
35. <form method="post" action="catalog.html">
36. <input type="submit" value="submit">
37. </form>
38. </td>
Web Programming Lab Manual Debre Tabor University Computer Science Department
39. <td>
40. <form method="post" action="userpro.html">
41. <input type="submit" value="register">
42.
43. <input type="reset" value="reset">
44. </form>
45. </td>
46. </tr>
47. </table>
48. </center>
49. </body>
50. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
6. Student Personal Info page
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Student Personal</title>
5. </head>
6. <body bgcolor="pink">
7. <style type="text/css">
8. #heading{
9. border: 2px solid blue;
10. margin: 0px auto;
11. }
12. </style>
13. <div id="heading" align="center">
14. <h1> Student Personal Information</h1>
15. </div>
16. <table align="center">
17. <tr></tr>
18. <tr></tr>
19. <tr></tr>
20. <form>
21. <tr>
22. <td> First Name: </td>
23. <td><input type="text" name="firstname"></td>
24. </tr>
25. <tr></tr>
26. <tr>
27. <td> Last Name: </td>
28. <td><input type="text" name="firstname"></td>
29. </tr>
30. <tr>
31. <td> Father Name: </td>
Web Programming Lab Manual Debre Tabor University Computer Science Department
32. <td><input type="text" name="firstname"></td>
33. </tr>
34. <tr>
35. <td> Mother Name: </td>
36. <td><input type="text" name="firstname"></td>
37. </tr>
38. <tr>
39. <td> Gender: </td>
40. <td><input type="radio" name="gender"> Male</td>
41. <td><input type="radio" name="gender"> Female</td>
42. </tr>
43. <tr>
44. <td> DOB: </td>
45. <td><input type="date" id="DATE" name="date"
value="TODAY"></td>
46. </tr>
47. <tr>
48. <td>Category:</td>
49. <td>
50. <select>
51. <option value="cat"> Choose </option>
52. <option value="cat"> OC </option>
53. <option value="cat"> BC </option>
54. <option value="cat"> SC </option>
55. <option value="cat"> ST </option>
56. </select>
57. </td>
58. </tr>
59.
60. <tr>
61. <td>Religion:</td>
62. <td>
63. <select>
Web Programming Lab Manual Debre Tabor University Computer Science Department
64. <option value="cat"> Choose </option>
65. <option value="rel"> Orthodox </option>
66. <option value="rel"> Muslim </option>
67. <option value="rel"> Protestant </option>
68. <option value="rel"> Judaism </option>
69. </select>
70. </td>
71. </tr>
72. <tr>
73. <td> Hobbies: </td>
74. <td><input type="text" name="firstname"></td>
75. </tr>
76. <tr>
77. <td> Languages Known: </td>
78. <td><input type="text" name="firstname"></td>
79. </tr>
80. <tr>
81. <td> Address: </td>
82. <td><input type="text" name="firstname"
size="20"></td>
83. </tr>
84. <tr>
85. <td> Mobile Number: </td>
86. <td><input type="text" name="firstname"></td>
87. </tr>
88. <tr>
89. <td> Email Address: </td>
90. <td><input type="text" name="firstname"
value="[email protected]"></td>
91. </tr>
92. <tr>
93. <td><input type="button" name="submit"
value="submit"></td>
Web Programming Lab Manual Debre Tabor University Computer Science Department
94. <td><input type="button" name="cancel"
value="cancel"></td>
95. </tr>
96. </form>
97. </table>
98. </body>
99. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Student Academical</title>
5. </head>
Web Programming Lab Manual Debre Tabor University Computer Science Department
6. <body bgcolor="pink">
7. <style type="text/css">
8. #heading{
9. border: 2px solid blue;
10. margin: 0px auto;
11. }
12. </style>
13. <div id="heading" align="center">
14. <h1> Student Academic Information</h1>
15. </div>
16. <table align="center">
17. <tr></tr>
18. <tr></tr>
19. <tr></tr>
20. <form>
21. <tr>
22. <th>10th:</th>
23. <td><input type="text" name="10th"></td>
24. <td>School Name:</td>
25. <td><input type="text" name="10th"></td>
26. </tr>
27. <tr>
28. <th>SELECT<select>
29. <option value="sel">Inter</option>
30. <option value="sel">Polytechnic</option>
31. </select></th>
32. <td>Percentage: </td>
33. <td><input type="text" name="inter"></td>
34. <td>Group:</td>
35. <td><input type="text" name="inter"></td>
36. <td>College Name:</td>
37. <td><input type="text" name="inter"></td>
38. </tr>
Web Programming Lab Manual Debre Tabor University Computer Science Department
39. <tr>
40. <th>B. Tech</th>
41. <td>Percentage: </td>
42. <td><input type="text" name="inter"></td>
43. <td>Branch:</td>
44. <td><input type="text" name="inter"></td>
45. <td>College Name:</td>
46. <td><input type="text" name="inter"></td>
47. </tr>
48. <tr>
49. <td><input type="button" name="submit"
value="submit"></td>
50. <td><input type="button" name="cancel"
value="cancel"></td>
51. </tr>
52. </form>
53. </table>
54. </body>
55. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 2.8: Student Academic Information page
8. Semester wise percentage and aggregate page
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>Semester</title>
5. </head>
6. <body bgcolor="pink">
7. <style type="text/css">
8. #heading{
9. border: 2px solid blue;
10. margin: 0px auto;
11. }
12. </style>
13. <div id="heading" align="center">
14. <h1> Semester Wise Aggregate</h1>
15. </div>
16. <table align="center" height= "30">
17. <tr></tr>
18. <tr></tr>
19. <tr></tr>
20. <form>
Web Programming Lab Manual Debre Tabor University Computer Science Department
21. <tr>
22. <th> First Year</th>
23. <td> 1-1 SGPA: </td>
24. <td><input type="text" name="firstyear"></td>
25. <td> 1-2 SGPA: </td>
26. <td><input type="text" name="firstyear"></td>
27. </tr>
28. <tr>
29. <td></td>
30. <td>Backlogs
31. <input type="radio" name="bl"> yes</td>
32. <td><input type="radio" name="bl"> No</td>
33. </tr>
34. <tr>
35. <td></td>
36. <td> No. of backlogs</td>
37. <td><input type="text" name="firstname"></td>
38. </tr>
39. <tr>
40. <th> Second Year</th>
41. <td> 2-1 SGPA: </td>
42. <td><input type="text" name="firstname"></td>
43. <td> 2-2 SGPA: </td>
44. <td><input type="text" name="firstname"></td>
45. </tr>
46. <tr>
47. <td></td>
48. <td>Backlogs
49. <input type="radio" name="bl"> yes</td>
50. <td><input type="radio" name="bl"> No</td>
51. </tr>
52. <tr>
53. <td></td>
Web Programming Lab Manual Debre Tabor University Computer Science Department
54. <td> No. of backlogs</td>
55. <td><input type="text" name="firstname"></td>
56. </tr>
57. <tr>
58. <th> Third Year</th>
59. <td> 3-1 SGPA: </td>
60. <td><input type="text" name="firstname"></td>
61. <td> 3-2 SGPA: </td>
62. <td><input type="text" name="firstname"></td>
63. </tr>
64. <tr>
65. <td></td>
66. <td>Backlogs
67. <input type="radio" name="bl"> yes</td>
68. <td><input type="radio" name="bl"> No</td>
69. </tr>
70. <tr>
71. <td></td>
72. <td> No. of backlogs</td>
73. <td><input type="text" name="firstname"></td>
74. </tr>
75. <tr>
76. <th> Fourth Year</th>
77. <td> 4-1 SGPA: </td>
78. <td><input type="text" name="firstname"></td>
79. <td> 4-2 SGPA: </td>
80. <td><input type="text" name="firstname"></td>
81. </tr>
82. <tr>
83. <td></td>
84. <td>Backlogs
85. <input type="radio" name="bl"> yes</td>
86. <td><input type="radio" name="bl"> No</td>
Web Programming Lab Manual Debre Tabor University Computer Science Department
87. </tr>
88. <tr>
89. <td></td>
90. <td> No. of backlogs</td>
91. <td><input type="text" name="firstname"></td>
92. </tr>
93. <tr>
94. <th> CGPA</th>
95. <td><input type="text" name="firstname"></td>
96. </tr>
97. <tr>
98. <td><input type="button" name="submit"
value="submit"></td>
99. <td><input type="button" name="cancel"
value="cancel"></td>
100. </tr>
101. </form>
102. </table>
103. </body>
104. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 2.9: Semester Wise Aggregate page
1. <!DOCTYPE html>
2. <html>
3. <body bgcolor="pink"> <br><br>
4. <script type="text/javascript">
5. function validate(){
6. var flag = 1;
7. if (document.myform.id.value == "" ||
8. document.myform.pwd.value == "") {
9. alert("Login ID and Password must be
filled")
10. flag = 0;
11. }
12. if (flag == 1) {
13. alert("valid input");
14. window.open("catalog.html",
"right");
Web Programming Lab Manual Debre Tabor University Computer Science Department
15. }
16. else{
17. alert("Invalid input");
18. }
19. }
20. </script>
21. <form name="myform">
22. <div align="center">
23. <pre>
24. LOGIN ID: <input type="text" name="id"><br>
25. PASSWORD: <input type="Password" name="pwd"><br><br>
26. </pre>
27. <input type="button" value="ok" onclick="validate()">
28. <input type="reset" value="clear">
29. </div>
30. </form>
31. </body>
32. </html>
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 2.10: Login Validation
10. Registration Validation
1. <!DOCTYPE html>
2. <html>
3. <body bgcolor="pink">
4. <br><br>
5. <script type="text/javascript">
6. function validate(){
7. var flag = 1;
8. if (document.myform.name.value = "" ||
9. document.myform.addr.value = "" ||
10. document.myform.phno.value = "" ||
11. document.myform.id.value = "" ||
12. document.myform.pwd.value = "") {
13.
14. alert("Enter all the details");
15. flag = 0;
16. }
17. var str = document.myform.phno.value;
Web Programming Lab Manual Debre Tabor University Computer Science Department
18. var x = new RegExp("\\d","g");
19. if (!(str.match(x))) {
20. if (!(str.length = 10))
21. flag = 0;
22. }
23. var str1 = document.myform.id.value;
24. var x1 = new RegExp("^[A-Z][a-zA-Z] + $", "g");
25. if (!(str1.match(x1))) {
26. flag = 0;
27. alert("Invalid UserID");
28. }
29. var str1 = document.myform.pwd.value;
30. var x1 = new RegExp("^[A-Z][a-zA-Z] + $", "g");
31. if (!(str1.match(x1))) {
32. flag = 0;
33. alert("Invalid UserID");
34. }
35. if (flag == 1) {
36. alert("Valid Input");
37. window.self.location.href = "login.html";
38. }
39. else{
40. alert("Invalid Input");
41. document.myform.focus();
42. }
43. }
44. </script>
45. <form name="myform">
46. <div align="center">
47. <pre>
48. NAME: <input type="text" name="name"><br>
49. ADDRESS: <input type="type" name="addr"><br>
50. CONTACT NUMBER: <input type="text" name="phno"> <br>
Web Programming Lab Manual Debre Tabor University Computer Science Department
51. LOGINID: <input type="text" name="id"> <br>
52. PASSWORD: <input type="password" name="pwd">
53. </pre> <br><br>
54. </div>
55. <br><br>
56. <div align="center">
57. <input type="button" value = "ok"
onclick="validate()">
58. <input type="reset" value="clear">
59. </div>
60. </form>
61. </body>
62. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter Three: Cascading Style Sheet (CSS)
CSS is used to define styles for your web pages, including the design, layout and variations in
display for different devices and screen sizes.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <style>
5. body {
6. background-color: lightblue;
7. }
8. h1{
9. color: green;
10. text-align: center;
11. }
12. p {
13. font-family: verdana;
14. font-size: 20px;
15. text-align: center;
16. }
17. </style>
18. </head>
19. <body>
20. <h1>My First CSS Example.</h1>
21. <p>This is a paragraph.</p>
22. </body>
23. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
The style attribute includes a series of CSS property and value pairs. Each "property: value" pair
is separated by a semicolon (;), just as you would write into an embedded or external style
sheets. But it needs to be all in one line i.e., no line break after the semicolon, as shown here:
Exercise 12: try the following codes in your code editor
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>Example of CSS Inline Styles</title>
6. </head>
7. <body>
Web Programming Lab Manual Debre Tabor University Computer Science Department
8. <h1 style="color:red; font-size:30px;">This is a heading</h1>
9. <p style="color:green; font-size:22px;">This is a paragraph.</p>
10. <div style="color:blue; font-size:14px;">This is some text content.</div>
11. </body>
12. </html>
Embedded style sheets are defined in the <head> section of an HTML document using the
<style> element. You can define any number of <style> elements in an HTML document but
they must appear between the <head> and </head> tags. Let's take a look at an example:
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>Example of CSS Embedded Style Sheet</title>
6. <style>
7. body { background-color: YellowGreen; }
8. p { color: #fff; }
9. </style>
10. </head>
11. <body>
12. <h1>This is a heading</h1>
13. <p>This is a paragraph of text.</p>
14. </body>
15. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Experiment 3.4: External Style Sheets
An external style sheet is ideal when the style is applied to many pages of the website. An
external style sheet holds all the style rules in a separate document that you can link from any
HTML file on your site. External style sheets are the most flexible because with an external style
sheet, you can change the look of an entire website by changing just one file.
You can attach external style sheets in two ways — linking and importing.
Before linking, we need to create a style sheet first. Let's open your favorite code editor and
create a new file. Now type the following CSS code inside this file and save it as "style.css".
1. body {
2. background: lightyellow;
3. font: 18px Arial, sans-serif;
4. }
5. h1{
6. color: orange;
7. }
An external style sheet can be linked to an HTML document using the <link> tag. The <link> tag
goes inside the <head> section, as you can see in the following example:
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <title>My HTML Document</title>
5. <link rel="stylesheet" href="style.css">
6. </head>
7. <body>
8. <h1>This is a heading</h1>
9. <p>This is a paragraph of text.</p>
10. </body>
11. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Universal Selector
The universal selector, denoted by an asterisk (*), matches every single element on the page. The
universal selector may be omitted if other conditions exist on the element. This selector is often
used to remove the default margins and paddings from the elements for quick testing purpose.
Let's try out the following example to understand how it basically works:
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="utf-8">
5. <title>Example of CSS universal selector</title>
6. <style>
7. *{
8. margin: 0;
9. padding: 0;
10. color: red;
11. }
12. </style>
13. </head>
14. <body>
15. <h1>This is heading</h1>
16. <p>This is a paragraph.</p>
17. </body>
18. </html>
The style rules inside the * selector will be applied to every element in a document.
Apply different font styles, font families, font colors and other formatting styles to the above
static web pages
1. <!DOCTYPE html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
2. <html>
3. <head>
4. <title></title>
5. <style type="text/css">
6. a:link {color: "orange";}
7. a:visited {color: "red";}
8. a:hover {color: green;}
9. a:active {color: yellow;}
10.
11. H1{
12. color: rgb(50, 100, 150);
13. text-align: right;
14. font-family: Times new roman;
15. }
16. H6{
17. color: green;
18. text-align: center;
19. font-family: Verdana;
20. }
21. </style>
22. </head>
23. <body>
24. <p>Mouse over the words to change the cursor.</p>
25. <span style="cursor:auto">auto</span><br/>
26. <span style="cursor:crosshair">crosshair</span><br/>
27. <span style="cursor:default">default</span><br/>
28. <span style="cursor:e-resize">e-resize</span><br/>
29. <span style="cursor:help">help</span><br/>
30. <span style="cursor:move">move</span><br/>
31. <span style="cursor:n-resize">n-resize</span><br/>
32. <span style="cursor:ne-resize">ne-resize</span><br/>
Web Programming Lab Manual Debre Tabor University Computer Science Department
33. <span style="cursor:nw-resize">nw-resize</span><br/>
34. <span style="cursor:pointer">pointer</span><br/>
35. <span style="cursor:progress">progress</span><br/>
36. <span style="cursor:s-resize">s-resize</span><br/>
37. <span style="cursor:se-resize">se-resize</span><br/>
38. <span style="cursor:sw-resize">sw-resize</span><br/>
39. <span style="cursor:text">text</span><br/>
40. <span style="cursor:w-resize">w-resize</span><br/>
41. <span style="cursor:wait">wait</span><br/>
42.
43. background-image:url("Sunset.jpg");
44. background-repeat: no-repeat;
45. <div style="position: static; border-style: solid; color: red; top: 100px; right:
150px;"> CS</div><br>
46. <div style="position: static; border-style: dashed; color: blue;"> IT</div>
47. <div align="right"> sdasdadadadasdased</div>
48. <h1> Welcome to CS</h1>
49. <h6> Welcome to Internal CS</h6>
50. </body>
51. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Open the saved HTML file in your favorite browser (double click on the file, or right-click - and
choose "Open with"). The result will look much like this:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter Four: JavaScript
Experiment 4.1: Simple Calculator using JavaScript
Write a JavaScript to design a simple calculator to perform the following operations: sum,
product, difference and quotient.
CODE:
1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <style>
5. table, td, th {
6. border: 1px solid black;
7. width: 33%;
8. text-align: center;
9. background-color: DarkGray;
10. border-collapse:collapse;
11. }
12. table { margin: auto; }
13. input { text-align:right; }
14. </style>
15. <script type="text/javascript">
16. function calc(clicked_id) {
17. var val1 = parseFloat(document.getElementById("value1").value);
18. var val2 = parseFloat(document.getElementById("value2").value);
19. if(isNaN(val1)||isNaN(val2))
20. alert("ENTER VALID NUMBER");
21. else if(clicked_id=="add")
22. document.getElementById("answer").value=val1+val2;
23. else if(clicked_id=="sub")
24. document.getElementById("answer").value=val1-val2;
25. else if(clicked_id=="mul")
26. document.getElementById("answer").value=val1*val2;
27. else if(clicked_id=="div")
Web Programming Lab Manual Debre Tabor University Computer Science Department
28. document.getElementById("answer").value=val1/val2;
29. }
30. function cls() {
31. value1.value="0";
32. value2.value="0";
33. answer.value="";
34. }
35. </script>
36. </head>
37. <body>
38. <table>
39. <tr>
40. <th colspan="4"> SIMPLE CALCULATOR </th>
41. </tr>
42. <tr>
43. <td>value1</td>
44. <td><input type="text" id="value1" value="0"/></td>
45. <td>value2</td>
46. <td><input type="text" id="value2" value="0"/></td></tr>
47. <tr>
48. <td><input type="button" value="Addition" id = "add" onclick="calc(this.id)"/></td>
49. <td><input type="button" value="Subtraction" id = "sub" onclick="calc(this.id)"/></td>
50. <td><input type="button" value="Multiplication" id = "mul" onclick="calc(this.id)"/></td>
51. <td><input type="button" value="Division" id ="div" onclick="calc(this.id)"/></td>
52. </tr>
53. <tr>
54. <td>Answer:</td><td> <input type="text" id="answer" value="" disabled/></td>
55. <td colspan="2"><input type="button" value="CLEAR ALL" onclick="cls()"/></td>
56. </tr>
57. </table>
58. </body>
59. </html>
Output:
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 4.1: Calculator using JavaScript
1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <style>
5. table,tr, td {
6. border: solid black;
7. width: 33%;
8. text-align: center;
9. border-collapse: collapse;
10. background-color:lightblue;
11. }
12. table { margin: auto; }
13. </style>
14. <script>
15. document.write( "<table> <tr><th colspan='3'> NUMBERS FROM
0 TO 10 WITH THEIR SQUARES AND CUBES </th></tr>" );
16. document.write( "<tr> <td>Number</td> <td>Square</td>
<td>Cube</td> </tr>" );
Web Programming Lab Manual Debre Tabor University Computer Science Department
17. for(var n=0; n<=10; n++) {
18. document.write( "<tr><td>" + n + "</td><td>" + n*n +
"</td><td>" +
19. n*n*n + "</td></tr>" ) ;
20. }
21. document.write( "</table>" ) ;
22. </script>
23. </head>
24. </html>
Output:
Web Programming Lab Manual Debre Tabor University Computer Science Department
1. <!DOCTYPE HTML>
2. <html>
3. <head>
4. <style>
5. p{
6. position: absolute;
7. top: 50%;
8. left: 50%;
9. transform: translate(-50%, -50%);
10. }
11. </style>
12. </head>
13. <body>
14. <p id="demo"></p>
15. <script>
16. var var1 = setInterval(inTimer, 1000);
17. var fs = 5;
18. var ids = document.getElementById("demo");
19. function inTimer() {
20. ids.innerHTML = 'TEXT GROWING';
21. ids.setAttribute('style', "font-size: " + fs + "px; color: red");
22. fs += 5;
23. if(fs >= 50 ){
24. clearInterval(var1);
25. var2 = setInterval(deTimer, 1000);
26. }
27. }
28. function deTimer() {
29. fs -= 5;
30. ids.innerHTML = 'TEXT SHRINKING';
31. ids.setAttribute('style', "font-size: " + fs + "px; color: blue");
Web Programming Lab Manual Debre Tabor University Computer Science Department
32. if(fs === 5 ){
33. clearInterval(var2);
34. }
35. }
36. </script>
37. </body>
38. </html>
Discuss the output with your colleagues.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter Five: PHP
Experiment 5.1: Hello World using PHP scripts embedded in HTML
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> PHP - Hello World!</title>
5. </head>
6. <body>
7. <h1>
8. <?php
9. echo "Hello World";
10. ?>
11. </h1>
12. </body>
13. </html>
This would output a “Hello World” content in your browser.
Web Programming Lab Manual Debre Tabor University Computer Science Department
14. </h1>
15. </body>
16. </html>
Experiment 5.3: Outputting text and variables with the print statement
1. <!DOCTYPE html>
2. <html>
3. <?php
4. $name = "Students";
5. ?>
6. <head>
7. <title> Simple PHP Declaration!</title>
8. </head>
9. <body>
10. <?php
11. $text1 = "Learn PHP";
12. $text2 = "Debre Tabor University, Computer Science Dep't";
Web Programming Lab Manual Debre Tabor University Computer Science Department
13.
14. $num1 = 5;
15. $num2 = 4;
16.
17.
18. print "<h2>" . $text1 . "</h2>";
19. print "Study PHP at " . $text2 . "<br>";
20.
21. Print $num1 + $num2;
22. ?>
23. </body>
24. </html>
1. <!DOCTYPE html>
2. <html>
3. <?php
4. $name = "Students";
5. ?>
6. <head>
7. <title> Simple PHP Declaration!</title>
8. </head>
9. <body>
10. <?php
11. //This is a single-line comment
12. # This is also a single-line comment
13.
14. #Declaring variables
Web Programming Lab Manual Debre Tabor University Computer Science Department
15. $text1 = "Hello World";
16. $x = 3;
17. $y = 4.1;
18.
19. echo "The first code in programming is " . $text1 . "!" . "<br>" . "<br>";
20. echo $x + $y;
21.
22. echo "<br>";
23.
24. echo strlen($text1);
25. echo "<br>";
26. echo strrev("\nHello World\n")
27. ?>
28. </body>
29. </html>
Exercise: what do you learn from the above example?
Experiment 5.5: Design HTML Form and retrieve the values in PHP Script
THEORY:
Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3,
...)). This array holds key/value pairs, where keys are the names of the form controls and values
are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are super globals, which means
that they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Information sent from a form with the GET method is visible to everyone (all variable names and
Web Programming Lab Manual Debre Tabor University Computer Science Department
values are displayed in the URL). GET also has limits on the amount of information to send. The
limitation is about 2000 characters. However, because the variables are displayed in the URL, it
is possible to bookmark the page. This can be useful in some cases.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request) and has no limits on the amount of information
to send. More over POST supports advanced functionality such as support for multi-part binary
input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the
page.
The Program:
1. <!DOCTYPE html>
2. <html>
3. <?php
4. $name = "Students";
5. ?>
6. <head>
7. <title> Simple PHP Forms and Retrieving using post! </title>
8. </head>
9. <body>
10. <form action="welcome.php" method="post">
11. Name: <input type="text" name="name"> <br>
12. E-mail: <input type="text" name="email"><br>
13. <input type="submit">
Web Programming Lab Manual Debre Tabor University Computer Science Department
14. </form>
15. </body>
16. </html>
When the user fills out the form above and clicks the submit button, the form data is sent for
processing to a PHP file named "welcome.php". The form data is sent with the HTTP POST
method. To display the submitted data you could simply echo all the variables. The
"welcome.php" looks like this:
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title></title>
5. </head>
6. <body>
7. Welcome <?php echo $_POST['name']; ?> <br>
8. Your email address is: <?php echo $_POST['email']; ?>
9. </body>
10. </html>
Web Programming Lab Manual Debre Tabor University Computer Science Department
Experiment 5.6: PHP Variables and Arrays
THEORY:
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for PHP variables:
•A variable starts with the $ sign, followed by the name of the variable
•A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
•A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
Remember that PHP variable names are case-sensitive!
PHP is a Loosely Typed Language
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has three different variable scopes: local, global, static
What is an Array?
• An array is a special variable, which can hold more than one value at a time.
• If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
• $cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
• However, what if you want to loop through the cars and find a specific one? And what if you
had not 3 cars, but 300?
• The solution is to create an array!
• An array can hold many values under a single name, and you can access the values by referring
to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
Web Programming Lab Manual Debre Tabor University Computer Science Department
array();
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
• There are two ways to create indexed arrays:
• The index can be assigned automatically (index always starts at 0), like this:
• $cars = array("Volvo", "BMW", "Toyota");
• or the index can be assigned manually:
• $cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Abebe"=>"35", "Amelga"=>"37", "Dawit"=>"43");
or:
$age['Abebe'] = "35";
$age['Amelga'] = "37";
$age['Dawit'] = "43";
PHP - Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.
PHP understands multidimensional arrays that are two, three, four, five, or more levels deep.
However, arrays more than three levels deep are hard to manage for most people.
The dimension of an array indicates the number of indices you need to select an element.
• For a two-dimensional array you need two indices to select an element
• For a three-dimensional array you need three indices to select an element
• PHP - Two-dimensional Arrays
•A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of
arrays).
Web Programming Lab Manual Debre Tabor University Computer Science Department
• We can store the data from the table above in a two-dimensional array, like this:
• $cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
• Now the two-dimensional $cars array contains four arrays, and it has two indices: row and
column.
1. <body>
2. <?php
3. $cars = array("Volvo", "BMW", "Toyota");
4. echo "I like " . $cars[0]. " and ". $cars[1] . ".";
5. ?>
6. </body>
Web Programming Lab Manual Debre Tabor University Computer Science Department
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function
PHP 5 String Functions
Function Description
print() Outputs one or more strings
printf() Outputs a formatted string
sprintf() Writes a formatted string to a variable
sscanf() Parses input from a string according to a format
str_pad() Pads a string to a new length
str_repeat() Repeats a string a specified number of times
str_replace() Replaces some characters in a string (case-sensitive)
str_split() Splits a string into an array
str_word_count() Count the number of words in a string
strcasecmp() Compares two strings (case-insensitive)
strchr() Finds the first occurrence of a string inside another string (alias of strstr())
strcmp() Compares two strings (case-sensitive)
strcoll() Compares two strings (locale based string comparison)
strlen() Returns the length of a string
strnatcasecmp() Compares two strings using a "natural order" algorithm (case-insensitive)
PHP Date/Time Introduction
The date/time functions allow you to get the date and time from the server where your PHP
script runs.
You can then use the date/time functions to format the date and time in several ways.
Function Description
checkdate() Validates a Gregorian date
date_add() Adds days, months, years, hours, minutes, and seconds to a date
date_create_from_format() Returns a new DateTime object formatted according to a specified format
date_create() Returns a new DateTime object
Web Programming Lab Manual Debre Tabor University Computer Science Department
It is based on the Julian Day Count, which is a count of days starting from January 1st, 4713 B.C.
Note: To convert between calendar formats, you must first convert to Julian Day Count, then to
the
calendar of your choice.
Note: The Julian Day Count is not the same as the Julian Calendar!
Function Description
cal_days_in_month() Returns the number of days in a month for a specified year and calendar
cal_from_jd() Converts a Julian Day Count into a date of a specified calendar
cal_info() Returns information about a specified calendar
cal_to_jd() Converts a date in a specified calendar to Julian Day Count
easter_date() Returns the Unix timestamp for midnight on Easter of a specified year
Returns the number of days after March 21, that the Easter Day is in a specified
easter_days()
year
frenchtojd() Converts a French Republican date to a Julian Day Count
gregoriantojd() Converts a Gregorian date to a Julian Day Count
jddayofweek() Returns the day of the week
jdmonthname() Returns a month name
PROGRAM
Example Of Array_flip Function
<?php
$array = array
(
"a" => "apple",
"b" => "banana",
"o"=>"orange"
);
print_r( array_flip($array) );
?>
Output Of Given Php Script
Array ( [apple] => a [banana] => b [orange] => o )
Example Of Array Count Function
<?php
$name = array ("php","java","html");
$a=count($name);
echo "Number of element in an array: ";
Web Programming Lab Manual Debre Tabor University Computer Science Department
echo $a;
?>
Output Of Given PHP Script
Number of element in an array: 3
Example Of Array Sum Function
<?php
$num = array(20, 50, 10);
echo "sum of array = " . array_sum($num);
?>
Output Of Given PHP Script
sum of array = 80
Example Of Strstr Function
<?php
$string = "understanding means transforming some text";
$txt = "some";
echo strstr($string, $txt);
?>
Output Of Given Php Script
some text
Example Of Strrev Function
<?php
echo strrev("Welcome to PHP");
?>
Output Of Given PHP Script
PHP ot emoclew
Example Of Strlen Function
<?php
$name="John";
if ( strlen( $name ) != 5 )
{
echo "Correct input.";
Web Programming Lab Manual Debre Tabor University Computer Science Department
}
else
{
echo "incorrect input";
}
?>
Output Of Given PHP Script
Correct input
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
OUTPUT:
Today is 2022/01/29
Today is 2022.01.29
Today is 2022-01-29
Today is Wednesday
<?php
echo "The time is " . date("h:i:sa");
?>
OUTPUT:
The time is 01:33:17am
Web Programming Lab Manual Debre Tabor University Computer Science Department
• Windows Computers:
The personal Web server that will be used in this class for Windows computers is named
WampServer. WampServer is a free to use open-source project that installs and configures
Apache, MySQL, and PHP on a Windows computer. With WampServer you don’t need to
install the individual software components separately. WampServer will quickly and easily
install and configure a complete personal Web server. The WAMP (Windows, Apache,
MySQL, and PHP) is very easy to install and to use, just download, extract and start.
SQLitemanager, The Phpmyadmin comes along with WAMP server which gives a very good
user interface to manage MySQL.
If you are using a Windows computer follow the steps in this document beginning on next
page.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Go to the official website https://www.wampserver.com/en/ and download the WampServer
setup. There are two versions of WampServer are available i.e. 64-bits (x64) and 32-bits (x86),
choose according to your computer’s configuration.
As soon as you will click on the download option, a pop up will appear showing some warnings.
Just don’t worry about these warning rather simply click on the link “download directly” like
Web Programming Lab Manual Debre Tabor University Computer Science Department
shown below and move ahead with the download process.
Soon after you click on the downloaded file, you will be asked to choose your preferred language
and click the “Ok” button. As I’m choosing English here. See below.
Web Programming Lab Manual Debre Tabor University Computer Science Department
he next screen you will see is about the license agreement. Click on the “I accept the agreement”
radio button and then the “Next” button to continue with the installation shown below.
The next screen will inform you about the required components that have to be present in your
computer system for the proper functioning of the WampServer. The main purpose of this step is
to check for the suitable version of Microsoft VC++ re-distributable package. Click on the ‘Next’
to continue.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Step 3: Select location/destination to install WAMP
Here, you need to select the location to install the WAMP on your computer. However, you can
accept the default location and move ahead. To continue with the installation hit the ‘Next’
button.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Step 4: Select Start Menu Folder to Install WAMP
Now, you need to select the folder where you wish to create the program’s shortcut. You can
select any folder of your choice or you can continue with the default option. You can easily
access this folder from the Windows start button. Choose the folder and click ‘Next’ to continue.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Step 5: ready to install WAMP
Finally, you would see a ready to install wizard with a ready setup to begin the installation. Just
hit the ‘Install’ button to begin the installation procedure.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Experiment 5.9: MySQL connectivity, INSERT, DELETE, SELECT WITH PHP
THEORY:
After a database and a table have been created, we can start adding data in them.
Here are some syntax rules to follow:
• The SQL query must be quoted in PHP
• String values inside the SQL query must be quoted
• Numeric values must not be quoted
• The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Select Data From a MySQL Database
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
or we can use the * character to select ALL columns from a table:
Web Programming Lab Manual Debre Tabor University Computer Science Department
SELECT * FROM table_name
Delete Data From a MySQL Table Using MySQLi and PDO
The DELETE statement is used to delete records from a table:
DELETE FROM table_name
WHERE some_column = some_value
PROGRAM:
The following examples add a new record to the "MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The following example selects the id, firstname and lastname columns from the MyGuests table and displays it on
the page:
<?php
$servername = "localhost";
Web Programming Lab Manual Debre Tabor University Computer Science Department
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
OUTPUT:
id: 1 - Name: John Doe
id: 2 - Name: Mary Moe
id: 3 - Name: Julie Dooley
The following examples delete the record with id=3 in the "MyGuests" table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
Web Programming Lab Manual Debre Tabor University Computer Science Department
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to delete a record
$sql = "DELETE FROM MyGuests WHERE id=3";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
$conn->close();
?>
After the record is deleted, the table will look like this:
id firstname lastname email reg_date
2014-10-22
1 John Doe [email protected]
14:26:15
2014-10-23
2 Mary Moe [email protected]
10:22:30
Web Programming Lab Manual Debre Tabor University Computer Science Department
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully"
?>
Output:
Connected successfully
Web Programming Lab Manual Debre Tabor University Computer Science Department
PROGRAM:
Create The HTML Form
Next, create an HTML form that allow users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
Web Programming Lab Manual Debre Tabor University Computer Science Department
?>
Conclusion: Hence we have implemented file uploading in PHP.
Web Programming Lab Manual Debre Tabor University Computer Science Department
Starting a PHP Session
A PHP session is easily started by making a call to the session_start()function.This function first
checks if a session is already started and if none is started then it starts one. It is recommended to
put
the call to session_start() at the beginning of the page.
Session variables are stored in associative array called $_SESSION[]. These variables can be
accessed
during lifetime of a session.
The following example starts a session then register a variable called counterthat is incremented
each
time the page is visited during the session.
Make use of isset() function to check if session variable is already set or not.
Destroying a PHP Session
A PHP session can be destroyed by session_destroy() function. This function does not need any
argument and a single call can destroy all the session variables. If you want to destroy a single
session
variable then you can use unset() function to unset a session variable.
PHP login with session
Php login script is used to provide the authentication for our web pages. the Script executes after
submitting the user login button.
Login Page
Login page should be as follows and works based on session. If the user close the session, it will
erase
the session data.
PROGRAM:
<?php
ob_start();
session_start();
?>
<?
// error_reporting(E_ALL);
Web Programming Lab Manual Debre Tabor University Computer Science Department
// ini_set("display_errors", 1);
?>
<html lang = "en">
<head>
<title>Tutorialspoint.com</title>
<link href = "css/bootstrap.min.css" rel = "stylesheet">
<style>
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #ADABAB;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
color: #017572;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
Web Programming Lab Manual Debre Tabor University Computer Science Department
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
border-color:#017572;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
border-color:#017572;
}
h2{
text-align: center;
color: #017572;
}
</style>
</head>
<body>
<h2>Enter Username and Password</h2>
<div class = "container form-signin">
<?php
$msg = '';
if (isset($_POST['login']) && !empty($_POST['username'])
&& !empty($_POST['password'])) {
if ($_POST['username'] == 'tutorialspoint' &&
$_POST['password'] == '1234') {
$_SESSION['valid'] = true;
$_SESSION['timeout'] = time();
$_SESSION['username'] = 'tutorialspoint';
echo 'You have entered valid use name and password';
Web Programming Lab Manual Debre Tabor University Computer Science Department
}else {
$msg = 'Wrong username or password';
}
}
?>
</div> <!-- /container -->
<div class = "container">
<form class = "form-signin" role = "form"
action = "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);
?>" method = "post">
<h4 class = "form-signin-heading"><?php echo $msg; ?></h4>
<input type = "text" class = "form-control"
name = "username" placeholder = "username = tutorialspoint"
required autofocus></br>
<input type = "password" class = "form-control"
name = "password" placeholder = "password = 1234" required>
<button class = "btn btn-lg btn-primary btn-block" type = "submit"
name = "login">Login</button>
</form>
Click here to clean <a href = "logout.php" tite = "Logout">Session.
</div>
</body>
</html>
Logout.php
It will erase the session data.
<?php
session_start();
unset($_SESSION["username"]);
unset($_SESSION["password"]);
echo 'You have cleaned session';
header('Refresh: 2; URL = login.php');
?>
Result
Web Programming Lab Manual Debre Tabor University Computer Science Department
Figure 5.3: PHP script for session management
Web Programming Lab Manual Debre Tabor University Computer Science Department
Chapter Six: AJAX
Experiment 6.1: AJAX Script using XMLHttpRequest PHP.
THEORY:
What is AJAX ?
• AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating
better, faster, and
more interactive web applications with the help of XML, HTML, CSS and Java Script.
• Conventional web application transmit information to and from the sever using synchronous
requests. This
means you fill out a form, hit submit, and get directed to a new page with new information from
the server.
• With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the
results and
update the current screen. In the purest sense, the user would never know that anything was even
transmitted
to the server.
PROGRAM:
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
Web Programming Lab Manual Debre Tabor University Computer Science Department
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}<
/script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
Result:
The XMLHttpRequest Object
Start typing a name in the input field below:
First name: a
THEORY:
To clearly illustrate how easy it is to access information from a database using Ajax and PHP, we
are
going to build MySQL queries on the fly and display the results on "ajax.html". But before we
proceed,
let’s do ground work. Create a table using the following command.
NOTE - We are assuming you have sufficient privilege to perform following MySQL
Web Programming Lab Manual Debre Tabor University Computer Science Department
operations.
CREATE TABLE `ajax_example` (
`name` varchar(50) NOT NULL,
`age` int(11) NOT NULL,
`sex` varchar(1) NOT NULL,
`wpm` int(11) NOT NULL,
PRIMARY KEY (`name`)
)
Now dump the following data into this table using the following SQL statements.
INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);
PROGRAM:
Client Side HTML file
Now lets have our client side HTML file which is ajax.html and it will have following code
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try {
Web Programming Lab Manual Debre Tabor University Computer Science Department
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
Web Programming Lab Manual Debre Tabor University Computer Science Department
</script>
<form name = 'myForm'>
Max Age: <input type = 'text' id = 'age' /> <br />
Max WPM: <input type = 'text' id = 'wpm' />
<br />
Sex: <select id = 'sex'>
<option value = "m">m</option>
<option value = "f">f</option>
</select>
<input type = 'button' onclick = 'ajaxFunction()' value = 'Query MySQL'/>
</form>
<div id = 'ajaxDiv'>Your result will display here</div>
</body>
</html>
Server Side PHP file
So now your client side script is ready. Now we have to write our server-side script which will
fetch
age, wpm and sex from the database and will send it back to the client. Put the following code
into
"ajax-example.php" file.
<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
Web Programming Lab Manual Debre Tabor University Computer Science Department
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
Web Programming Lab Manual Debre Tabor University Computer Science Department
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>
Result:
Web Programming Lab Manual Debre Tabor University Computer Science Department
How to set cookies in PHP?
How to Retrieve a Cookie Value?
How to create a session? How to set a value in session ? How to Remove data from a
session?
How to create a mysql connection?
How to execute an sql query? How to fetch its result ?
How to create a text file in php?
What are the different types of errors in PHP ?
What is the purpose of php.ini file?
What are the different types of PHP variables?
Explain the syntax for 'foreach' loop.
What is associate array?
What is Multidimensional array?
How will you concatenate two strings in PHP?
How will you find the length of a string in PHP?
What is Ajax?
What are Ajax applications?
What are the advantages of Ajax?
What are all the technologies used by Ajax?
What are all the browsers support AJAX?
How can we cancel the XMLHttpRequest in AJAX?
What are the protocols used by Ajax?
What is XML?
What are the features of XML?
What are the differences between HTML and XML?
What is XML DOM Document?
What is XPath?
What is an attribute?
What is XML Element?
What is XML Parser?
Web Programming Lab Manual Debre Tabor University Computer Science Department