Internet Programming II (Lab) Programing Two in PHP
Internet Programming II (Lab) Programing Two in PHP
Contact: meti22bekele@[Link]
October, 2024
Sendafa, Ethiopia
Module Description
The Internet Programming II Lab Manual is designed to provide hands-on experience that complements
the theoretical components of the Internet Programming II course. This lab manual guides students
through practical exercises and real-world projects focused on client- and server-side web
development. Students will engage in activities that include building dynamic web applications,
working with databases, and implementing web security measures. The labs emphasize problem-
solving, debugging, and refining code to produce efficient and scalable web solutions.
i
Course Introduction
Internet Programming II is an intermediate-level course that builds on foundational web
development concepts, focusing on the creation of dynamic, interactive, and data-driven web
applications. In this course, students will learn how to bridge client-side and server-side technologies
to develop full-featured web applications that communicate with databases and handle asynchronous
data exchanges.
Additionally, students will be introduced to key web security concepts to ensure the applications they
build are functional and secure.
ii
Laboratory Objectives
The laboratory component of Internet Programming II is designed to reinforce the concepts taught
in lectures through hands-on practice. The primary objectives of the lab sessions are to:
1. Develop Dynamic Web Applications: Enable students to implement server-side scripting and
logic to build dynamic, data-driven web applications.
4. Apply Web Security Practices: Familiarize students with common security vulnerabilities and
help them implement security measures, such as data validation, user authentication, and
session management.
5. Use Version Control: Promote the use of Git for managing code changes, collaborating on
projects, and maintaining organized development workflows.
6. Debug and Optimize Web Applications: Equip students with the skills to troubleshoot, debug,
and improve the performance of their web applications.
iii
Table of Contents
iv
Session 1: General Laboratory Instruction/Introduction
Objective: at the end of this laboratory session, you will be able to:
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.
2
If you omit the language tag from your <script> tag, the browser will assume that your code is
written in JavaScript.
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,
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 [Link]. A ".js" file
extension indicates a JavaScript file.
4. Steps to execute PHP Program.
A. Type the program in notepad++ and save it with .php extension in the C:\wamp\www folder.
B. Next type the supported html & save it with .html extension in the same folder.
C. Start server (go to start->programs->Wamp server->start wamp server).
D. Open the browser & type the URL as [Link] then it will display the welcome web page
then Open Browser and type the URL as [Link]
Example: [Link]
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 [Link], it should be [Link] 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.
5. Installation Instructions
The Web pages that students create in Advanced Internet Programming / Internet Programming II
(Server-side programming) contain PHP code that must be processed by a Web server. It isn’t possible
to open PHP files directly using a Web browser alone as was done in Internet Programming I /
Introduction to Internet Programming (Client-Side Programming). PHP Web pages need to be
3
processed by a Web server first before they are viewed in a Web browser. Therefore, the first thing that
needs to be done is install a personal Web server on your computer.
❖ 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.
Apache is a free open-source Web server. Apache has been the most popular web server on the
Internet since April 1996. According to a recent Netcraft survey, 62% of all Web sites on the
Internet are using Apache. This makes Apache more widely used than all other Web servers
combined. Microsoft’s Web server named Microsoft IIS has less than a third of the market share.
PHP is a free open-source scripting language designed for producing dynamic, database-driven
web pages. PHP is a recursive acronym for "PHP: Hypertext Preprocessor". PHP is installed on
more than 20 million websites and 1 million web servers.
MySQL is a free open-source relational database management system (RDBMS). MySQL has
more than 11 million installations.
4
1. Open a Web browser and go to the WampServer download page at
[Link] you can download and install WampServer.
This will give you a server on your PC (Windows users), somewhere you can test your scripts.
In this example, the Mozilla Firefox Web browser is being used.
2. Click on the DOWNLOAD tab to download the appropriate WampServer software version to
your computer. Choose the top left button to install WAMPSERVER (32 BITS & PHP 5.4)
2.4. Even if you have a 64-bit computer the 32-bit version will work fine for this class. We’re
choosing this version for the smaller installation size and because we don’t need to utilize 64-
bit functionality.
3. Choose the Save File option and then click the Save File button and double click the setup file
to install and follow the wizard.
5
If the installation went well, you should have a new icon in the bottom right, where the clock
is:
To test if PHP was installed properly enter the address [Link] into the
Web browser. If you see the following Web page then PHP was installed correctly.
6
To test if MySQL was installed properly enter the address [Link] into
the Web browser. If you see the following Web page then MySQL was installed correctly.
7
If you saw the above page, then congratulations! That’s it. The WampServer personal Web server is
now successfully installed. Your PHP server is up and running and you can start scripting the PHP
page.
8
When you click on www directory, you should see an explorer window appear. (You'll probably have
only two files, index and testmysql.)
This www folder for Wampserver is usually at this location on your hard drive: c:/wamp/www/
Bear this in mind when you click File > Save As to save your PHP scripts.
[Link]
9
You would type this:
[Link]
You don't type the name of the Wamp folder, however. This would be wrong, for example:
c:/wamp/www/[Link]
[Link]
Your server knows where the www folder is, so you don't have to type it out: just add the script name
to localhost. Likewise, if you create a folder under www then you'd just type this:
[Link]
<html> <head>
</head>
<?php
?>
<?php
$x=3;
$x=4.5;
echo "Hello, World!,
$x ";
?>
</body> </html>
10
Output
Now open the browser and type [Link] or you could type it in [Link]
and browse through the projects and select [Link]
11
Session 2: Create a Simple HTML & PHP Page
Objective: at the end of this laboratory session, you will be able to:
Example 1: The following program will display Hello World on the browser (PHP scripts embedded
in HTML).
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Output:
12
Hello World
<!DOCTYPE html>
<html>
<?php
<head>
</head>
<body>
<h1>
<?php
print(“Welcome to PHP, $name!" );
?>
</h1>
</body></html>
Output:
13
Welcome to PHP, Abebe!
<!DOCTYPE html>
<html>
<head>
<title>Simple PHP Example</title>
</head>
<body>
<?php
echo"<p><h1>Output</h1>";
echo "<h2>Output</h2>";
echo "<h3>Output</h3></p>";
?>
<script language="PHP">
echo "\n<b>More PHP Output</b>\n";
echo "New line in source but not rendered";
echo "<br/>";
echo "New line rendered but not in source";
</script>
</body></html>
Exercise: What is the output of example 3?
14
[Link]
<!DOCTYPE html>
<html> <head>
</head>
<body>
</body>
</html>
[Link]
<?php
<h3><i>Included HTML</i></h3>
[Link]
15
Session 3: PHP Comments, Variables and Strings
Objective: at the end of this laboratory session, you will be able to:
Defining and using variables to store and manipulate different types of data.
Gaining the ability to use variables and strings in real-world web applications.
Example 1: The following program will help you to know about comments, variables, and strings.
<!DOCTYPE html>
<html> <head>
</head>
<body>
<?php
# And the Perl style works as well (in case you are interested)
16
// Note that with double quotes the variables are interpolated
// into the string but with single quotes the variable names are
// Also note something about the \n in the first two lines below:
//
17
echo "Here are the first three characters: <br/>";
echo "$x[0] $x[1] $x[2] <br />";
$y = $x;
$x = $y == "hello 11";
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x = $y == "hello 11.35";
echo "\$x is $x and is type ", gettype($x), "<br/>\n";
$x = 1234;
echo var_dump($x) . "<br/>\n";
if (is_int($x))
echo "I am an int<br/>\n";
else
if (is_string($x))
else
else
$x = "wacky1234";
echo var_dump($x), "<br/>\n";
if (is_int($x))
18
else
if (is_string($x))
else
if (is_numeric($x))
else
?>
</body> </html>
<?php
$my_string = "Hello Bob. My name is: ";
$newline = "<br />";
echo $my_string."Bobettta".$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string.$newline;
echo "Hi, I'm Bob. Who are you? ".$my_string."Bobetta";
//echo “$my_string”;
//echo ‘$my_string’;
?>
Output:
19
Hello Bob. My name is: Bobetta
Hi, I'm Bob. Who are you? Hello Bob. My name is:
Hi, I'm Bob. Who are you? Hello Bob. My name is: Bobetta
Exercise: try to display the values of the variable that are enclosed within double quotes (“ “) and
single quotes(‘ ‘). For example, see the output of the following from the above example.
echo “$my_string”;
echo ‘$my_string’;
What difference do you observe?
20
}
# The phpinfo() function is very useful, showing the configuration
# information about the server.
// phpinfo();
?>
</body> </html>
21
Session 4: PHP Expressions, Operators, control structures
Objective: at the end of this laboratory session, you will be able to:
Understanding and using various operators (arithmetic, comparison, logical, etc.) to
perform calculations and comparisons in PHP.
Writing and evaluating expressions to manipulate data and perform operations.
Implementing control structures (if, else, elseif, switch) to make decisions based on
conditions.
Using loops (for, while, do-while, foreach) to repeat actions and iterate over data sets.
Applying these concepts to create efficient, dynamic web applications that respond to
user interactions or inputs.
<?php
$addition = 2 + 4;
$subtraction = 6 - 2;
$multiplication = 5 * 3;
$division = 15 / 3;
$modulus = 5 % 2;
echo "Perform addition: 2 + 4 = ".$addition."<br />";
echo "Perform subtraction: 6 - 2 = ".$subtraction."<br />";
echo "Perform multiplication: 5 * 3 = ".$multiplication."<br />"; echo
"Perform division: 15 / 3 = ".$division."<br />";
echo "Perform modulus: 5 % 2 = " . $modulus . ". Modulus is the
remainder after the division operation has been performed.
In this case, it was 5 / 2, which has a remainder of 1.";
?>
22
Output:
Perform addition: 2 + 4 = 6
Perform subtraction: 6 - 2 = 4
Perform multiplication: 5 * 3 = 15
Perform division: 15 / 3 = 5
Perform modulus: 5 % 2 = 1. Modulus is the remainder after the division operation has been
performed. In this case, it was 5 / 2, which has a remainder of 1.
<?php
$a_string = "Hello";
Output:
Hello Billy!
<?php
$x = 4;
echo "The value of x with post-plusplus = " . $x++;
echo "<br /> The value of x after the post-plusplus is " . $x;
$x = 4;
echo "<br />The value of x with with pre-plusplus = " . ++$x;
echo "<br /> The value of x after the pre-plusplus is " . $x;
?>
23
Output:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$x = 15;
$y = 6;
$z = 5;
echo ($x/$y), " ", (int)($x/$y), ($x/$z), "<br/><br/>\n";
$a = "aardvark";
24
if ($x !== $x2) print "[int] $x !== [string] $x2 <br/>\n"; // yes
if ($x < $y) print "[int] $x < [int] $y <br/>\n"; // yes
if ($x < $y2) print "[int] $x < [string] $y2 <br/>\n"; // yes (casting)
if ($x < $z) print "[int] $x < [int] $z <br/>\n"; // no (numeric)
if (strcmp($x, $z) < 0) print "$x lt $z <br/>\n"; // yes (alpha)
if ((string)$x < (string)$z) print "$x lt $z <br/>\n"; // no (why???)
else
print "$x ge $z <br/>\n";
if ($x < $a) print "$x < $a <br/>\n"; // no (why???)
else print "$x >= $a <br/>\n";
if ((string)$x < $a) print "$x lt $a <br/>\n"; // yes (why???)
echo "<br/>";
$y = 0; // 0 integer
25
{
?>
<h2><strong> <?php
for ($i = 1; $i <= 10; $i++)
echo $i;
26
}
echo "<br/>\n";
endfor;
echo "<br/>\n";
?>
</strong></h2>
</body>
</html>
Exercises
1. Write a PHP program that uses a while loop to print the phrase “Hello World” ten times.
2. Write a PHP program that uses a for loop to print the phrase “Hello World” ten times.
3. Write a PHP code that calculates and displays the summation of the first 10 even numbers.
4. Write a PHP code that calculates and displays the net salary, pension, and tax of an Ethiopian
police university Employee.
27
Session 5: PHP Arrays
Objective: at the end of this laboratory session, you will be able to:
Understanding how to create and use different types of arrays (indexed, associative,
and multidimensional arrays).
Accessing, modifying, and manipulating array elements.
Utilizing array functions to perform operations such as sorting, merging, and
searching within arrays.
Implementing arrays to manage and organize data dynamically in web applications
<html>
<body>
<?php
//numeric array
$friend[0] = "Abebe";
$friend[1] = "Yonas ";
$friend[2] = "Tigist";
$friend[3] = "Sara";
//associative array
$age["Abebe"] = 45;
$age["Yonas"] = 32;
$age["Tigist"] = 26;
$age["Sara"] = 15;
28
print "My friends names are " . $friend[0] . ", " . $friend[1] . ", " . $friend[2] . ", and " .
$friend[3];
Print "<p>";
print "Sara is " . $age["Sara"] . " years old";
echo"<hr/>\n"; print_r($friend);
echo"<hr/>\n"; print_r($age);
echo "<hr/>\n";
foreach ($friend as $key => $val)
{
echo "$key is an index of $val <br/>";
}
echo "<hr/>\n";
{
echo "$key is $val years old <br/>";
echo "<hr/>\n";
//two-dimensional arrays
<?php
$marks = array( "Mohammad" => array("physics" => 35, "maths" => 30,"chemistry" => 39),
"Qadir" => array("physics" => 30,"maths" => 32,"chemistry" => 29),
29
echo $marks['Zara']['chemistry'] . "<br />";
//One predefined way to show an array with arbitrary nesting
// is the print_r method as shown below.
echo"<hr/>\n";
print_r($marks);
?>
</body>
</html>
<?php
30
/* The first foreach-command is addressing every part in
?>
Example 3: Accessing multi-dimensional array values using foreach statement and list () construct
<?php
$marks = array( "Mohammad" => array("physics" => 35, "maths" => 30,"chemistry" => 39),
"Qadir" => array("physics" => 30,"maths" => 32,"chemistry" => 29),
31
//method2
?>
32
Session 6: PHP Functions
Objective: at the end of this laboratory session, you will be able to:
Understanding the syntax and structure of defining and calling functions in PHP.
Differentiating between built-in and user-defined functions.
Passing arguments to functions and returning values to the calling code.
Utilizing variable scope and understanding local vs. global variables.
Applying functions to break down complex problems into manageable, logical parts,
fostering better organization in web application development.
Example 1: Defining and calling a PHP Function with parameter and no parameter.
<html>
<head>
<title>Writing PHP Function</title> </head>
<body>
<?php //Defining a PHP Function
function writeMessage()
{
echo "You are really a nice person, Have a nice time!<br/>";
}
/* Calling a PHP Function */
writeMessage(); //Writing PHP Function with Parameters
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum <br/>";
}
addFunction(10, 20);
?>
</body>
</html>
33
Output:
<?php
//Use of default parameters in functions function
makecoffee($type = "cappuccino")
{
return "Making a cup of $type.<br/>";
}
echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
34
Example 3: Passing function parameters by value and reference
<?php
//Passing function parameters by value
function add_some_extra($string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, '; add_some_extra($str);
function add_some_extra1(&$string)
add_some_extra1($str1);
?>
Output:
This is a string,
This is a string, and something extra.
35
<html>
<head>
<title>The scope of a variable</title>
</head>
<body>
<?php
//Local scope
function update_counter1 ( ) {
$counter1=$counter1+2;// shows error
echo "counter1 is now $counter1 <br/>";
}
$counter1 = 10;
update_counter1( );
echo "counter1 is $counter1 <br/>";//10
//Global scope
function update_counter2 ( ) {
global $counter2;
$counter2++;
}
$counter2 = 10;
36
update_counter2( );
echo "Global counter2 is $counter2 <br/>"; //11
counter1 is now 2
counter1 is 10
Global counter2 is 11
Static counter3 is now 1
Static counter3 is now 2
Global counter3 is 10
Exercise
Using the PHP function, write a program that calculates the sum of three numbers:
37
2. The case of three parameters to the function
3. The case of default parameter to the function
38
Session 7: Interaction between Client-Side and Server-Side scripts (HTML FORM
Manipulation with PHP)
Objective: at the end of this laboratory session, you will be able to:
Understanding the structure and elements of HTML forms, including input types,
labels, and form attributes.
Learning how to handle form submissions in PHP, including retrieving and processing
user input using the $_POST and $_GET superglobals.
Implementing data validation techniques to ensure the integrity and security of user
inputs.
Exploring how to provide user feedback and error messages based on form validation
results.
Developing practical applications that utilize form data to create personalized user
experiences, such as registration forms, contact forms, and search functionalities.
Enhancing skills in integrating PHP with HTML to create seamless user interfaces
that effectively capture and process data.
HTML Code:
[Link]
<html><body>
<select name="item">
<option>Paint</option>
<option>Brushes</option>
<option>Erasers</option>
</select>
39
<input type="submit" />
</form> </body></html>
PHP Code:
[Link]
<html><body>
<?php
$quantity = $_POST['quantity'];
$item = $_POST['item'];
echo "You ordered ". $quantity . " " . $item . ".<br />";
echo "Thank you for ordering from Tizag Art Supplies!";
?> </body></html>
If you selected the item brushes and specified a quantity of 6, then the following would be displayed on
"[Link]":
[Link]
<html> <head>
<title>hello user</title>
</head>
<body>
</form>
</body> </html>
40
[Link]
[Link]
<?php
Exercises
3. Accept two numbers from the HTML form and display their summation,
subtraction, product and division on the browser using PHP.
4. Develop and demonstrate using PHP script that displays your full information
(Name, date of birth, Department, Address, etc) that was accepted from the
HTML form.
41
Session 8: FORM validation with PHP
Objective: at the end of this laboratory session, you will be able to:
42
PHP Code segment
[Link]
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$websiteError ="";
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailError = "Invalid email format";
}}
43
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check address syntax is valid or not(this regular expression also allows dashes in the URL)
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-
z09+&@#\/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?> //php code ends here
44
HTML Code segment
<!DOCTYPE html>
<html>
<head>
<title>Form Validation with PHP - Demo Preview</title>
<meta content="noindex, nofollow" name="robots">
<link href="[Link]" rel="stylesheet">
</head>
<body>
<div class="maindiv">
<div class="form_div">
<div class="title">
<h2>Form Validation with PHP.</h2>
</div>
<form action="[Link]" method="post">
<h2>Form</h2>
<span class="error">* required field.</span>
Name:
<input class="input" name="name" type="text" value=""> <span
class="error">* <?php echo $nameError;?></span>
E-mail:
<input class="input" name="email" type="text" value=""> <span
class="error">* <?php echo $emailError;?></span>
Gender:
<input class="radio" name="gender" type="radio" value="female">Female
<input class="radio" name="gender" type="radio" value="male">Male
<span class="error">*<?php echo $genderError;?></span>
Website:
<input class="input" name="website" type="text" value="">
<span class="error"><?php echo $websiteError;?></span>
Comment:
45
<textarea cols="40" name="comment" rows="5">
</textarea>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</body>
</html>
CSS File
[Link]
(Remember this from your previous course: Internet Programming I)
@import "[Link]
/* Above line is to import Google font style */
.maindiv{
margin:0auto;
width:980px;
height:500px;
background:#fff; padding-
top:20px; font-size:14px
}
.title{
width:500px; height:70px;
text-shadow:2px 2px 2px #cfcfcf; font-
size:16px; text-align:center;
font-family:'Droid Serif',serif
}
.form_div{
width:70%;
float:left
46
}
form{
width:440px;
border:1px dashed #ccc;
padding:10px 30px 40px;
background-color:#f0f8ff; font-
family:'Droid Serif',serif
}
form h2{
text-align:center;
text-shadow:2px 2px 2px #cfcfcf
}
textarea{
width:250px;
height:60px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:5px;
border:none
}
.input{
width:250px;
height:15px;
border-radius:1px;
box-shadow:0 0 1px 2px #123456;
margin-top:10px;
padding:5px; border:none;
margin-bottom:20px
}
.submit{
47
color:#fff;
border-radius:3px;
background:#1F8DD6;
padding:5px;
margin-top:40px; border:none;
width:100px;
height:30px;
box-shadow:0 0 1px 2px #123456;
font-size:16px
}
.error{
color:red }
.radio{
width:15px; height:15px;
border-radius:1px;
margin-top:10px;
padding:5px; border:none;
margin-bottom:20px
}
.formget{
float:right;
margin-top:85px
}
Exercises
1. Is the above expression enough to validate name, email, gender, website and comment? If not,
please validate them to the maximum level?
2. Using PHP script validates data/input submitted from html form of having inputs (phone
number, age, and address).
48
Session 9: File system in PHP
Objective: at the end of this laboratory session, you will be able to:
Understanding the PHP file system functions and their applications for managing files
and directories.
Learning how to perform essential file operations, including creating, opening,
reading, writing, and closing files.
Implementing techniques for uploading and downloading files securely in web
applications.
Exploring methods for handling file permissions and ensuring proper security
measures are in place when accessing or modifying files.
49
Exercise: Discuss the differences of include, include_once, require, require_once from the above
example.
<?php
// these first 5 examples use relative referenced paths (relative to where script is)
$my_file = "../[Link]"; // Connect to file in the parent directory (jump up one level)
?>
Creating Files
<?php
// you can create any extension type file(html, php, xml, etc...)
$file_x = "my_file.txt";
$createFile=touch($file_x);
if (file_exists($file_x)) {
echo "The file has been created";
} else {
echo "The file has not been created";
}
?>
50
The file has been created
Deleting files
<?php
// you can delete any extension type file(html, php, jpg, gif, flv, swf, etc...)
$file_x = "my_file.txt";
if (file_exists($file_x)) {
unlink($file_x); // delete it here only if it exists
echo "The file has been deleted";
} else {
echo "The file was not found and could not be deleted";
}
?>
51
<?php
$target_file = "my_file.txt";
// Here we define the string data that is to be placed into the file
$target_file_data = "This is the string data or code I want to place in the newly created
file.";
// Here we are creating a file(since it does not yet exist) and adding data to it
// Here we define the string data that is to be appended to the data already in file
This is the string data or code I want to place in the newly created file.
Here is more data I want to append to the file.
52
In the example above we created a file, wrote to it, closed it, appended
data to it, then displayed its contents.
Reading a file
<html> <head>
</head> <body>
<?php
$filename = “my_file.txt";
$file = fopen( $filename, "r" );
if( $file == false )
{
echo ( "Error in the opening file"
); exit();
}
</body> </html>
Writing a file
53
<?php
$filename = "my_file.txt";
$file = fopen( $filename, "w" );
if( $file == false )
{ echo ( "Error in opening new file" );
exit();
}
fwrite( $file, "This is a simple test\n" );
fclose( $file );
?>
<html>
<head>
</head>
<body> <?php
if (file_exists($filename))
echo ($msg );
}
else
{ echo ("File $filename does not exit" );
?>
</body></html>
54
Uploading Files
file_uploader.html
<html> <head>
</head>
<body><h3>File Upload:</h3>
enctype="multipart/form-data">
<?php
if( $_FILES['file']['name'] != "" )
{ copy( $_FILES['file']['name'], "/var/www/html" ) or
die( "Could not copy file!");
}
else
{ die("No file specified!");
?>
</head> <body>
55
<ul>
</ul>
</body></html>
When you will upload a file using upload form and upload script, it will display following result:
Exercises:
1. Using PHP scripts create, delete, read, write, append, upload, and download a file.
2. Move and copy the file form its original place to another using PHP
3. Retrieve the file information from the global PHP variable called $_FILES.
56
Session 10: Manipulating MySQL Database with PHP -Part I
Objective: at the end of this laboratory session, you will be able to:
NB: if you don't know the username, servername, and password, make these parameters empty.
<html><head>
57
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create database: ' . mysql_error());
}
echo "Database TUTORIALS created successfully\n";
mysql_close($conn);
?>
</body></html>
<html><head>
<title>Deleting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = 'DROP DATABASE TUTORIALS';
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete database: ' . mysql_error());
58
}
echo "Database TUTORIALS deleted
successfully\n";
mysql_close($conn);
?>
</body></html>
<html><head>
<title>Selecting MySQL Database</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'TUTORIALS' );
mysql_close($conn);
?>
</body> </html>
59
<html><head>
<title>Creating MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "CREATE TABLE tutorials_tbl( ". "tutorial_id INT NOT NULL
AUTO_INCREMENT, ". "tutorial_title VARCHAR(100) NOT NULL, ".
"tutorial_author VARCHAR(40) NOT NULL, ". "submission_date DATE, ".
"PRIMARY KEY ( tutorial_id )); ";
mysql_select_db( 'TUTORIALS' );
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
</body></html>
60
<html>
<head><title>Dropping MySQL Tables</title>
</head><body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
If(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "DROP TABLE tutorials_tbl";
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not delete table: ' . mysql_error());
}
echo "Table deleted successfully\n";
mysql_close($conn);
?>
</body></html>
61
Session 11: Manipulating MySQL Database with PHP -Part II
62
{?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="600" border="0" cellspacing="1" cellpadding="2">
<tr><td width="250">Tutorial Title</td><td>
<input name="tutorial_title" type="text" id="tutorial_title"></td>
</tr><tr><td width="250">Tutorial Author</td><td>
<input name="tutorial_author" type="text" id="tutorial_author"></td>
</tr><tr><td width="250">Submission Date [ yyyy-mm-dd ] </td><td>
<input name="submission_date" type="text" id="submission_date"></td></tr>
<tr><td width="250"> </td><td> </td></tr><tr><td width="250"> </td><td>
<input name="add" type="submit" id="add" value="Add Tutorial"></td>
</tr></table></form>
<?Php
}
?> </body></html>
Example 2: The HTML form and PHP scripts are on separate files.
[Link]
<html>
<body>
<form action="[Link]" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
63
</html>
[Link]
<?php
$con=mysqli_connect(““, ““ , ““ , "my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
64
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error()); }
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']} <br> ".
"Author: {$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
//display all the records from tutorial_tbl table using mysql_fetch_assoc() function.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
If(! $conn )
65
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM
tutorials_tbl';
mysql_select_db('TUTORIALS');
$retval=mysql_query($sql,$conn);
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_assoc($retval))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']}
<br> ". "Author: {$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "-------------------
<br>";}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
//display all the records from tutorials_tbl table using MYSQL_NUM argument.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error()); }
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl';
66
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_NUM))
{ echo "Tutorial ID :{$row[0]} <br> ". "Title: {$row[1]} <br> ". "Author:
{$row[2]} <br> ". "Submission Date : {$row[3]} <br> ". "-------<br>";} echo
"Fetched data successfully\n";
mysql_close($conn);
?>
NB: All the above three examples will produce the same result.
Example 4: Return all the records from the tutorials_tbl table for which the author's name is Abebe
using the MYSQL_NUM argument.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{ die('Could not connect: ' . mysql_error());}
$sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date
FROM tutorials_tbl WHERE tutorial_author=" Abebe "'; mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{ die('Could not get data: ' . mysql_error());}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{ echo "Tutorial ID :{$row['tutorial_id']} <br> ". "Title: {$row['tutorial_title']} <br>
". "Author: {$row['tutorial_author']} <br> ". "Submission Date :
{$row['submission_date']} <br> ". "--------------<br>";}
67
echo "Fetched data successfully\n";
mysql_close($conn);
?>
68
Deleting Data Using PHP Script:
69
Session 12: Designing Online Databases with phpMyAdmin
phpMyAdmin will be opened in your browser. Write anything as a username (remember it)
and leave the password textbox blank and press Go.
70
4. Creating tables in your default database.
Select your default database (it is circled with red color on the left side of the screen below).
¾Inside the textbox named “Create Table” type the name of the new table (it is circled with
black color on the figure below).
Inside the next textbox to the right, type the number of fields in the new table (again, it is
circled with black color on the figure below).
Press the Go button (as shown on the most right side of the figure below).
71
Enter the names of the fields that you would like to create in your table (they are circled in red
color on a figure below).
You need to specify data for -Type, -Length Values -Null or not Null (to set Null click on
the checkbox).
It is good to have a habit of creating one more column for some unique information (such as
ID which can be used later for connecting tables, circled blue)
Then press Save.
To insert into a table, select a table (like BillPay, Customer, etc. on the left side of the figure
given below)
72
Click Insert menu item (circled with red color on the figure above).
Insert data in the Value textboxes (circled with green color on the figure above).
Press the Go button (circled with black color on the figure above).
5.2. Update:
To update the entry of a table, select the table (in red color below).
Click the Browse menu item (circled in blue color on the figure above).
Click on the Pencil sign (circled with black color on a figure below) for the entry you want to
be updated.
The textbox will appear with existing data in that field.
Update (change, modify) the data in the field and click on Go button.
73
5.3. Delete:
Select the entry you want to delete from the table, and then click the delete icon in front of it
(circled with blue color in the figure above).
6. Modifying a table:
To delete a table from the database, select the database (circled with red color on the figure
below).
Select a specific table you want to be deleted (circled with black color below).
And select Drop (circled with black color below).
74
Session 13: Cookies and Sessions in PHP
<?php
session_start();
if (isset($_SESSION["count"])) $s =
(int) $_SESSION["count"];
if (isset($_COOKIE["cookie1"])) $c1
= $_COOKIE["cookie1"];
if (isset($_COOKIE["cookie2"])) $c2
= $_COOKIE["cookie2"];
if ((!isset($s)) && (!(isset($c1)))):
setcookie("cookie1","You have visited the site 1 previous time",time()+600);
$_SESSION["count"] = $s;
?>
<!DOCTYPE html>
<html>
75
<head>
</head>
<body>
<h3>
<?php
echo "Welcome to the PHP cookies and sessions Example <br/>";
if ($output):
echo "$output<br/>";
endif;
echo "You have visited $s pages in the current session"; ?>
</body>
</html>
Example 2: Write a PHP program to store current date-time in a COOKIE and display the “Last visited
on‟ date-time on the web page upon reopening of the same page.
<html >
<head>
<title>Cookies</title>
</head>
<body>
<p>
</p>
76
</form>
</body>
</html>
<?php
$inTwoMonths=60*60*24*60+time();
setcookie('lastVisit',date("G:i-m/d/y"),$inTwoMonths);
if(isset($_COOKIE['lastVisit']))
{
$visit=$_COOKIE['lastVisit'];
echo "Your last visit was - ".$visit;
}
else echo "You've got some stale cookies!";
?>
Output:
Example 3: Write a PHP program to store page views count in SESSION, to increment the count on
each refresh, and to show the count on web page.
Method 1
<?php
session_start();
session_register("count");
77
if (!isset($_SESSION)) {
$_SESSION["count"] = 0;
echo "<p>Counter initialized</p>\n"; }
else { $_SESSION["count"]++; }
echo "<p>The counter is now <b>$_SESSION[count]</b></p>".
"<p>reload this page to increment</p>";
?>
Method 2
<html >
<body>
<p> To see page views count in session <input type="submit" name="Click Here"/>
</p>
</form> </body>
</html>
<?php
//------------------------[Link](PHP File)-----------------------------
session_start();
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "This page has been viewed ".$_SESSION['views']." times.";
?>
78
REFERENCES
1. Programming PHP. 3rd ed. Kevin Tatroe, Peter MacIntyre, and Rasmus Lerdorf, 2013.
2. Harvey M. Deitel. 5th ed. Internet and World Wide Web: How to Program.
3. PHP5 and MySQL Bible by Tim Converse and Joyce Park with Clark Morgan
7. PHP and MySQL Web Development, by Luke Welling and Laura Thomson (Developer's Library)
9. [Link]
79