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
Ad

More Related Content

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

Php
PhpPhp
Php
Gangadhar S
 
Materi Dasar PHP
Materi Dasar PHPMateri Dasar PHP
Materi Dasar PHP
Robby Firmansyah
 
Php Basics
Php BasicsPhp Basics
Php Basics
Shaheed Udham Singh College of engg. n Tech.,Tangori,Mohali
 
Prersentation
PrersentationPrersentation
Prersentation
Ashwin Deora
 
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGEINTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
PRIYADARSINIK3
 
1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master1336333055 php tutorial_from_beginner_to_master
1336333055 php tutorial_from_beginner_to_master
jeeva indra
 
PHP - Web Development
PHP - Web DevelopmentPHP - Web Development
PHP - Web Development
Niladri Karmakar
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
Alokin Software Pvt Ltd
 
UNIT4.pdf php basic programming for begginers
UNIT4.pdf php basic programming for begginersUNIT4.pdf php basic programming for begginers
UNIT4.pdf php basic programming for begginers
AAFREEN SHAIKH
 
PHP
PHPPHP
PHP
Rowena LI
 
Php tutorialw3schools
Php tutorialw3schoolsPhp tutorialw3schools
Php tutorialw3schools
rasool noorpour
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
Arjun Shanka
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
ShaimaaMohamedGalal
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
Shashank Skills Academy
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
PHP from soup to nuts Course Deck
PHP from soup to nuts Course DeckPHP from soup to nuts Course Deck
PHP from soup to nuts Course Deck
rICh morrow
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
Muhamad Al Imran
 

More from AOmaAli (14)

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

Recently uploaded (20)

Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Enterprise Integration Is Dead! Long Live AI-Driven Integration with Apache C...
Markus Eisele
 
AI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of DocumentsAI Agents at Work: UiPath, Maestro & the Future of Documents
AI Agents at Work: UiPath, Maestro & the Future of Documents
UiPathCommunity
 
Dark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanizationDark Dynamism: drones, dark factories and deurbanization
Dark Dynamism: drones, dark factories and deurbanization
Jakub Šimek
 
May Patch Tuesday
May Patch TuesdayMay Patch Tuesday
May Patch Tuesday
Ivanti
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
Could Virtual Threads cast away the usage of Kotlin Coroutines - DevoxxUK2025
João Esperancinha
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Ad

Lecture 6: Introduction to PHP and Mysql .pptx

  • 1. 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
  • 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
  翻译: