0% found this document useful (0 votes)
8 views366 pages

CS310 Handouts Merge PDF by DL

The document provides an introduction to PHP, a server scripting language used for creating dynamic web pages. It covers PHP's features, such as its compatibility with various platforms and databases, as well as basic syntax, variable types, and functions. Additionally, it explains the differences between output methods, variable scopes, and includes examples of PHP code.

Uploaded by

locusmartin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views366 pages

CS310 Handouts Merge PDF by DL

The document provides an introduction to PHP, a server scripting language used for creating dynamic web pages. It covers PHP's features, such as its compatibility with various platforms and databases, as well as basic syntax, variable types, and functions. Additionally, it explains the differences between output methods, variable scopes, and includes examples of PHP code.

Uploaded by

locusmartin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 366

WEEK 1

Prepared by DL...
May You All Stay Success in your Whole Life,
Ameen! Summ Ameen... Just Remember us
in your Deep Prayers. JazakAllah...
 PHP is a server scripting language, and a
powerful tool for making dynamic and
interactive Web pages.

 PHP is a widely-used, free, and efficient


alternative to competitors such as Microsoft's
ASP.
While PHP originally stood for Personal Home
Page, it now stands for (PHP: Hypertext
Preprocessor), which is a recursive acronym.

P -> PHP
H -> Hypertext
P -> Preprocessor
 It is powerful enough to be at the core of the
biggest blogging system on the web
(WordPress)!

 It is deep enough to run the largest social


network (Facebook)!

 It is also easy enough to be a beginner's first


server side language!
 PHP can generate dynamic page content

 PHP can create, open, read, write, delete, and


close files on the server

 PHP can collect form data

 PHP can send and receive cookies


 PHP can add, delete, modify data in your
database

 PHP can be used to control user-access

 PHP can encrypt data


With PHP you are not limited to output HTML.

You can output

 Images
 PDF files
 Flash movies
 XHTML
 XML.
 PHP runs on various platforms (Windows,
Linux, Unix, Mac OS X, etc.)

 PHP is compatible with almost all servers


used today (Apache, IIS, etc.)
 PHP supports a wide range of databases like
MySQL, MS Access, MS SQL Server, Oracle, etc

 PHP is free.

 PHP is easy to learn and runs efficiently on


the server side
 PHP is FREE

 It runs on Linux which is FREE

 It support MySQL Free

 It runs on Apache which is also free

That is why most of the time hosting of PHP is


cheap.
 A PHP script can be placed anywhere in the
document.

 A PHP script starts with <?php and ends


with ?>:

 <?php
// PHP code goes here
?>
 Extension of PHP page should be .php
PHP statements end with a semicolon (;)
To get the PHP running at your computer you
will need to
 install a web server
 install PHP
 install a database, such as MySQL

The official PHP website (PHP.net) has


installation instructions for
PHP: http://php.net/manual/en/install.php
 Installation and configuration process of PHP
can be easily done using Bundled Software
know as LAMP and WAMP

 LAMP Stands for Linux, Apache, MySQL


and PHP.

 WAMP is Windows, Apache, MySQL and PHP.

 We will be using a WAMP bundle


 This is a open source platform.

 WAMP Server works on Windows Operating


System only.

 WAMP is a combine
package of Windows, Apache, MySQL
and PHP.

 .
VertrigoServ is easy to install package
consisting of

 Apache (HTTP web server)


 PHP(Server Side Scripting)
 MySQL (SQL Database Management System)
 PhpMyAdmin (tool written in PHP intended to
handle the administration of MySQL)
<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
echo "Hello World!";
?>

</body>
</html>
WEEK 2
In PHP there are two basic ways to get output:
echo
h andd print.
i t

The differences are small:


 echo has no return value while print has a
return value of 1 so it can be used in
expressions.
i
 echo can take multiple parameters (although
such usage is rare) while print can take one
argument.
 echo is marginally faster than print.
The echo statement can be used with or
without parentheses: echo or echo().
The following example shows how to output
text with the echo command (notice that the
text can contain HTML markup)
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm
I m about to learn PHP!<br>";
PHP!<br> ;
echo "This ", "string ", "was ", "made ",
"with multiple
p p parameters.";;
?>
<?php
$txt1 = "Learn PHP";
$txt2 = "W3Schools.com";
$x = 5;
$y = 4;

echo "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>";
h $
echo $x + $
$y;
?>
 The following example shows how to output
text with the print command (notice that the
text can contain HTML markup)

 <?php
print "<h2>PHP
<h2>PHP is Fun!</h2>";
Fun!</h2> ;
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
A comment in PHP code is a line that is not
read/executed as part of the program. Its only
purpose is to be read by someone who is
looking at the code.
Comments can be used to:

 Let others understand what you are doing

 Remind yourself of what you did - Most


programmers have experienced coming back
to their own work a year or two later and
having to re-figure
re figure out what they did.
Comments can remind you of what you were
thinking when you wrote the code.
PHP supports several ways of commenting:

 // (Single Line Comment)


 # (Single Line Comment)
 /* */ (Multiple Line Comments)
<!DOCTYPE html>
<html>
<body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines
multiple lines comment block
that spans over multiple
lines
*/
<?>
</body>
</html>
<!DOCTYPE html>
<html>
ht l
<body>
<?php>
// You can also use comments to leave out
parts of a code line
$ = 5 /* + 15 */ + 5
$x 5;
echo $x;
?>
</body>
</html>
In PHP, all keywords (e.g. if, else, while, echo,
etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
case sensitive
<!DOCTYPE html>
<html>
<body>
<?php

ECHO "Hello World!<br>";


echo "Hello
Hello World!<br>
World!<br>";;
EcHo "Hello World!<br>";
?>
</body>
</html>
All variable names are case-sensitive

<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My
My car is " . $color . "<br>";
<br> ;
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
 A variable can have a short name (like x and
y) or a more descriptive name (age,
studentname, total_volume).
 A variable starts with the $ sign, followed by
the name of the variable
 A variable
i bl name must start with i h a lletter or the
h
underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-
numeric characters and underscores (A-z, (A z, 0-
0
9, and _ )
 Variable names are case-sensitive ($age and
$AGE are two diff
different variables)
i bl )
In PHP, a variable starts with the $ sign,
followed by the name of the variable:

E
Example:
l
<!DOCTYPE html>
<html>
<body>
<?php
$
$txt = ""Hello
ll world!";
ld "
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo
h "<br>";
" b "
echo $y;
?>
</body>
</html>
After the execution of the statements above,
the variable $txt will hold the value Hello
world! the variable $x will hold the value 5,
world!, 5
and the variable $y will hold the value 10.5.
Note: Unlike other programming languages,
PHP has no command for declaring a variable.
It is created the moment you first assign a
value to it.
Variables can store data of different types, and
different data types can do different things.
PHP supports the following data types:

 String
 I t
Integer
 Float (double)
 Boolean
 Array
 Object
 NULL
 A string is a sequence of characters, like
"Hello world!".
 A string can be any text inside quotes. You
can use single or double quotes:
<?php
$x = "Hello world!";
$y = 'Hello world!';

echo $x;
echo "<br>";;
echo $y;
?>
 An integer is a whole number (without
decimals). It is a number between -
2,147,483,648 and +2,147,483,647.
 An integer must have at least one digit (0-9)
 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats:
decimal (10-based),
(10 based) hexadecimal (16(16-based
based
- prefixed with 0x) or octal (8-based -
prefixed with 0)
<?php
$x = 5985;
var_dump($x);
?>

var dump($x) will return the data type variable


var_dump($x) variable.
A float (floating point number) is a number
with a decimal point or a number in
exponential form.

In the following example $x is a float.

<?php
$x = 10.365;
var_dump($x);
?>
A Boolean represents two possible states: TRUE
or FALSE.

$x = true;
$y = false;

Booleans are often used in conditional testing.


You will learn more about conditional testing in
a later chapter of this tutorial.
An object is a data type which stores data and
information on how to process that data.
In PHP, an object must be explicitly declared.

First we must declare a class of object. For this,


we use the class keyword.
keyword A class is a structure
that can contain properties and methods:
 <?php
 class Car {
 function Car() {
 $this >model = “Honda";
$this->model Honda ;
 }
 }
 // create an object
 $fahad = new Car();

 // show object properties


 echo $fahad->model;
 ?>
Null is a special data type which can have only
one value: NULL.

A variable
i bl off d
data type NULL iis a variable
i bl that
h
has no value assigned to it.

 Tip: If a variable is created without a value, it


is automatically assigned a value of NULL.
 Variables can also be emptied by setting the
value to NULL:
 <?php
$x = "Hello world!";
$x = null;
var dump($x);
var_dump($x);
?>
WEEK 3
 PHP automatically converts the variable to the
correct data type, depending on its value.

 IIn other
h languages
l such
h as C,
C C++,
C and
d Java,
J
the programmer must declare the name and
type of the variable before using it
it.
 <?php
$x = 5;
$y = 4;
echo $x + $y;

 $x = “Pakistan”
Pakistan

 Echo $x

?>
In PHP, variables can be declared anywhere in
th script.
the i t

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
A variable declared outside a function has a
GLOBAL SCOPE and can only be accessed
outside a function:
 <?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an
error
echo "<p>Variable x inside function is:
$x</p>";
/p ;
}
myTest();
h ""<p>Variable
echo V i bl x outside
t id ffunction
ti iis:
$x</p>";
?>
A variable declared within a function has a
LOCAL SCOPE and can only be accessed within
that function:
 <?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is:
$x</p> ;
$x</p>";
}
myTest();
// using x outside the function will generate an
error
echo "<p>Variable x outside function is:
$ / "
$x</p>";
?>
The global keyword is used to access a global
variable from within a function.

To do
T d this,
hi use theh global
l b lkkeyword
dbbefore
f the
h
variables (inside the function):
<?php
$x = 5;
$y = 10;

ffunction
i myTest()
T () {
global $x, $y;
$y = $x + $y;
}

myTest();
y ();
echo $y; // outputs 15
?>
Normally, when a function is
completed/executed, all of its variables are
deleted. However, sometimes we want a local
variable NOT to be deleted
deleted. We need it for a
further job.

To do this, use the static keyword when you


first declare the variable:
<?php
function
f ti myTest()
T t() {
static $x = 0;
echo $x;;
$x++;
}

myTest();
myTest();
T ()
myTest();
?>
A string is a sequence of characters, like "Hello
world!".
The PHP strlen() function returns the length of
a string.
Th example
The l b
below
l returns the
h llength
h off the
h
string "Hello world!":

<?php
echo strlen("Hello
strlen( Hello world!");
world! ); // outputs 12
?>
The PHP str_word_count() function counts the
number of words in a string:

<?php
echo str_word_count(
str word count("Hello
Hello world!");
world! );
// outputs 2
?>
The PHP strrev() function reverses a string:

<?php
echo strrev("Hello world!");
// outputs !dlrow olleH
?>
The PHP strpos() function searches for a
specific text within a string.

If a match
h is
i found,
f d the
h function
f i returns the
h
character position of the first match. If no
match is found
found, it will return FALSE
FALSE.
The example below searches for the text
"world" in the string "Hello world!":

<?php
? h
echo strpos("Hello world!", "world");
// outputs 6
?>
 The PHP str_replace() function replaces some
characters with some other characters in a
string.
 The example below replaces the text "world"
world
with "Dolly":

<?php
echo str_replace("world",
p ( , "Dolly",
y , "Hello
world!"); // outputs Hello Dolly!
?>
 For a complete reference of all string
functions, go to complete PHP String
Reference.

 http://www.w3schools.com/php/php_ref_stri
ng asp
ng.asp

 The PHP string reference contains description


and example of use, for each function!
A constant is an identifier (name) for a simple
value. The value cannot be changed during the
script.

A valid constant name starts with a letter or


underscore (no $ sign before the constant
name).

Note: Unlike variables, constants are


automatically global across the entire script.
To create a constant, use the define() function.

Syntax
define(name, value, case-insensitive
case insensitive)

Parameters:
 name: Specifies the name of the constant

 value: Specifies the value of the constant

 case-insensitive: Specifies whether the constant


name should be case-insensitive. Default is false
The example below creates a constant with
a case-sensitive name:
WEEK 4
Operators are used to perform operations on
variables and values.
PHP divides the operators in the following
groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 St i
String t
operators
 Array operators
Operator Name Example Result
+ Addition $x + $y Sum of $x and $y

- Subtraction $x - $y Difference of $x and $y

* Multiplication $x * $y Product of $x and $y

/ Division $x / $y Quotient of $x and $y

% Modulus $x % $y Remainder of $x divided by


$y
** Exponentiation $x ** $y Result of raising $x to the
$y'th power (Introduced in
PHP 5.6)
 The PHP assignment operators are used with
numeric values to write a value to a variable.

 The basic
Th b i assignment
i operator iin PHP is
i "=".
" "
It means that the left operand gets set to the
value of the assignment expression on the
right.
Assignment Same as... Description

x=y x=y The left operand gets set to the value of the
expression on the right
x+
+= y x=x+y Addition

x -= y x=x-y Subtraction

x *= y x=x*y Multiplication

x/
/= y x=x/y Division

x %= y x=x%y Modulus
Operator Name Example Result

== Equal $x == $y Returns true if $x is equal


to $y

=== Identical $x === Returns true if $x is equal


$y to $y, and they are of the
same type

!= Not equal $x != $y Returns true if $x is not


equal to $y

<> Not equal $x <> $y Returns true if $x is not


equal
q to $y
y
!== Not identical $x !== $y Returns true if $x
i nott equall tto
is
$y, or they are
not of the same
type

> Greater than $x > $y Returns true if $x


is greater than
$y

< Less than $x < $y Returns true if $x


is less than $y

>= Greater than or $x >= $y Returns true if $x


equal to is greater than or
equall to $
$y

<= Less than or $x <= $y Returns true if $x


equal to is less than or
equal to $y
Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post- Returns $x, then decrements $x by one


decrement
Operator Name Example Result
and And $x and $y True if both $x and $y are
true
or Or $x or $y True if either $x or $y is
true
xor Xor $x xor $y True if either $x or $y is
true, but not both
&& And $x && $y True if both $x and $y are
true
|| Or $x || $y True if either $x or $y is
true
! Not !$
!$x Tr e if $x
True $ is not tr
true
e
Operator Name Example Result

. Concatenation $txt1 . $txt2 Concatenation of


$txt1 and $txt2

.= Concatenation $txt1 .= $txt2 Appends $txt2 to


assignment $txt1
WEEK 5
Condition will
be evaluated to
true or false
Multiple if statements if … elseif… else

if ($num1 > $num2) if ($num1 > $num2)


echo “Number 1 is greater than number 2” ; echo “Number 1 is greater than number 2” ;

if($num1 < $num2) else if ($num1 < $num2)


echo “Number 2 is greater than number 1” ; echo “Number 1 is less than number 2” ;

if($num1 == $num2) else


echo “Both numbers are equal” ; echo “Both numbers are equal” ;
WEEK 6
In the first part, we set the value of loop
counter and it is initialized only once at the
start of loop
In the second part, we set the condition for
the continuation/termination of loop
In third part, we increment/decrement the
value of loop counter
for ($i = 0; $i<5; $i++)
{
echo “value of i is $i <br>” ;
}

Iterations Condition Loop body Increment


($i<5) Output $i++
1 0<5 (True) 0 1
2 1<5 (True ) 1 2
3 2<5 (True) 2 3
4 3<5 (True) 3 4
5 4<5 (True) 4 5
6 5<5 (False) Loop terminates
$i = 0 ;
while($i<5)
{
echo “value of i is $i <br>” ;
$i++ ;
}
Iterations Condition Loop body Increment
($i<5) Output $i++
1 0<5 (True) 0 1
2 1<5 (True ) 1 2
3 2<5 (True) 2 3
4 3<5 (True) 3 4
5 4<5 (True) 4 5
6 5<5 (False) Loop terminates
$i = 0 ;
do
{
echo “value of i is $i <br>” ;
$i++ ;
} while($i<5) ;

Iterations Loop body Increment Condition


Output $i++ ($i<5)
1 0 1 1<5 (True)
2 1 2 2<5 (True )
3 2 3 3<5 (True)
4 3 4 4<5 (True)
5 4 5 5<5 (False)

Here loop terminates


WEEK 7
 The include statement takes all the
text/code/markup that exists in the specified
file and copies it into the file that uses the
include statement.

 Including files is very useful when you want


to include the same PHP, HTML, or text on
multiple pages of a website.
include 'filename';
Assume we have a standard footer file called
"footer.php", that looks like this:

<?php

echo "<p>Copyright; 1990-" . date("Y") . "


ABC.com</p>";

?>
To include the footer file in a page, use the include
statement:

<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>

<?php include 'footer.php';?>


</body>
</html>
 The PHP date() function is used to format a
date and/or a time.
 The PHP date() function formats a timestamp
to a more readable date and time.

Syntax
date(format,timestamp)

Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the
current date and time

Note that the PHP date() function will return the current date/time
of the server!
 The required format parameter of the date()
function specifies how to format the date (or
time).

 Here are some characters that are commonly


used for dates:
◦ d - Represents the day of the month (01 to 31)
◦ m - Represents a month (01 to 12)
◦ Y - Represents a year (in four digits)
◦ l (lowercase 'L') - Represents the day of the week

 Other characters, like"/", ".", or "-" can also be


inserted between the characters to add additional
formatting.
 The example below formats today's date in
three different ways:

<?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");
?>
 Use the date() function to automatically
update the copyright year on your website:

Example

&copy; 2010-<?php echo date("Y")?>


 Here are some characters that are commonly
used for times:

◦ h - 12-hour format of an hour with leading zeros


(01 to 12)
◦ i - Minutes with leading zeros (00 to 59)
◦ s - Seconds with leading zeros (00 to 59)
◦ a - Lowercase Ante meridiem and Post meridiem
(am or pm)
 The example below outputs the current time
in the specified format:

<?php
echo "The time is " . date("h:i:sa");
?>
 If the time you got back from the code is not
the right time, it's probably because your
server is in another country or set up for a
different timezone.

 So, if you need the time to be correct


according to a specific location, you can set a
timezone to use.
 The example below sets the timezone to
"Asia/Karachi", then outputs the current time
in the specified format:

Example

<?php
date_default_timezone_set("Asia/Karachi");
echo "The time is " . date("h:i:sa");
?>
 A cookie is often used to identify a user. A
cookie is a small file that the server embeds
on the user's computer.

 Each time the same computer requests a


page with a browser, it will send the cookie
too.

 With PHP, you can both create and retrieve


cookie values.
A cookie is created with the setcookie()
function.

Syntax

setcookie(name, value, expire, path, domain,


secure, httponly);

Only the name parameter is required. All other


parameters are optional.

Note: The setcookie() function must appear BEFORE the <html> tag.
<?php
$cookie_name = "user";
$cookie_value = "Ahmed";
setcookie($cookie_name, $cookie_value, time() + (86400
* 30), "/"); // 86400 = 1 day
?>
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];}
?>
</body></html>

The value of the cookie is automatically URL encoded when sending the
cookie, and automatically decoded when received (to prevent URL
encoding, use setrawcookie() instead).
To delete a cookie, use the setcookie() function with an
expiration date in the past:

Example

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600,"/");
?>
<html><body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body></html>
WEEK 8
 A session is a way to store information (in variables) to
be used across several pages.
 Unlike a cookie, the information is not stored on the
users computer.
 When you work with an application, you open it, do
some changes, and then you close it. This is much like
a Session.
 On the internet there is one problem: the web server
does not know who you are, because the HTTP address
doesn't maintain state.
 Session variables solve this problem by storing user
information to be used across multiple pages (e.g.
username etc.). By default, session variables last until
the user closes the browser.
 Session variables hold information about one single
user, and are available to all pages in one application.
 A session is started with the session_start() function.
 Session variables are set with the PHP global variable: $_SESSION.
 Now, let's create a new page called "session_demo1.php". In this page,
we start a new PHP session and set some session variables:

Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body></html>

Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.
 Next, we create another page called
"session_demo2.php". From this page, we will
access the session information we set on the first
page ("session_demo1.php").

 Session variables are not passed individually to


each new page, instead they are retrieved from
the session we open at the beginning of each
page (session_start()).

 All session variable values are stored in the


global $_SESSION variable
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>
 Another way to show all the session variable values for a user
session is to run the following code:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>
 Most sessions set a user-key on the user's
computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12.
 Then, when a session is opened on another
page, it scans the computer for a user-key.
 If there is a match, it accesses that session, if
not, it starts a new session.
 Most sessions set a user-key on the user's
computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12.
 Then, when a session is opened on another
page, it scans the computer for a user-key.
 If there is a match, it accesses that session, if
not, it starts a new session.
To remove all global session variables and destroy the session, use
session_unset() and session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html><body>

<?php
// remove all session variables
session_unset();

// destroy the session


session_destroy();
?>

</body></html>
WEEK 9
Filters are used for
 Validating data = Determine if the data is in proper form.
 Sanitizing data = Remove any illegal character from the data.
 Many web applications receive external input. External
input/data can be:
◦ User input from a form
◦ Cookies
◦ Web services data
◦ Server variables
◦ Database query results

 You should always validate external data!


 Invalid submitted data can lead to security problems and break
your webpage!
 By using PHP filters you can be sure your application gets the
correct input!
 The filter_var() function both validate and
sanitize data.

 The filter_var() function filters a single


variable with a specified filter. It takes two
pieces of data:
◦ The variable you want to check
◦ The type of check to use
 The following example uses the filter_var()
function to remove all HTML tags from a string:

Example

<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str,
FILTER_SANITIZE_STRING);
echo $newstr;
?>
 The following example uses the filter_var() function to first remove all
illegal characters from a URL, then check if $url is a valid URL:

Example

<?php
$url = "http://www.vu.edu.pk";

// Remove all illegal characters from a url


$url = filter_var($url, FILTER_SANITIZE_URL);

// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");
}
?>
 The following example uses the filter_var() function to first remove all
illegal characters from the $email variable, then check if it is a valid email
address:

Example

<?php
$email = "[email protected]";

// Remove all illegal characters from email


$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
?>
 The following example uses the filter_var() function to check if
the variable $int is an integer. If $int is an integer, the output of
the code above will be: "Integer is valid". If $int is not an integer,
the output will be: "Integer is not valid":

Example

<?php
$int = 100;

if (!filter_var($int, FILTER_VALIDATE_INT) === false) {


echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
 In the previous example, if $int was set to 0, the function above
will return "Integer is not valid". To solve this problem, use the
code below:

Example

<?php
$int = 0;

if (filter_var($int, FILTER_VALIDATE_INT) === 0 || !filter_var($int,


FILTER_VALIDATE_INT) === false) {
echo("Integer is valid");
} else {
echo("Integer is not valid");
}
?>
 The following example uses the filter_var() function to
check if the variable $ip is a valid IP address:

Example

<?php
$ip = "127.0.0.1";

if (!filter_var($ip, FILTER_VALIDATE_IP) === false) {


echo("$ip is a valid IP address");
} else {
echo("$ip is not a valid IP address");
}
?>
WEEK 10
 Data base
◦ A database is an organized collection of data.
 Database management system (DBMS)
◦ It is a computer software application, designed to
allow the definition, creation, querying, update, and
administration of databases.
◦ Example
Some examples of DBMS are :
 MySQL
 PostgreSQL
 Microsoft SQL Server
 Oracle
 Sybase

2
 A free, fast, reliable, easy-to-use, multi-user
multi-threaded relational database system.
 SQL (Structured Query Language) is use in
MYSQL database system.
 It is freely available and released under GPL
(GNU General Public License ).
 Officially pronounced “my Ess Que Ell” (not
my sequel).

3
 There are many tools available for handling
MY SQL databases such as:

 XAMPP :consisting mainly of the Apache HTTP


Server, MySQL database
 WAMP:consisting of the Apache web
server, OpenSSL for SSL
support, MySQL database

 For our course we will use WAMP


 Is a FREE software tool written
in PHP intended to handle the administration
of MySQL over the Internet.
 PhpMyAdmin supports a wide range of
operations with MySQL, the most frequently
used being the managing of databases,
tables, fields, relations, indexes, users,
permissions.
 You still have the ability to execute SQL
statements directly as well.
 These mysql database tables contain grant
information:
 user: User accounts, global privileges, and
other non-privilege columns.
 db: Database-level privileges.
 host: Obsolete.
 tables_priv: Table-level privileges.
 columns_priv: Column-level privileges.
 procs_priv: Stored procedure and function
privileges.
 Used in PHP code,
 <?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username,
$password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
 Earlier versions of PHP used the MySQL
extension. PHP version 5 and after that
work with a MySQL database using:

 MySQLi extension (the "i" stands for


improved)
 PDO (PHP Data Objects)
 PDO will work on 12 different
database systems, where as MySQLi
will only work with MySQL databases.
 Three ways of working with PHP and
MySQL:
i- MySQLi (object-oriented)
ii- MySQLi (procedural)
iii- PDO

Note: We will use Procedural method in our examples.


The CREATE DATABASE statement is used to
create a database in MySQL.

Examples

<?PHP $servername = "localhost";

$username = “root";

$password = “";
// Create connection
$conn = mysqli_connect($servername, $username,
$password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());}

// Create database
$sql = "CREATE DATABASE mystudent";
if (mysqli_query($conn, $sql)) {
echo "Database created successfully";
} else {
echo "Error creating database: " . mysqli_error($conn);
} ?>
WEEK 11
 The CREATE TABLE statement is used to create a table in
MySQL.

 We will create a table named “Student", with five


columns: “s_id", "firstname", "lastname", "email" and
"reg_date":

SQL Statement:-
CREATE TABLE Student (
s_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)
Example:-
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username,
$password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE student (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table student created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
 When 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
 The INSERT INTO statement is used to add
new records to a MySQL table:

SQL Statement: INSERT INTO table_name


(column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Note: If a column is AUTO_INCREMENT (like the "id" column) or


TIMESTAMP (like the "reg_date" column), it is no need to be specified
in the SQL query; MySQL will automatically add the value.
Example
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username,
$password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
Example(continued )
$sql = "INSERT INTO student (firstname, lastname,
email)
VALUES (‘Ali', ‘Wali', ‘[email protected]')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" .
mysqli_error($conn);
}
mysqli_close($conn);
?>
 we perform an INSERT or UPDATE on a table with
an AUTO_INCREMENT field, we can get the ID of
the last inserted/updated record immediately.
 In the table “student", the "id" column is an
AUTO_INCREMENT field:
Example
<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO student (firstname, lastname, email)
VALUES (‘Nadeem', ‘Muhammad', ‘[email protected]')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " .
$last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
 Multiple SQL statements must be executed with the
mysqli_multi_query() function.

 The following examples add three new records to


the “student" table:

<?php
$servername = "localhost";
$username = “root";
$password = “";
$dbname = "mystudent";
$conn = mysqli_connect($servername, $username,
$password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO student (firstname, lastname, email)
VALUES (‘Babar', ‘Ali', ‘[email protected]');";
$sql .= "INSERT INTO student (firstname, lastname, email)
VALUES (‘sara', ‘khan', ‘[email protected]');";
$sql .= "INSERT INTO student (firstname, lastname,
email)
VALUES (‘Mahmood', ‘Zakir', ‘[email protected]')";
if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" .
mysqli_error($conn);
}

mysqli_close($conn);
?>
 A prepared statement is a feature used to execute the
same (or similar) SQL statements repeatedly with high
efficiency.
 Prepared statements basically work like this:
 Prepare: An SQL statement template is created and sent to
the database. Certain values are left unspecified, called
parameters (labeled "?"). Example: INSERT INTO student
VALUES(?, ?, ?)
 The database parses, compiles, and performs query
optimization on the SQL statement template, and stores
the result without executing it
 Execute: At a later time, the application binds the values to
the parameters, and the database executes the statement.
 The application may execute the statement as many times as
it wants with different values
 Compared to executing SQL statements directly, prepared
statements have two main advantages:

 Prepared statements reduces parsing time as the preparation


on the query is done only once (although the statement is
executed multiple times)
 Bound parameters minimize bandwidth to the server as you
need send only the parameters each time, and not the whole
query
 Prepared statements are very useful against SQL injections,
because parameter values, which are transmitted later using a
different protocol, need not be correctly escaped. If the
original statement template is not derived from external
input, SQL injection cannot occur.
Example
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
// Create connection
$conn = new mysqli($servername, $username, $password,
$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("INSERT INTO student
(firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname,
$email);

// set parameters and execute


$firstname = “Khalid";
$lastname = “Zia";
$email = “[email protected]";
$stmt->execute();
$firstname = “Amna";
$lastname = “khan";
$email = “[email protected]";
$stmt->execute();
$firstname = “Zanub";
$lastname = “ali";
$email = “[email protected]";
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
?>
WEEK 12
The SELECT statement is used to select data
from one or more tables:
Example
SELECT column_name(s) FROM table_name

we can use the * character to select ALL


columns from a table:
Example
SELECT * FROM table_name
Example
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
// Create connection
$conn = mysqli_connect($servername, $username,
$password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT id, firstname, lastname FROM student";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " .
$row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
The DELETE statement is used to delete records
from a table.
SQL Statement:-DELETE FROM table_name
WHERE some_column = some_value.
Example:-
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
Example (continued )
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to delete a record
$sql = "DELETE FROM student WHERE id=3";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
 The UPDATE statement is used to update existing
records in a table:
 SQL UPDATE Statement:- UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
Example:-
<?php
$servername = "localhost";
$username = “root";
$password = "";
$dbname = "mystudent";
Example(continued)
// Create connection
$conn = mysqli_connect($servername, $username, $password,
$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE student SET lastname=‘Ismaile‘ WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
 MySQL provides a LIMIT clause that is used to
specify the number of records to return

Example:-
$sql = "SELECT * FROM student Orders LIMIT 05";

When the SQL query above is run, it will return the


first 05 records.
WEEK 13
 File handling is an important part of any web
application. You often need to open and
process a file for different tasks.
 PHP has several functions for creating, reading,
uploading, and editing files.

 Be careful when manipulating files!


When you are manipulating files you must be
very careful. You can do a lot of damage if you
do something wrong.

◦ Common errors are:

 Editing the wrong file


 Filling a hard-drive with garbage data
 And deleting the content of a file by accident
 The readfile() function reads a file and writes it to the
output buffer.

 Assume we have a text file called "webdictionary.txt",


stored on the server, that looks like this:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the
output buffer is as follows (the readfile() function
returns the number of bytes read on success):

Example

<?php
echo readfile("webdictionary.txt");
?>

The readfile() function is useful if all you want to


do is open up a file and read its contents.
A better method to open files is with the fopen() function.
This function gives you more options than the readfile()
function.

We will use the text file, "webdictionary.txt", during the


lessons:

AJAX = Asynchronous JavaScript and XML


CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
 fopen() function looks like this
fopen("webdictionary.txt", "r")

 The first parameter of fopen() contains the


name of the file to be opened and the second
parameter specifies in which mode the file
should be opened.
<?php
$myfile = fopen("webdictionary.txt", "r") or
die("Unable to open file!");
echo
fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
The file may be opened in one of the following modes:

Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

Open a file for write only. Erases the contents of the file or creates a new file
w
if it doesn't exist. File pointer starts at the beginning of the file

Open a file for write only. The existing data in file is preserved. File pointer
a
starts at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for write only. Returns FALSE and an error if file already
x
exists
r+ Open a file for read/write. File pointer starts at the beginning of the file

Open a file for read/write. Erases the contents of the file or creates a new file
w+
if it doesn't exist. File pointer starts at the beginning of the file

Open a file for read/write. The existing data in file is preserved. File pointer
a+
starts at the end of the file. Creates a new file if the file doesn't exist
Creates a new file for read/write. Returns FALSE and an error if file already
x+
exists
The fread() function reads from an open file.

The following PHP code reads the


"webdictionary.txt" file to the end:

fread($myfile,filesize("webdictionary.txt"));

The first parameter of fread() contains the


name of the file to read from and the second
parameter specifies the maximum number of
bytes to read.
 The fclose() function is used to close an open file.

 It's a good programming practice to close all files after you have
finished with them. You don't want an open file running around
on your server taking up resources!

 The fclose() requires the name of the file (or a variable that holds
the filename) we want to close:

Example

<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
 The fgets() function is used to read a single line from a
file.

 The example below outputs the first line of the


"webdictionary.txt" file:

Example

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to
open file!");
echo fgets($myfile);
fclose($myfile);
?>

Note: After a call to the fgets() function, the file pointer has
moved to the next line.
 The feof() function checks if the "end-of-file" (EOF) has been
reached.

 The feof() function is useful for looping through data of unknown


length.

 The example below reads the "webdictionary.txt" file line by line,


until end-of-file is reached:

Example

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
 The fgetc() function is used to read a single character from a file.

 The example below reads the "webdictionary.txt" file character by


character, until end-of-file is reached:

Example

<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

Note: After a call to the fgetc() function, the file pointer moves to the
next character.
PHP Exception Handling
 Creating a custom exception handler is quite
simple.
 We simply create a special class with
functions that can be called when an
exception occurs in PHP.
 The class must be an extension of the
exception class.
 The custom exception class inherits the
properties from PHP's exception class and
you can add custom functions to it.
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>

The new class is a copy of the old exception class with an addition of the
errorMessage() function.
Since it is a copy of the old class, and it inherits the properties and methods from the
old class, we can use the exception class methods like getLine() and getFile() and
getMessage().
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>

The customException() class is created as an extension of the old exception class. This
way it inherits all methods and properties from the old exception class
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>

The errorMessage() function is created. This function returns an error


message if an e-mail address is invalid
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>

The $email variable is set to a string that is not a valid e-mail address
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>

The "try" block is executed and an exception is thrown since the e-mail
address is invalid
<?php
class customException extends Exception {
public function errorMessage() {
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}}
$email = "[email protected]";
try {
//check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage(); } ?>

The "catch" block catches the exception and displays the error message
WEEK 14
 The fopen() function is also used to create a file. Maybe a
little confusing, but in PHP, a file is created using the same
function used to open files.

 If you use fopen() on a file that does not exist, it will create
it, given that the file is opened for writing (w) or
appending (a).

 The example below creates a new file called "testfile.txt".


The file will be created in the same directory where the
PHP code resides:

Example

$myfile = fopen("testfile.txt", "w")

PHP File Permissions


If you are having errors when trying to get this code to run, check that you have
granted your PHP file access to write information to the hard drive.
 The fwrite() function is used to write to a file.
 The first parameter of fwrite() contains the name of the file
to write to and the second parameter is the string to be
written.
 The example below writes a couple of names into a new
file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open
file!");
$txt = "John Doe ";
fwrite($myfile, $txt);
$txt = "Jane Doe ";
fwrite($myfile, $txt);
fclose($myfile);
?>
Example explained

 Notice that we wrote to the file "newfile.txt"


twice. Each time we wrote to the file we sent the
string $txt that first contained "John Doe" and
second contained "Jane Doe". After we finished
writing, we closed the file using the fclose()
function.

If we open the "newfile.txt" file it would look like


this:

John Doe Jane Doe


 Now that "newfile.txt" contains some data we can show
what happens when we open an existing file for writing.
All the existing data will be ERASED and we start with an
empty file.
 In the example below we open our existing file
"newfile.txt", and write some new data into it:

Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open
file!");
$txt = "Mickey Mouse ";
fwrite($myfile, $txt);
$txt = "Minnie Mouse ";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John
and Jane have vanished, and only the data we
just wrote is present:

Mickey Mouse Minnie Mouse


 First, ensure that PHP is configured to allow
file uploads.

 In your "php.ini" file, search for the


file_uploads directive, and set it to On:

file_uploads = On
 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>
Some rules to follow for the HTML form are:
 Make sure that the form uses method="post"
 The form also needs the following attribute:
enctype="multipart/form-data". It specifies which content-type
to use when submitting the form

Without the requirements above, the file upload will not work.

Other things to notice:


 The type="file" attribute of the <input> tag shows the input field
as a file-select control, with a "Browse" button next to the input
control

 The form above sends data to a file called "upload.php", which


we will create next.
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;
}
}?>
 $target_dir = "uploads/" - specifies the
directory where the file is going to be placed
 $target_file specifies the path of the file to be
uploaded
 $uploadOk=1 is not used yet (will be used
later)
 $imageFileType holds the file extension of
the file
 Next, check if the image file is an actual
image or a fake image

Note: You will need to create a new directory called "uploads" in


the directory where "upload.php" file resides. The uploaded files
will be saved there.
 Now we can add some restrictions.

 First, we will check if the file already exists in the


"uploads" folder. If it does, an error message is
displayed, and $uploadOk is set to 0:

// Check if file already exists


if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
 The file input field in our HTML form above is
named "fileToUpload".

 Now, we want to check the size of the file. If the


file is larger than 500kb, an error message is
displayed, and $uploadOk is set to 0:

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
 The code below only allows users to upload JPG,
JPEG, PNG, and GIF files. All other file types gives
an error message before setting $uploadOk to 0:

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType !=
"png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are
allowed.";
$uploadOk = 0;
}
Now if $uploadOk is set to 0 then file will not be uploaded
otherwise file uploading code will be executed

// Check if $uploadOk is set to 0 by an error


if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],
$target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). "
has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
 Exceptions are events that occur during the execution of
programs that disturb the normal flow of instructions.

 We can also explicitly trigger an exception with throw keyword

 After exception is triggered it must be handled

 This is what normally happens when an exception is triggered:


◦ The current code state is saved
◦ The code execution will switch to a predefined (custom) exception
handler function
◦ Depending on the situation, the handler may then resume the
execution from the saved code state, terminate the script execution or
continue the script from a different location in the code

Note: Exceptions should only be used with error conditions, and should
not be used to jump to another place in the code at a specified point.
PHP Exception Handling
 When an exception is thrown, the code following it will not be
executed, and PHP will try to find the matching "catch" block.
 If an exception is not caught, a fatal error will be issued with an
"Uncaught Exception" message.

Lets try to throw an exception without catching it:

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
Fatal error: Uncaught exception 'Exception'
with message 'Value must be 1 or below' in C:\webfolder\test.php:6
Stack trace: #0 C:\webfolder\test.php(12):
checkNum(28) #1 {main} thrown in C:\webfolder\test.php on line 6
 To avoid the error from the example above, we
need to create the proper code to handle an
exception.

 Proper exception code should include:


1. Try - A function using an exception should be in a "try"
block. If the exception does not trigger, the code will
continue as normal. However if the exception triggers,
an exception is "thrown"
2. Throw - This is how you trigger an exception. Each
"throw" must have at least one "catch"
3. Catch - A "catch" block retrieves an exception and
creates an object containing the exception information
Lets try to trigger an exception with valid code:

<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below"); }
return true;
}
//trigger exception in a "try" block
try {
checkNum(2);
//If the exception is thrown, this text will not be shown
echo 'If you see this, the number is 1 or below'; }

//catch exception
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
?>

The code above will get an error like this:

Message: Value must be 1 or below


 The code throws an exception and catches it:
1. The checkNum() function is created. It checks if a
number is greater than 1. If it is, an exception is
thrown
2. The checkNum() function is called in a "try" block
3. The exception within the checkNum() function is
thrown
4. The "catch" block retrieves the exception and
creates an object ($e) containing the exception
information
5. The error message from the exception is echoed
by calling $e->getMessage() from the exception
object
WEEK 15
WordPress is web software you can use to
create a beautiful website, blog, or app. We
like to say that WordPress is both free and
priceless at the same time.
 https://wordpress.org/showcase/
 Free
 Easy to use
 Written in PHP
 MySQL Database at back end
 Easy customization (Themes)

 Simple to understand
 Access to your web server
 A text editor
 An FTP Client
 Your web browser of choice
 Youmust be able to execute PHP at your web
server

 Access to an MySql Database

 In
simple you web hosting company should
provide PHP and MySQL support
 Access to your web server www directory
 A text editor
 Your web browser of choice
 MySQL Database
 Access to your web server www or
public_html directory
 A text editor
 An FTP Client

 Your web browser of choice


 A MySQL Database
WEEK 16
the Pages menu in the WordPress
 Find
Dashboard Navigation menu. Click Add new.

 Add the title of the page, like About. Note:


If you have pretty permalinks set up, the
title of your page will also be the URL slug.

 Next, add some content.

 To Publish the page click on save and publish


 Media consists of the images, video,
recordings, and files that you upload and use
in your site/blog.

 Mediais typically uploaded and inserted into


the content when writing a Post or writing a
Page.
The Media Library Screen allows you to edit,
view, and delete Media previously uploaded to
your blog. Multiple Media objects can be
selected for deletion.

Search and filtering ability is also provided to


allow you to find the desired Media.
You must define a menu before you can add
items to it.

 Login to the Wordpress Dashboard.


 From the 'Appearance' menu on the left-hand
side of the Dashboard, select the 'Menus'
option to bring up the Menu Editor.
 Select Create a new menu at the top of the
page
 Enter a name for your new menu in the Menu
Name box
 Click the Create Menu button.
You can add different link types into your menu, these
are split between panes left of the menu you're
currently editing.

 Locate the pane entitled Pages.


 Within this pane, select the View All link to bring up
a list of all the currently published Pages on your
site.
 Select the Pages that you want to add by clicking the
checkbox next to each Page's title.
 Click the Add to Menu button located at the bottom
of this pane to add your selection(s) to the menu that
you created in the previous step.
 Click the Save Menu button once you've added all the
menu items you want.
 Locate
the menu item that you want to
remove in the menu editor window

 Click
on the arrow icon in the top right-hand
corner of the menu item/box to expand it.

 Click
on the Remove link. The menu
item/box will be immediately removed.

the Save Menu button to save your


 Click
changes.
https://codex.wordpress.org/WordPress_Menu
_User_Guide
WordPress themes are simply a group of files,
called templates, which determine the look
and basic function of your site
https://wordpress.org/themes/
 http://www.templatemonster.com/wordpres
s-themes.php

 http://themeforest.net/

 http://www.themezilla.com/themes/
Plugins tiny pieces of software which are used
to extend and add to the functionality that
already exists in WordPress.

The core of WordPress is designed to be lean


and lightweight, to maximize flexibility and
minimize code bloat. Plugins then offer
custom functions and features so that each
user can tailor their site to their specific
needs.
https://wordpress.org/plugins/
We need to have employee list for our website
which we have developed in Wordpress.

We can use plugins like

 Employee Spotlight
 Simple Staff List
 OS Our Team
The Theme Customizer allows you to preview
changes to your site before publishing them.
You can also navigate to different pages on
your site to preview them.
 Site Title & Tagline
 Colors
 Header Image
 Background Image
 Navigation

 Widgets
 Static Front Page
https://codex.wordpress.org/Appearance_Cust
omize_Screen

You might also like