SlideShare a Scribd company logo
Introduction to PHP
COURSE INSTRUCTOR: Akram Ali Omar
Email: akram.ali.omar@gmail.com
Mobile: +255778695626
The State University Of Zanzibar 1
DINF 0212 & DCS 0212: Interactive Website
Development
INTRODUCTION TO PHP
• PHP is a powerful tool for making dynamic and interactive Web
pages.
• We will learn about PHP, and how to execute scripts on your server.
2
What is PHP?
• PHP stands for PHP: Hypertext Preprocessor
• PHP is a server-side scripting language, like ASP
• PHP scripts are executed on the server
• PHP supports many databases (MySQL, Informix, Oracle,
Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
• PHP is an open source software
• PHP is free to download and use
3
Why is PHP used?
1. Easy to Use
Code is embedded into HTML. The PHP code is enclosed in
special start and end tags that allow you to jump into and out of
"PHP mode".
<html>
<head>
<title>Example</title>
</head>
<body>
<?php
echo "Hi, I'm a PHP script!";
?>
</body>
</html>
Why is PHP used?
2. Cross Platform
Runs on almost any Web server on several operating systems.
One of the strongest features is the wide range of supported databases
Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server
Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX,
Windows NT/98/2000/XP/2003
Supported Databases: Adabas D, dBase,Empress, FilePro (read-only),
Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct
MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL,
SQLite, Solid, Sybase, Velocis,Unix dbm
Why is PHP used?
PHP
Software Free
Platform Free (Linux)
Development Tools Free
PHP Coder, jEdit
3. Cost Benefits
PHP is free. Open source code means that the entire PHP
community will contribute towards bug fixes. There are several
add-on technologies (libraries) for PHP that are also free.
Getting Started
1. How to escape from HTML and enter PHP mode
• PHP parses a file by looking for one of the special tags that
tells it to start interpreting the text as PHP code. The parser then
executes all of the code it finds until it runs into a PHP closing tag.
Starting tag Ending tag Notes
<?php ?> Preferred method as it allows the use of
PHP with XHTML
<? ?> Not recommended. Easier to type, but has
to be enabled and may conflict with XML
<script language="php"> ?> Always available, best if used when
FrontPage is the HTML editor
<% %> Not recommended. ASP tags support was
added in 3.0.4
<?php echo “Hello World”; ?>
PHP CODE HTML
HTML
What is a PHP File?
• PHP files can contain text, HTML tags and scripts
• PHP files are returned to the browser as plain HTML
• PHP files have a file extension of ".php", ".php3", or ".phtml"
8
Basic PHP Syntax
• A PHP scripting block always starts with <?php and ends with
?>. A PHP scripting block can be placed anywhere in the
document.
• On servers with shorthand support enabled you can start a
scripting block with <? and end with ?>.
• For maximum compatibility, we recommend that you use the
standard form (<?php) rather than the shorthand form.
<?php
?>
9
simple PHP script which sends the text "Hello
World" to the browser:
10
<html>
<body>
<?php
echo "Hello World";
?>
</body>
</html>
Comments in PHP
In PHP, we use // to make a single-line comment or /* and */ to make a
large comment block.
11
<html>
<body>
<?php
//This is a comment
/*
This is
a comment
block
*/
?>
</body>
</html>
Variables in PHP
• Variables are used for storing a values, like text strings, numbers
or arrays.
• When a variable is declared, it can be used over and over again in
your script.
• All variables in PHP start with a $ sign symbol.
• The correct way of declaring a variable in PHP:
$var_name = value;
• Example:
12
<?php
$txt="Hello World!";
$x=16;
?>
PHP is a Loosely Typed Language
• In PHP, a variable does not need to be declared before adding a
value to it.
• PHP automatically converts the variable to the correct data type,
depending on its value.
• In PHP, the variable is declared automatically when you use it.
13
Naming Rules for Variables
• A variable name must start with a letter or an underscore "_"
• A variable name can only contain alpha-numeric characters and
underscores (a-z, A-Z, 0-9, and _ )
• A variable name should not contain spaces. If a variable name is
more than one word, it should be separated with an underscore
($my_string), or with capitalization ($myString)
14
String Variables in PHP
• String variables are used for values that contains characters.
15
<?php
$txt="Hello World";
echo $txt;
?>
The Concatenation Operator
• The concatenation operator (.) is used to put two string values
together.
16
<?php
$txt1="Hello World!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?>
The strlen() and strpos() function
• The strlen() function is used to return the length of a string.
• The strpos() function is used to search for character within a
string.
17
<?php
echo strpos("Hello world!","world");
?>
<?php
echo strlen("Hello world!");
?>
PHP Operators
• Arithmetic Operators
• Assignment Operators
18
PHP Operators …..
• Comparison Operators
• Logical Operators
19
Conditional Statements
• if statement - use this statement to execute some code only if a
specified condition is true
• if...else statement - use this statement to execute some code if a
condition is true and another code if the condition is false
• if...elseif....else statement - use this statement to select one of
several blocks of code to be executed
• switch statement - use this statement to select one of many
blocks of code to be executed
20
The if Statement
• Syntax
if (condition) code to be executed if condition is true;
• example
21
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri") echo "Have a nice weekend!";
?>
</body>
</html>
The if...else Statement
• Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
• Example
22
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
</body>
</html>
The if...elseif....else Statement
Syntax
if (condition)
code to be executed if condition is
true;
elseif (condition)
code to be executed if condition is
true;
else
code to be executed if condition is
false;
Example
23
<html>
<body>
<?php
$d=date("D");
if ($d=="Fri"){
echo "Have a nice
weekend!";
}
elseif ($d=="Sun"){
echo "Have a nice
Sunday!";
}
else{
echo "Have a nice
day!";
}
?>
</body>
</html>
The PHP Switch Statement
Syntax
24
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both
label1 and label2;
}
The PHP Switch Statement ..
Example
25
<html>
<body>
<?php
switch ($x)
{
case 1: echo "Number 1"; break;
case 2: echo "Number 2"; break;
case 3: echo "Number 3"; break;
default: echo "No number between 1 and 3";
}
?>
</body>
</html>
PHPArrays
In PHP, there are three kind of arrays:
• Numeric array - An array with a numeric index
• Associative array - An array where each ID key is associated
with a value
• Multidimensional array - An array containing one or more
arrays
26
Numeric Arrays
• A numeric array stores each array element with a numeric index.
• There are two methods to create a numeric array.
I. $cars=array("Saab","Volvo","BMW","Toyota");
II. $cars[0]="Saab";
$cars[1]="Volvo";
$cars[2]="BMW";
$cars[3]="Toyota";
27
Associative Arrays
• An associative array, each ID key is associated with a value.
• When storing data about specific named values, a numerical array
is not always the best way to do it.
• With associative arrays we can use the values as keys and assign
values to them.
Example 1
Example 2
28
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
Multidimensional Arrays
• In a multidimensional array, each element in the main array can
also be an array. And each element in the sub-array can be an array,
and so on.
Example1
Example 2
29
$families =
array( "Griffin"=>array ("Peter","Lois","Megan"),"Quagm
ire"=>array( "Glenn"),"Brown"=>array("Cleveland","Loret
ta", "Junior"));
Array([Griffin] => Array([0] => Peter[1] => Lois[2] =>
Megan )[Quagmire] => Array ([0] => Glenn)[Brown] =>
Array ([0] => Cleveland[1] => Loretta [2] => Junior))
PHP Looping - While Loops
• Loops execute a block of code a specified number of times, or
while a specified condition is true.
 The while Loop
The while loop executes a block of code while a condition is
true.
 Syntax
while (condition)
{
code to be executed;
}
30
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i .
"<br />";
$i++;
}
?>
</body>
</html>
The do...while Statement
Syntax
do{
code to be executed;
}
while (condition);
Example
31
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i .
"<br />";
}
while ($i<=5);
?>
</body>
</html>
The for Loop
• The for loop is used when you know in advance how many times
the script should run.
• Syntax
for (init; condition; increment)
{
code to be executed;
}
Example
32
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i
. "<br />";
}
?>
</body>
</html>
The foreach Loop
• The foreach loop is used to loop through arrays.
• Syntax
foreach ($array as $value)
{
code to be executed;
}
Example
33
<html>
<body>
<?php
$x=array("one","two","three"
);
foreach ($x as $value)
{
echo $value . "<br />";
}
?>
</body>
</html>
34
PHP Functions
• The real power of PHP comes from its functions.
• In PHP, there are more than 700 built-in functions.
PHP Built-in Functions
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
35
PHP Functions
Example
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
36
PHP Date() Function
• The PHP date() function is used to format a
time and/or date.
• Syntax
date(format,timestamp)
37
PHP Date() - Format the Date
• The required format parameter in the date() function
specifies how to format the date/time.
• Here are some characters that can be used:
 d - Represents the day of the month (01 to 31)
 m - Represents a month (01 to 12)
 Y - Represents a year (in four digits)
• Other characters, like"/", ".", or "-" can also be
inserted between the letters to add additional
formatting:
38
PHP Date() - Examples
39
PHP Date() - Adding a Timestamp
• The mktime() function returns the Unix
timestamp for a date
40
PHP Date() - Adding a Timestamp
• PHP Date / Time Functions
Nesting Files
• require(), include(), include_once(), require_once() are
used to bring in an external file
• This lets you use the same chunk of code in a number
of pages, or read other kinds of files into your program
• Be VERY careful of using these anywhere close to user
input--if a hacker can specify the file to be included,
that file will execute within your script, with whatever
rights your script has (readfile is a good alternative if
you just want the file, but don't need to execute it)
Include VS Require function
• The require() function is identical to include(), except that it handles errors differently
• When using include and include_once, if the including PHP files is not exist, PHP post a
warning and try to execute the program
• Require and require_once is used to make sure that a file is included and to stop the
program if it isn’t
PHP form handling
Web Server
User
User requests a particular URL
XHTML Page supplied with Form
User fills in form and submits.
Another URL is requested and the
Form data is sent to this page either in
URL or as a separate piece of data.
XHTML Response
PHP form handling
 The form variables are available to PHP in the page to which
they have been submitted.
 The variables are available in two superglobal arrays created
by PHP called $_POST and $_GET.
 There is another array called $_REQUEST which merges
GET and POST data
Access data
• Access submitted data in the relevant array for the
submission type, using the input name as a key.
<form action=“path/to/submit/page”
method=“get”>
<input type=“text” name=“email”>
</form>
$email = $_GET[‘email’];
To get value of multiple checked checkboxes
 name attribute in HTML input type=”checkbox” tag must be
initialize with an array, to do this write [ ] at the end of it’s
name attribute
 Example
PHP File Upload
 With PHP, it is possible to upload files to the server.
 Create an Upload-File Form
• The enctype attribute of the <form> tag specifies which
content-type to use when submitting the form.
• "multipart/form-data" is used when a form requires binary
data, like the contents of a file, to be uploaded
<html>
<body>
<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Restrictions on Upload
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
}
else
{
echo "Invalid file";
}
?>
Saving the Uploaded File
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)){
if ($_FILES["file"]["error"] > 0){
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else{
echo "Invalid file";
}
?>
A warning..
NEVER TRUST USER INPUT
• Always check what has been input.
• Validation can be undertaken using
Regular expressions or in-built PHP
functions.
Assignment: Repeat assignment
4(client side validation) using php
(sever side validation)
The State University Of Zanzibar 51

More Related Content

Similar to Lecture 6: Introduction to PHP and Mysql .pptx (20)

PPT
Php i-slides
ravi18011991
 
PPTX
Php
Richa Goel
 
PPT
PHP - Web Development
Niladri Karmakar
 
PPT
Php(report)
Yhannah
 
PPTX
Day1
IRWAA LLC
 
PPT
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
PPTX
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
PPT
introduction to php web programming 2024.ppt
idaaryanie
 
PPT
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
PDF
Lecture14-Introduction to PHP-coding.pdf
IotenergyWater
 
PPTX
Php.ppt
Nidhi mishra
 
PPTX
php Chapter 1.pptx
HambaAbebe2
 
PDF
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
PDF
PHP Basic & Variables
M.Zalmai Rahmani
 
PPT
php basic notes of concept for beginners
yashpalmodi1990
 
PPT
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
PDF
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
PPT
Prersentation
Ashwin Deora
 
Php i-slides
ravi18011991
 
PHP - Web Development
Niladri Karmakar
 
Php(report)
Yhannah
 
Day1
IRWAA LLC
 
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
introduction to php web programming 2024.ppt
idaaryanie
 
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Lecture14-Introduction to PHP-coding.pdf
IotenergyWater
 
Php.ppt
Nidhi mishra
 
php Chapter 1.pptx
HambaAbebe2
 
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
PHP Basic & Variables
M.Zalmai Rahmani
 
php basic notes of concept for beginners
yashpalmodi1990
 
PHP complete reference with database concepts for beginners
Mohammed Mushtaq Ahmed
 
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
Prersentation
Ashwin Deora
 

More from AOmaAli (15)

PPTX
Introduction to Foundation of Computing Lecture 1.pptx
AOmaAli
 
PPTX
Lecture 3 Introduction to HTML FORM AND CSS.pptx
AOmaAli
 
PPTX
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
PPT
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
AOmaAli
 
PDF
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
AOmaAli
 
PPTX
SSdsdc dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
AOmaAli
 
PPTX
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
PPTX
Lecture 2 Software Development Process and SDCL models.pptx
AOmaAli
 
PPTX
LECTURE 2 -Object oriented Java Basics.pptx
AOmaAli
 
PPTX
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
PPTX
Software development life cycle (SDLC) Models
AOmaAli
 
PPTX
LECTURE 14 Data Access.pptx
AOmaAli
 
PPTX
LECTURE 12 WINDOWS FORMS PART 2.pptx
AOmaAli
 
PPTX
LECTURE 1 - Introduction to Programming.pptx
AOmaAli
 
PPTX
LECTURE 1-Introduction to mobile communication systems.pptx
AOmaAli
 
Introduction to Foundation of Computing Lecture 1.pptx
AOmaAli
 
Lecture 3 Introduction to HTML FORM AND CSS.pptx
AOmaAli
 
lecture 7 - Introduction to MySQL with PHP.pptx
AOmaAli
 
3-itec229 sddds dfsddfdf dfdfdf _chapter1.ppt
AOmaAli
 
Instructional Design - Storyboard_IT Teaching Methods_ED 2216_MSM.pdf
AOmaAli
 
SSdsdc dssdsd sfdddsd sdsds assas sdsddsdsdAD.pptx
AOmaAli
 
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
Lecture 2 Software Development Process and SDCL models.pptx
AOmaAli
 
LECTURE 2 -Object oriented Java Basics.pptx
AOmaAli
 
LECTURE 1-BASIC CONCEPT OF INFORMATION SYSTEM.pptx
AOmaAli
 
Software development life cycle (SDLC) Models
AOmaAli
 
LECTURE 14 Data Access.pptx
AOmaAli
 
LECTURE 12 WINDOWS FORMS PART 2.pptx
AOmaAli
 
LECTURE 1 - Introduction to Programming.pptx
AOmaAli
 
LECTURE 1-Introduction to mobile communication systems.pptx
AOmaAli
 
Ad

Recently uploaded (20)

DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Digital Circuits, important subject in CS
contactparinay1
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Ad

Lecture 6: Introduction to PHP and Mysql .pptx

  • 1. Introduction to PHP COURSE INSTRUCTOR: Akram Ali Omar Email: [email protected] Mobile: +255778695626 The State University Of Zanzibar 1 DINF 0212 & DCS 0212: Interactive Website Development
  • 2. INTRODUCTION TO PHP • PHP is a powerful tool for making dynamic and interactive Web pages. • We will learn about PHP, and how to execute scripts on your server. 2
  • 3. What is PHP? • PHP stands for PHP: Hypertext Preprocessor • PHP is a server-side scripting language, like ASP • PHP scripts are executed on the server • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.) • PHP is an open source software • PHP is free to download and use 3
  • 4. Why is PHP used? 1. Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags that allow you to jump into and out of "PHP mode". <html> <head> <title>Example</title> </head> <body> <?php echo "Hi, I'm a PHP script!"; ?> </body> </html>
  • 5. Why is PHP used? 2. Cross Platform Runs on almost any Web server on several operating systems. One of the strongest features is the wide range of supported databases Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise Server Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac OSX, Windows NT/98/2000/XP/2003 Supported Databases: Adabas D, dBase,Empress, FilePro (read-only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase, mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8), Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm
  • 6. Why is PHP used? PHP Software Free Platform Free (Linux) Development Tools Free PHP Coder, jEdit 3. Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute towards bug fixes. There are several add-on technologies (libraries) for PHP that are also free.
  • 7. Getting Started 1. How to escape from HTML and enter PHP mode • PHP parses a file by looking for one of the special tags that tells it to start interpreting the text as PHP code. The parser then executes all of the code it finds until it runs into a PHP closing tag. Starting tag Ending tag Notes <?php ?> Preferred method as it allows the use of PHP with XHTML <? ?> Not recommended. Easier to type, but has to be enabled and may conflict with XML <script language="php"> ?> Always available, best if used when FrontPage is the HTML editor <% %> Not recommended. ASP tags support was added in 3.0.4 <?php echo “Hello World”; ?> PHP CODE HTML HTML
  • 8. What is a PHP File? • PHP files can contain text, HTML tags and scripts • PHP files are returned to the browser as plain HTML • PHP files have a file extension of ".php", ".php3", or ".phtml" 8
  • 9. Basic PHP Syntax • A PHP scripting block always starts with <?php and ends with ?>. A PHP scripting block can be placed anywhere in the document. • On servers with shorthand support enabled you can start a scripting block with <? and end with ?>. • For maximum compatibility, we recommend that you use the standard form (<?php) rather than the shorthand form. <?php ?> 9
  • 10. simple PHP script which sends the text "Hello World" to the browser: 10 <html> <body> <?php echo "Hello World"; ?> </body> </html>
  • 11. Comments in PHP In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. 11 <html> <body> <?php //This is a comment /* This is a comment block */ ?> </body> </html>
  • 12. Variables in PHP • Variables are used for storing a values, like text strings, numbers or arrays. • When a variable is declared, it can be used over and over again in your script. • All variables in PHP start with a $ sign symbol. • The correct way of declaring a variable in PHP: $var_name = value; • Example: 12 <?php $txt="Hello World!"; $x=16; ?>
  • 13. PHP is a Loosely Typed Language • In PHP, a variable does not need to be declared before adding a value to it. • PHP automatically converts the variable to the correct data type, depending on its value. • In PHP, the variable is declared automatically when you use it. 13
  • 14. Naming Rules for Variables • A variable name must start with a letter or an underscore "_" • A variable name can only contain alpha-numeric characters and underscores (a-z, A-Z, 0-9, and _ ) • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with an underscore ($my_string), or with capitalization ($myString) 14
  • 15. String Variables in PHP • String variables are used for values that contains characters. 15 <?php $txt="Hello World"; echo $txt; ?>
  • 16. The Concatenation Operator • The concatenation operator (.) is used to put two string values together. 16 <?php $txt1="Hello World!"; $txt2="What a nice day!"; echo $txt1 . " " . $txt2; ?>
  • 17. The strlen() and strpos() function • The strlen() function is used to return the length of a string. • The strpos() function is used to search for character within a string. 17 <?php echo strpos("Hello world!","world"); ?> <?php echo strlen("Hello world!"); ?>
  • 18. PHP Operators • Arithmetic Operators • Assignment Operators 18
  • 19. PHP Operators ….. • Comparison Operators • Logical Operators 19
  • 20. Conditional Statements • if statement - use this statement to execute some code only if a specified condition is true • if...else statement - use this statement to execute some code if a condition is true and another code if the condition is false • if...elseif....else statement - use this statement to select one of several blocks of code to be executed • switch statement - use this statement to select one of many blocks of code to be executed 20
  • 21. The if Statement • Syntax if (condition) code to be executed if condition is true; • example 21 <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; ?> </body> </html>
  • 22. The if...else Statement • Syntax if (condition) code to be executed if condition is true; else code to be executed if condition is false; • Example 22 <html> <body> <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend!"; else echo "Have a nice day!"; ?> </body> </html>
  • 23. The if...elseif....else Statement Syntax if (condition) code to be executed if condition is true; elseif (condition) code to be executed if condition is true; else code to be executed if condition is false; Example 23 <html> <body> <?php $d=date("D"); if ($d=="Fri"){ echo "Have a nice weekend!"; } elseif ($d=="Sun"){ echo "Have a nice Sunday!"; } else{ echo "Have a nice day!"; } ?> </body> </html>
  • 24. The PHP Switch Statement Syntax 24 switch (n) { case label1: code to be executed if n=label1; break; case label2: code to be executed if n=label2; break; default: code to be executed if n is different from both label1 and label2; }
  • 25. The PHP Switch Statement .. Example 25 <html> <body> <?php switch ($x) { case 1: echo "Number 1"; break; case 2: echo "Number 2"; break; case 3: echo "Number 3"; break; default: echo "No number between 1 and 3"; } ?> </body> </html>
  • 26. PHPArrays In PHP, there are three kind of arrays: • Numeric array - An array with a numeric index • Associative array - An array where each ID key is associated with a value • Multidimensional array - An array containing one or more arrays 26
  • 27. Numeric Arrays • A numeric array stores each array element with a numeric index. • There are two methods to create a numeric array. I. $cars=array("Saab","Volvo","BMW","Toyota"); II. $cars[0]="Saab"; $cars[1]="Volvo"; $cars[2]="BMW"; $cars[3]="Toyota"; 27
  • 28. Associative Arrays • An associative array, each ID key is associated with a value. • When storing data about specific named values, a numerical array is not always the best way to do it. • With associative arrays we can use the values as keys and assign values to them. Example 1 Example 2 28 $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34); $ages['Peter'] = "32"; $ages['Quagmire'] = "30"; $ages['Joe'] = "34";
  • 29. Multidimensional Arrays • In a multidimensional array, each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Example1 Example 2 29 $families = array( "Griffin"=>array ("Peter","Lois","Megan"),"Quagm ire"=>array( "Glenn"),"Brown"=>array("Cleveland","Loret ta", "Junior")); Array([Griffin] => Array([0] => Peter[1] => Lois[2] => Megan )[Quagmire] => Array ([0] => Glenn)[Brown] => Array ([0] => Cleveland[1] => Loretta [2] => Junior))
  • 30. PHP Looping - While Loops • Loops execute a block of code a specified number of times, or while a specified condition is true.  The while Loop The while loop executes a block of code while a condition is true.  Syntax while (condition) { code to be executed; } 30 <html> <body> <?php $i=1; while($i<=5) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html>
  • 31. The do...while Statement Syntax do{ code to be executed; } while (condition); Example 31 <html> <body> <?php $i=1; do { $i++; echo "The number is " . $i . "<br />"; } while ($i<=5); ?> </body> </html>
  • 32. The for Loop • The for loop is used when you know in advance how many times the script should run. • Syntax for (init; condition; increment) { code to be executed; } Example 32 <html> <body> <?php for ($i=1; $i<=5; $i++) { echo "The number is " . $i . "<br />"; } ?> </body> </html>
  • 33. The foreach Loop • The foreach loop is used to loop through arrays. • Syntax foreach ($array as $value) { code to be executed; } Example 33 <html> <body> <?php $x=array("one","two","three" ); foreach ($x as $value) { echo $value . "<br />"; } ?> </body> </html>
  • 34. 34 PHP Functions • The real power of PHP comes from its functions. • In PHP, there are more than 700 built-in functions. PHP Built-in Functions A function will be executed by a call to the function. You may call a function from anywhere within a page. Create a PHP Function A function will be executed by a call to the function. Syntax function functionName() { code to be executed; }
  • 35. 35 PHP Functions Example <html> <body> <?php function writeName() { echo "Kai Jim Refsnes"; } echo "My name is "; writeName(); ?> </body> </html>
  • 36. 36 PHP Date() Function • The PHP date() function is used to format a time and/or date. • Syntax date(format,timestamp)
  • 37. 37 PHP Date() - Format the Date • The required format parameter in the date() function specifies how to format the date/time. • Here are some characters that can be used:  d - Represents the day of the month (01 to 31)  m - Represents a month (01 to 12)  Y - Represents a year (in four digits) • Other characters, like"/", ".", or "-" can also be inserted between the letters to add additional formatting:
  • 38. 38 PHP Date() - Examples
  • 39. 39 PHP Date() - Adding a Timestamp • The mktime() function returns the Unix timestamp for a date
  • 40. 40 PHP Date() - Adding a Timestamp • PHP Date / Time Functions
  • 41. Nesting Files • require(), include(), include_once(), require_once() are used to bring in an external file • This lets you use the same chunk of code in a number of pages, or read other kinds of files into your program • Be VERY careful of using these anywhere close to user input--if a hacker can specify the file to be included, that file will execute within your script, with whatever rights your script has (readfile is a good alternative if you just want the file, but don't need to execute it)
  • 42. Include VS Require function • The require() function is identical to include(), except that it handles errors differently • When using include and include_once, if the including PHP files is not exist, PHP post a warning and try to execute the program • Require and require_once is used to make sure that a file is included and to stop the program if it isn’t
  • 43. PHP form handling Web Server User User requests a particular URL XHTML Page supplied with Form User fills in form and submits. Another URL is requested and the Form data is sent to this page either in URL or as a separate piece of data. XHTML Response
  • 44. PHP form handling  The form variables are available to PHP in the page to which they have been submitted.  The variables are available in two superglobal arrays created by PHP called $_POST and $_GET.  There is another array called $_REQUEST which merges GET and POST data
  • 45. Access data • Access submitted data in the relevant array for the submission type, using the input name as a key. <form action=“path/to/submit/page” method=“get”> <input type=“text” name=“email”> </form> $email = $_GET[‘email’];
  • 46. To get value of multiple checked checkboxes  name attribute in HTML input type=”checkbox” tag must be initialize with an array, to do this write [ ] at the end of it’s name attribute  Example
  • 47. PHP File Upload  With PHP, it is possible to upload files to the server.  Create an Upload-File Form • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. • "multipart/form-data" is used when a form requires binary data, like the contents of a file, to be uploaded <html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
  • 48. Restrictions on Upload <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Stored in: " . $_FILES["file"]["tmp_name"]; } } else { echo "Invalid file"; } ?>
  • 49. Saving the Uploaded File <?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)){ if ($_FILES["file"]["error"] > 0){ echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])){ echo $_FILES["file"]["name"] . " already exists. "; } else{ move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else{ echo "Invalid file"; } ?>
  • 50. A warning.. NEVER TRUST USER INPUT • Always check what has been input. • Validation can be undertaken using Regular expressions or in-built PHP functions. Assignment: Repeat assignment 4(client side validation) using php (sever side validation)
  • 51. The State University Of Zanzibar 51