SlideShare a Scribd company logo
WEB DEVELOPMENT AND
APPLICATIONS
PHP (Hypertext Preprocessor)
By: Gheyath M. Othman
Introduction to PHP (Hypertext Preprocessor)
 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 (OSS)
 PHP is free to download and use
What is PHP?
Introduction
 PHP files may 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"
What is a PHP File ?
 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
What Can PHP Do?
Introduction
 PHP runs on different 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
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
Why PHP?
To start using PHP, you can:
 Find a web host with PHP and MySQL support
 Install a web server on your own PC, and then install PHP and MySQL
What Do You Need?
PHP Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with :
and ends with :
For Example:
Basic PHP Syntax?
<?php
?>
<?php
// PHP code goes here
?>
Note:
• The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, PHP scripting code.
PHP Syntax
Below, we have an example of a simple PHP file, with a PHP script that uses a
built-in PHP function "echo" to output the text "Hello World!" on a web page:
Example:
Basic PHP Syntax?
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
PHP Syntax
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and
user-defined functions are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
PHP Case Sensitivity
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
Note: However; all variable names are case-sensitive.
Comments in 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.
In PHP, we use // to make a single-line comment or /* and */ to make a large
comment block.
<html><body>
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
?>
</body></html>
PHP Variables
 Variables are used for storing values, such as numbers, strings or functions
results, so that they can be used many times in a script.
 All variables in PHP start with a ( $ )sign symbol.
The correct way of setting a variable in PHP:
Example:
Let's try creating a variable with a string, and a variable with a number as the
follow:
Variables in PHP
$var_name = value;
<?php
$txt = "Hello World!";
$number = 16;
?>
PHP Variables
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different variables)
• A variable name should not contain spaces. If a variable name is more than one
word, it should be separated with underscore ($my_string), or with
capitalization ($myString)
Variable Naming Rules
PHP Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Output Variables
<?php
$txt = “Akre City";
echo "I love $txt!";
?>
PHP String
A string variable is used to store and manipulate a piece of text.
String variables are used for values that contains character strings.
Below, the PHP script assigns the string "Hello World" to a string variable called
$txt:
Strings in PHP
<?php
$txt="Hello World";
echo $txt;
?>
PHP String
 There is only one string operator in PHP.
 The concatenation operator (.) is used to put two string values together.
 To concatenate two variables together, use the dot (.) operator , as the follow:
The Concatenation Operator
<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
PHP String
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
Using the strlen() function
<?php
echo strlen("Hello world!");
?>
Note : The length of a string is often used in loops or other functions, when it is
important to know when the string ends. (i.e. in a loop, we would want to stop the
loop after the last character in the string)
12
PHP String
The PHP str_word_count() function counts the number of words in a string:
The PHP strrev() function reverses a string:
Count The Number of Words in a String
<?php
echo str_word_count("Hello world!");
?>
Reverse a String
<?php
echo strrev("Hello world!");
?>
2
!dlrow olleH
PHP String
The PHP str_replace() function replaces some characters with some other
characters in a string.
The example below replaces the text "world" with "Dolly":
Replace Text Within a String
<?php
echo str_replace("world", "Dolly", "Hello
world!");
?>
Hello Dolly
PHP String
The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first
match. If no match is found, it will return FALSE.
Let's see if we can find the string "world" in our string:
Using the strpos() function
<?php
echo strpos("Hello world!","world");
?>
Note :As you see the position of the string "world" in our string is position 6. The
reason that it is 6, and not 7, is that the first position in the string is 0, and not 1.
6
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data
to the screen.
The differences are small: echo has no return value while print has a return
value of 1 so it can be used in expressions. echo can take multiple parameters
while print can take one argument. echo is marginally faster than print.
PHP echo and print Statements
PHP echo and print Statements
The echo statement can be used with or without parentheses: echo or echo().
Display Text
The following example shows how to output text with the echo command
(notice that the text can contain HTML markup):
The PHP echo Statement
<?php
echo "<h2>PHP is Fun!</h2>";
echo "Hello world!<br>";
echo "I'm about to learn PHP!<br>";
echo "This ", "string ", "was ", "made ",
"with multiple parameters.";
?>
PHP echo and print Statements
Display Variables
The following example shows how to output text and variables with the
echo statement:
The PHP echo Statement
<?php
$txt1 = "Learn PHP";
$txt2 = “Akre";
$x = 5;
$y = 4;
echo "<h2>$txt1</h2>";
echo "Study PHP at $txt2<br>";
echo $x + $y;
?>
PHP echo and print Statements
The print statement can be used with or without parentheses: print or print().
Display Text
The following example shows how to output text with the print command (notice
that the text can contain HTML markup):
The PHP print Statement
<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
PHP echo and print Statements
Display Variables
The following example shows how to output text and variables with the print
statement:
The PHP print Statement
<?php
$txt1 = "Learn PHP";
$txt2 = “Akre";
$x = 5;
$y = 4;
print "<h2>$txt1</h2>";
print "Study PHP at $txt2<br>";
print $x + $y;
?>
PHP Operators
Operator Description Example Result
+ Addition x=2
x+2
4
- Subtraction x=2
5-x
3
* Multiplication x=4
x*5
20
/ Division 15/5
5/2
3
2.5
% Modulus (division
remainder)
5%2
10%8
10%2
1
2
0
++ Increment x=5
x++
x=6
-- Decrement x=5
x--
x=4
Arithmetic Operators
PHP Operators
Operator Example Is The Same As
= x=y x=y
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
.= x.=y x=x.y
%= x%=y x=x%y
Assignment Operators
PHP Operators
Operator Description Example
== is equal to 5==8 returns false
!= is not equal 5!=8 returns true
> is greater than 5>8 returns false
< is less than 5<8 returns true
>= is greater than or equal to 5>=8 returns false
<= is less than or equal to 5<=8 returns true
Comparison Operators
PHP Operators
Operator Description Example
&& and x=6
y=3
(x < 10 && y > 1) returns true
|| or x=6
y=3
(x==5 || y==5) returns false
! not x=6
y=3
!(x==y) returns true
Logical Operators
PHP Operators
Operator Description Example
. Concatenation $txt1 . $txt2
.= Concatenation
assignment
$txt1 .= $txt2
PHP String Operators
Operator Description Example
+ Union $x + $y
== Equality $x == $y
=== Identity $x === $y
!= Inequality $x != $y
<> Inequality $x <> $y
!== Non-identity $x !== $y
PHP Array Operators
PHP Conditional Statements
Very often when you write code, you want to perform different actions for
different decisions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
 if statement - executes some code only if a specified condition is true
 if...else statement - executes some code if a condition is true and another
code if the condition is false
 if...elseif....else statement - specifies a new condition to test, if the first
condition is false
 switch statement - selects one of many blocks of code to be executed
PHP Conditional Statements
PHP Conditional Statements
The if statement is used to execute some code only if a specified condition is
true. Syntax
The if Statement
if (condition) {
code to be executed if condition is true;
}
Use the if....else statement to execute some code if a condition is true and
another code if the condition is false. Syntax
The if...else Statement
if (condition) {
code to be executed if condition is true;
}
else {
code to be executed if condition is false;
}
PHP Conditional Statements
Use the if....elseif...else statement to specify a new condition to test, if the first
condition is false. Syntax
The if...elseif....else Statement
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;
}
PHP Conditional Statements
 The switch statement is used to perform different actions based on different
conditions.
 Use the switch statement to select one of many blocks of code to be executed.
The switch Statement
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different
from both label1 and label2;
}
PHP Conditional Statements
This is how it works:
 A single expression (most often a variable) is evaluated once.
 The value of the expression is compared with the values for each case in the
structure.
 If there is a match, the code associated with that case is executed.
 After a code is executed, break is used to stop the code from running into the
next case.
 The default statement is used if none of the cases are true.
The switch Statement
PHP Loops
Often when you write code, you want the same block of code to run over and
over again in a row. Instead of adding several almost equal code-lines in a script,
we can use loops to perform a task like this.
In PHP, we have the following looping statements:
 while - loops through a block of code as long as the specified condition is true.
 do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true.
 for - loops through a block of code a specified number of times.
 foreach - loops through a block of code for each element in an array.
PHP Loops
PHP Loops
The while loop executes a block of code as long as the specified condition is true.
Syntax
Example
while (condition is true) {
code to be executed;
}
The while Loop
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP Loops
The do...while loop will always execute the block of code once, it will then check
the condition, and repeat the loop while the specified condition is true.
Syntax
Example
do {
code to be executed;
} while (condition is true);
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
The do...while Loop
PHP Loops
The for loop is used when you know in advance how many times the script
should run. Syntax
 initialization counter: Initialize the loop counter value.
 test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop
continues. If it evaluates to FALSE, the loop ends.
 increment counter: Increases the loop counter value
Example
for (initialization counter; test counter; increment counter) {
code to be executed;
}
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
The for Loop
PHP Loops
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array. Syntax
Example
foreach ($array as $value) {
code to be executed;
}
<?php
$colors = array("red", "green",
"blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
The foreach Loop
PHP Functions
A function is a block of code that can be executed whenever we need it.
Creating PHP functions:
 All functions start with the word "function()“.
 Name the function - It should be possible to understand what the function
does by its name. The name can start with a letter or underscore (not a
number).
 Add a "{" - The function code starts after the opening curly brace.
 Insert the function code.
 Add a "}" - The function is finished by a closing curly brace.
PHP Functions
Syntax
Example
A simple function that writes my name when it is called:
function functionName() {
code to be executed;
}
PHP Functions
<?php
function writeMyName()
{
echo “Areen";
}
echo "Hello world!<br />";
echo "My name is ";
writeMyName();
?>
To add more functionality to a function, we can add parameters. A parameter
is just like a variable.
Example
PHP Functions - Adding parameters
<?php
function writeMyName($fname)
{
echo $fname . " Ahmed<br />";
}
echo "My name is ";
writeMyName(“Arin");
?>
PHP Functions
 An array is a special variable, which can hold more than one value at a time.
 An array stores multiple values in one single variable
PHP Arrays
In PHP, there are three types of arrays:
• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays
Indexed Array : like
PHP Arrays
$cars = array("Volvo", "BMW", "Toyota");
example
<!DOCTYPE html><html>
<body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . "
and " . $cars[2] . ".";
?>
</body></html>
<!DOCTYPE html><html>
<body>
<?php
$cars = array(“Volvo", “BMW", “Toyota");
foreach ($cars as $value) {
echo "$value <br>";
}
?>
</body></html>
Associative Array : like
PHP Arrays
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
example
<!DOCTYPE html><html>
<body>
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
</body>
</html>
Note: you can use count function to return the length of array.
Like count($age)→ 3
Multidimensional Array : example
PHP Arrays
<!DOCTYPE html><html><body>
<?php
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
</body></html>
Note:
• For a two-dimensional array you need two indices to select an element
• For a three-dimensional array you need three indices to select an element
PHP - Sort Functions For Arrays
• sort() - sort arrays in ascending order
• rsort() - sort arrays in descending order
• asort() - sort associative arrays in ascending order, according to the value
• ksort() - sort associative arrays in ascending order, according to the key
• arsort() - sort associative arrays in descending order, according to the value
• krsort() - sort associative arrays in descending order, according to the key
<!DOCTYPE html><html><body>
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>"; }
?>
</body></html>
Simple example
PHP Superglobal Variables
Several predefined variables in PHP are "superglobals", which means that they are
always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
The PHP superglobal variables are:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
PHP Superglobal Variables
PHP $GLOBALS
$GLOBALS is a PHP super global variable which is used to access global variables
from anywhere in the PHP script (also from within functions or methods). example
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
100
PHP Superglobal Variables
PHP $_SERVER
$_SERVER is a PHP super global variable which holds information about headers,
paths, and script locations. The example below shows how to use some of the
elements in $_SERVER: example
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
<!DOCTYPE html><html><body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit“ name=“submit”>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body></html>
PHP Superglobal Variables
PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.
PHP Superglobal Variables
PHP $_POST
PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables. example
<!DOCTYPE html><html><body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
?>
</body></html>
PHP Superglobal Variables
PHP $_GET
PHP $_GET can also be used to collect form data after submitting an HTML form
with method="get". $_GET can also collect data sent in the URL.
Note: You will learn more about $_POST and $_GET in the PHP Forms chapter.

More Related Content

PDF
Php Tutorials for Beginners
Vineet Kumar Saini
 
PDF
Php tutorial(w3schools)
Arjun Shanka
 
PPTX
PHP
Steve Fort
 
PPSX
Php and MySQL
Tiji Thomas
 
PDF
4.2 PHP Function
Jalpesh Vasa
 
PPT
Php Lecture Notes
Santhiya Grace
 
Php Tutorials for Beginners
Vineet Kumar Saini
 
Php tutorial(w3schools)
Arjun Shanka
 
Php and MySQL
Tiji Thomas
 
4.2 PHP Function
Jalpesh Vasa
 
Php Lecture Notes
Santhiya Grace
 

What's hot (20)

PPTX
Php.ppt
Nidhi mishra
 
PPTX
Php basics
Jamshid Hashimi
 
PDF
Php introduction
krishnapriya Tadepalli
 
PPTX
Html forms
Himanshu Pathak
 
PDF
Intro to HTML and CSS basics
Eliran Eliassy
 
PDF
Laravel Introduction
Ahmad Shah Hafizan Hamidin
 
PPTX
Php
Shyam Khant
 
PPTX
HTML/HTML5
People Strategists
 
PPT
PHP
sometech
 
PDF
GET and POST in PHP
Vineet Kumar Saini
 
PPT
Php Presentation
Manish Bothra
 
PPT
01 Php Introduction
Geshan Manandhar
 
PPT
cascading style sheet ppt
abhilashagupta
 
PPTX
Form Validation in JavaScript
Ravi Bhadauria
 
PPT
Php Ppt
vsnmurthy
 
PPTX
jQuery from the very beginning
Anis Ahmad
 
PPTX
html-table
Dhirendra Chauhan
 
PDF
An Introduction to Redux
NexThoughts Technologies
 
Php.ppt
Nidhi mishra
 
Php basics
Jamshid Hashimi
 
Php introduction
krishnapriya Tadepalli
 
Html forms
Himanshu Pathak
 
Intro to HTML and CSS basics
Eliran Eliassy
 
Laravel Introduction
Ahmad Shah Hafizan Hamidin
 
HTML/HTML5
People Strategists
 
GET and POST in PHP
Vineet Kumar Saini
 
Php Presentation
Manish Bothra
 
01 Php Introduction
Geshan Manandhar
 
cascading style sheet ppt
abhilashagupta
 
Form Validation in JavaScript
Ravi Bhadauria
 
Php Ppt
vsnmurthy
 
jQuery from the very beginning
Anis Ahmad
 
html-table
Dhirendra Chauhan
 
An Introduction to Redux
NexThoughts Technologies
 
Ad

Similar to Web Development Course: PHP lecture 1 (20)

PDF
1336333055 php tutorial_from_beginner_to_master
jeeva indra
 
PDF
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
PDF
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
PPT
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
PPT
Php i basic chapter 3
Muhamad Al Imran
 
PPT
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
PDF
PHP Basic & Variables
M.Zalmai Rahmani
 
PDF
Introduction to PHP
Devshri Pandya
 
PDF
Php tutorialw3schools
rasool noorpour
 
DOCX
PHP NOTES FOR BEGGINERS
Aminiel Michael
 
PPTX
Php intro by sami kz
sami2244
 
PPTX
php Chapter 1.pptx
HambaAbebe2
 
PPTX
PHP Lecture 01 .pptx PHP Lecture 01 pptx
shahgohar1
 
PPTX
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
PRIYADARSINIK3
 
PPTX
introduction to server-side scripting
Amirul Shafeeq
 
DOCX
Basic php 5
Engr. Raud Ahmed
 
PDF
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PPTX
PHP2An introduction to Gnome.pptx.j.pptx
JAYAVARSHINIJR
 
1336333055 php tutorial_from_beginner_to_master
jeeva indra
 
Programming in PHP Course Material BCA 6th Semester
SanthiNivas
 
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Muhamad Al Imran
 
Php i basic chapter 3
Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Muhamad Al Imran
 
PHP Basic & Variables
M.Zalmai Rahmani
 
Introduction to PHP
Devshri Pandya
 
Php tutorialw3schools
rasool noorpour
 
PHP NOTES FOR BEGGINERS
Aminiel Michael
 
Php intro by sami kz
sami2244
 
php Chapter 1.pptx
HambaAbebe2
 
PHP Lecture 01 .pptx PHP Lecture 01 pptx
shahgohar1
 
INTRODUCTION ON PHP - SERVER SIDE SCRIPTING LANGUAGE
PRIYADARSINIK3
 
introduction to server-side scripting
Amirul Shafeeq
 
Basic php 5
Engr. Raud Ahmed
 
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PHP2An introduction to Gnome.pptx.j.pptx
JAYAVARSHINIJR
 
Ad

More from Gheyath M. Othman (9)

PDF
Web Development Course: PHP lecture 4
Gheyath M. Othman
 
PDF
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
PDF
Web Development Course: PHP lecture 2
Gheyath M. Othman
 
PDF
Web Design Course: CSS lecture 1
Gheyath M. Othman
 
PDF
Web Design Course: CSS lecture 5
Gheyath M. Othman
 
PDF
Web Design Course: CSS lecture 4
Gheyath M. Othman
 
PDF
Web Design Course: CSS lecture 3
Gheyath M. Othman
 
PDF
Web Design Course: CSS lecture 2
Gheyath M. Othman
 
PDF
Web Design Course: CSS lecture 6
Gheyath M. Othman
 
Web Development Course: PHP lecture 4
Gheyath M. Othman
 
Web Development Course: PHP lecture 3
Gheyath M. Othman
 
Web Development Course: PHP lecture 2
Gheyath M. Othman
 
Web Design Course: CSS lecture 1
Gheyath M. Othman
 
Web Design Course: CSS lecture 5
Gheyath M. Othman
 
Web Design Course: CSS lecture 4
Gheyath M. Othman
 
Web Design Course: CSS lecture 3
Gheyath M. Othman
 
Web Design Course: CSS lecture 2
Gheyath M. Othman
 
Web Design Course: CSS lecture 6
Gheyath M. Othman
 

Recently uploaded (20)

PPT
How to Protect Your New York Business from the Unexpected
Sam Vohra
 
PDF
The Digital Culture Challenge; Bridging the Employee-Leadership Disconnect
Brian Solis
 
PDF
Danielle Oliveira New Jersey - A Seasoned Lieutenant
Danielle Oliveira New Jersey
 
PDF
Drone Spraying in Agriculture, How It’s Enhancing Efficiency and Crop Yields
ganeshdukare428
 
PPTX
Certificate of Incorporation, Prospectus, Certificate of Commencement of Busi...
Keerthana Chinnathambi
 
PDF
A Complete Guide to Data Migration Services for Modern Businesses
Aurnex
 
PPTX
E-Way Bill under GST – Transport & Logistics.pptx
Keerthana Chinnathambi
 
PPTX
Virbyze_Our company profile_Preview.pptx
myckwabs
 
PDF
Keppel Ltd. 1H 2025 Results Presentation Slides
KeppelCorporation
 
PPTX
Buy Chaos Software – V-Ray, Enscape & Vantage Licenses in India
PI Software
 
PDF
Best 10 Website To Buy Instagram Accounts Bulk 2025 USA
pvabest USA 2025
 
PPTX
GenAI at FinSage Financial Wellness Platform
SUBHANKARGHOSH126678
 
PPTX
Creating the Ultimate SOP Manual: Streamline, Standardize, and Scale
RUPAL AGARWAL
 
PDF
William Trowell - A Construction Project Manager
William Trowell
 
PPTX
NTE 2025/20: Updated End User Undertaking (EUU) Form and Guidance
RT Consulting Limited
 
PDF
Withum Webinar - OBBBA: Tax Insights for Food and Consumer Brands
Withum
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Data Sheet Cloud Integration Platform - dataZap
Chainsys SEO
 
PPTX
斯特灵大学文凭办理|办理UOS毕业证成绩单文凭复刻学历学位认证多久
1cz3lou8
 
PDF
NewBase 29 July 2025 Energy News issue - 1807 by Khaled Al Awadi_compressed.pdf
Khaled Al Awadi
 
How to Protect Your New York Business from the Unexpected
Sam Vohra
 
The Digital Culture Challenge; Bridging the Employee-Leadership Disconnect
Brian Solis
 
Danielle Oliveira New Jersey - A Seasoned Lieutenant
Danielle Oliveira New Jersey
 
Drone Spraying in Agriculture, How It’s Enhancing Efficiency and Crop Yields
ganeshdukare428
 
Certificate of Incorporation, Prospectus, Certificate of Commencement of Busi...
Keerthana Chinnathambi
 
A Complete Guide to Data Migration Services for Modern Businesses
Aurnex
 
E-Way Bill under GST – Transport & Logistics.pptx
Keerthana Chinnathambi
 
Virbyze_Our company profile_Preview.pptx
myckwabs
 
Keppel Ltd. 1H 2025 Results Presentation Slides
KeppelCorporation
 
Buy Chaos Software – V-Ray, Enscape & Vantage Licenses in India
PI Software
 
Best 10 Website To Buy Instagram Accounts Bulk 2025 USA
pvabest USA 2025
 
GenAI at FinSage Financial Wellness Platform
SUBHANKARGHOSH126678
 
Creating the Ultimate SOP Manual: Streamline, Standardize, and Scale
RUPAL AGARWAL
 
William Trowell - A Construction Project Manager
William Trowell
 
NTE 2025/20: Updated End User Undertaking (EUU) Form and Guidance
RT Consulting Limited
 
Withum Webinar - OBBBA: Tax Insights for Food and Consumer Brands
Withum
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Data Sheet Cloud Integration Platform - dataZap
Chainsys SEO
 
斯特灵大学文凭办理|办理UOS毕业证成绩单文凭复刻学历学位认证多久
1cz3lou8
 
NewBase 29 July 2025 Energy News issue - 1807 by Khaled Al Awadi_compressed.pdf
Khaled Al Awadi
 

Web Development Course: PHP lecture 1

  • 1. WEB DEVELOPMENT AND APPLICATIONS PHP (Hypertext Preprocessor) By: Gheyath M. Othman
  • 2. Introduction to PHP (Hypertext Preprocessor)  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 (OSS)  PHP is free to download and use What is PHP?
  • 3. Introduction  PHP files may 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" What is a PHP File ?  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 What Can PHP Do?
  • 4. Introduction  PHP runs on different 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  PHP is free. Download it from the official PHP resource: www.php.net  PHP is easy to learn and runs efficiently on the server side Why PHP? To start using PHP, you can:  Find a web host with PHP and MySQL support  Install a web server on your own PC, and then install PHP and MySQL What Do You Need?
  • 5. PHP Syntax A PHP script can be placed anywhere in the document. A PHP script starts with : and ends with : For Example: Basic PHP Syntax? <?php ?> <?php // PHP code goes here ?> Note: • The default file extension for PHP files is ".php". • A PHP file normally contains HTML tags, PHP scripting code.
  • 6. PHP Syntax Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP function "echo" to output the text "Hello World!" on a web page: Example: Basic PHP Syntax? <html> <body> <?php echo "Hello World!"; ?> </body> </html> Note: PHP statements end with a semicolon (;).
  • 7. PHP Syntax In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive. In the example below, all three echo statements below are legal (and equal): PHP Case Sensitivity <?php ECHO "Hello World!<br>"; echo "Hello World!<br>"; EcHo "Hello World!<br>"; ?> Note: However; all variable names are case-sensitive.
  • 8. Comments in 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. In PHP, we use // to make a single-line comment or /* and */ to make a large comment block. <html><body> <?php // This is a single-line comment # This is also a single-line comment /* This is a multiple-lines comment block that spans over multiple lines */ ?> </body></html>
  • 9. PHP Variables  Variables are used for storing values, such as numbers, strings or functions results, so that they can be used many times in a script.  All variables in PHP start with a ( $ )sign symbol. The correct way of setting a variable in PHP: Example: Let's try creating a variable with a string, and a variable with a number as the follow: Variables in PHP $var_name = value; <?php $txt = "Hello World!"; $number = 16; ?>
  • 10. PHP Variables • A variable starts with the $ sign, followed by the name of the variable • A variable name must start with a letter or the underscore character • A variable name cannot start with a number • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) • Variable names are case-sensitive ($age and $AGE are two different variables) • A variable name should not contain spaces. If a variable name is more than one word, it should be separated with underscore ($my_string), or with capitalization ($myString) Variable Naming Rules
  • 11. PHP Variables The PHP echo statement is often used to output data to the screen. The following example will show how to output text and a variable: Output Variables <?php $txt = “Akre City"; echo "I love $txt!"; ?>
  • 12. PHP String A string variable is used to store and manipulate a piece of text. String variables are used for values that contains character strings. Below, the PHP script assigns the string "Hello World" to a string variable called $txt: Strings in PHP <?php $txt="Hello World"; echo $txt; ?>
  • 13. PHP String  There is only one string operator in PHP.  The concatenation operator (.) is used to put two string values together.  To concatenate two variables together, use the dot (.) operator , as the follow: The Concatenation Operator <?php $txt1="Hello World"; $txt2="1234"; echo $txt1 . " " . $txt2; ?>
  • 14. PHP String The strlen() function is used to find the length of a string. Let's find the length of our string "Hello world!": Using the strlen() function <?php echo strlen("Hello world!"); ?> Note : The length of a string is often used in loops or other functions, when it is important to know when the string ends. (i.e. in a loop, we would want to stop the loop after the last character in the string) 12
  • 15. PHP String The PHP str_word_count() function counts the number of words in a string: The PHP strrev() function reverses a string: Count The Number of Words in a String <?php echo str_word_count("Hello world!"); ?> Reverse a String <?php echo strrev("Hello world!"); ?> 2 !dlrow olleH
  • 16. PHP String The PHP str_replace() function replaces some characters with some other characters in a string. The example below replaces the text "world" with "Dolly": Replace Text Within a String <?php echo str_replace("world", "Dolly", "Hello world!"); ?> Hello Dolly
  • 17. PHP String The strpos() function is used to search for a string or character within a string. If a match is found in the string, this function will return the position of the first match. If no match is found, it will return FALSE. Let's see if we can find the string "world" in our string: Using the strpos() function <?php echo strpos("Hello world!","world"); ?> Note :As you see the position of the string "world" in our string is position 6. The reason that it is 6, and not 7, is that the first position in the string is 0, and not 1. 6
  • 18. PHP echo and print Statements echo and print are more or less the same. They are both used to output data to the screen. The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters while print can take one argument. echo is marginally faster than print. PHP echo and print Statements
  • 19. PHP echo and print Statements The echo statement can be used with or without parentheses: echo or echo(). Display Text The following example shows how to output text with the echo command (notice that the text can contain HTML markup): The PHP echo Statement <?php echo "<h2>PHP is Fun!</h2>"; echo "Hello world!<br>"; echo "I'm about to learn PHP!<br>"; echo "This ", "string ", "was ", "made ", "with multiple parameters."; ?>
  • 20. PHP echo and print Statements Display Variables The following example shows how to output text and variables with the echo statement: The PHP echo Statement <?php $txt1 = "Learn PHP"; $txt2 = “Akre"; $x = 5; $y = 4; echo "<h2>$txt1</h2>"; echo "Study PHP at $txt2<br>"; echo $x + $y; ?>
  • 21. PHP echo and print Statements The print statement can be used with or without parentheses: print or print(). Display Text The following example shows how to output text with the print command (notice that the text can contain HTML markup): The PHP print Statement <?php print "<h2>PHP is Fun!</h2>"; print "Hello world!<br>"; print "I'm about to learn PHP!"; ?>
  • 22. PHP echo and print Statements Display Variables The following example shows how to output text and variables with the print statement: The PHP print Statement <?php $txt1 = "Learn PHP"; $txt2 = “Akre"; $x = 5; $y = 4; print "<h2>$txt1</h2>"; print "Study PHP at $txt2<br>"; print $x + $y; ?>
  • 23. PHP Operators Operator Description Example Result + Addition x=2 x+2 4 - Subtraction x=2 5-x 3 * Multiplication x=4 x*5 20 / Division 15/5 5/2 3 2.5 % Modulus (division remainder) 5%2 10%8 10%2 1 2 0 ++ Increment x=5 x++ x=6 -- Decrement x=5 x-- x=4 Arithmetic Operators
  • 24. PHP Operators Operator Example Is The Same As = x=y x=y += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y .= x.=y x=x.y %= x%=y x=x%y Assignment Operators
  • 25. PHP Operators Operator Description Example == is equal to 5==8 returns false != is not equal 5!=8 returns true > is greater than 5>8 returns false < is less than 5<8 returns true >= is greater than or equal to 5>=8 returns false <= is less than or equal to 5<=8 returns true Comparison Operators
  • 26. PHP Operators Operator Description Example && and x=6 y=3 (x < 10 && y > 1) returns true || or x=6 y=3 (x==5 || y==5) returns false ! not x=6 y=3 !(x==y) returns true Logical Operators
  • 27. PHP Operators Operator Description Example . Concatenation $txt1 . $txt2 .= Concatenation assignment $txt1 .= $txt2 PHP String Operators Operator Description Example + Union $x + $y == Equality $x == $y === Identity $x === $y != Inequality $x != $y <> Inequality $x <> $y !== Non-identity $x !== $y PHP Array Operators
  • 28. PHP Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In PHP we have the following conditional statements:  if statement - executes some code only if a specified condition is true  if...else statement - executes some code if a condition is true and another code if the condition is false  if...elseif....else statement - specifies a new condition to test, if the first condition is false  switch statement - selects one of many blocks of code to be executed PHP Conditional Statements
  • 29. PHP Conditional Statements The if statement is used to execute some code only if a specified condition is true. Syntax The if Statement if (condition) { code to be executed if condition is true; } Use the if....else statement to execute some code if a condition is true and another code if the condition is false. Syntax The if...else Statement if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
  • 30. PHP Conditional Statements Use the if....elseif...else statement to specify a new condition to test, if the first condition is false. Syntax The if...elseif....else Statement 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; }
  • 31. PHP Conditional Statements  The switch statement is used to perform different actions based on different conditions.  Use the switch statement to select one of many blocks of code to be executed. The switch Statement switch (expression) { case label1: code to be executed if expression = label1; break; case label2: code to be executed if expression = label2; break; default: code to be executed if expression is different from both label1 and label2; }
  • 32. PHP Conditional Statements This is how it works:  A single expression (most often a variable) is evaluated once.  The value of the expression is compared with the values for each case in the structure.  If there is a match, the code associated with that case is executed.  After a code is executed, break is used to stop the code from running into the next case.  The default statement is used if none of the cases are true. The switch Statement
  • 33. PHP Loops Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a task like this. In PHP, we have the following looping statements:  while - loops through a block of code as long as the specified condition is true.  do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true.  for - loops through a block of code a specified number of times.  foreach - loops through a block of code for each element in an array. PHP Loops
  • 34. PHP Loops The while loop executes a block of code as long as the specified condition is true. Syntax Example while (condition is true) { code to be executed; } The while Loop <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?>
  • 35. PHP Loops The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true. Syntax Example do { code to be executed; } while (condition is true); <?php $x = 1; do { echo "The number is: $x <br>"; $x++; } while ($x <= 5); ?> The do...while Loop
  • 36. PHP Loops The for loop is used when you know in advance how many times the script should run. Syntax  initialization counter: Initialize the loop counter value.  test counter: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE, the loop ends.  increment counter: Increases the loop counter value Example for (initialization counter; test counter; increment counter) { code to be executed; } <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?> The for Loop
  • 37. PHP Loops The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. Syntax Example foreach ($array as $value) { code to be executed; } <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> The foreach Loop
  • 38. PHP Functions A function is a block of code that can be executed whenever we need it. Creating PHP functions:  All functions start with the word "function()“.  Name the function - It should be possible to understand what the function does by its name. The name can start with a letter or underscore (not a number).  Add a "{" - The function code starts after the opening curly brace.  Insert the function code.  Add a "}" - The function is finished by a closing curly brace. PHP Functions
  • 39. Syntax Example A simple function that writes my name when it is called: function functionName() { code to be executed; } PHP Functions <?php function writeMyName() { echo “Areen"; } echo "Hello world!<br />"; echo "My name is "; writeMyName(); ?>
  • 40. To add more functionality to a function, we can add parameters. A parameter is just like a variable. Example PHP Functions - Adding parameters <?php function writeMyName($fname) { echo $fname . " Ahmed<br />"; } echo "My name is "; writeMyName(“Arin"); ?> PHP Functions
  • 41.  An array is a special variable, which can hold more than one value at a time.  An array stores multiple values in one single variable PHP Arrays In PHP, there are three types of arrays: • Indexed arrays - Arrays with a numeric index • Associative arrays - Arrays with named keys • Multidimensional arrays - Arrays containing one or more arrays
  • 42. Indexed Array : like PHP Arrays $cars = array("Volvo", "BMW", "Toyota"); example <!DOCTYPE html><html> <body> <?php $cars = array("Volvo", "BMW", "Toyota"); echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . "."; ?> </body></html> <!DOCTYPE html><html> <body> <?php $cars = array(“Volvo", “BMW", “Toyota"); foreach ($cars as $value) { echo "$value <br>"; } ?> </body></html>
  • 43. Associative Array : like PHP Arrays $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); example <!DOCTYPE html><html> <body> <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> </body> </html> Note: you can use count function to return the length of array. Like count($age)→ 3
  • 44. Multidimensional Array : example PHP Arrays <!DOCTYPE html><html><body> <?php $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>"; echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>"; echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>"; echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>"; ?> </body></html> Note: • For a two-dimensional array you need two indices to select an element • For a three-dimensional array you need three indices to select an element
  • 45. PHP - Sort Functions For Arrays • sort() - sort arrays in ascending order • rsort() - sort arrays in descending order • asort() - sort associative arrays in ascending order, according to the value • ksort() - sort associative arrays in ascending order, according to the key • arsort() - sort associative arrays in descending order, according to the value • krsort() - sort associative arrays in descending order, according to the key <!DOCTYPE html><html><body> <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); $clength = count($cars); for($x = 0; $x < $clength; $x++) { echo $cars[$x]; echo "<br>"; } ?> </body></html> Simple example
  • 46. PHP Superglobal Variables Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are: • $GLOBALS • $_SERVER • $_REQUEST • $_POST • $_GET • $_FILES • $_ENV • $_COOKIE • $_SESSION
  • 47. PHP Superglobal Variables PHP $GLOBALS $GLOBALS is a PHP super global variable which is used to access global variables from anywhere in the PHP script (also from within functions or methods). example <?php $x = 75; $y = 25; function addition() { $GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y']; } addition(); echo $z; ?> 100
  • 48. PHP Superglobal Variables PHP $_SERVER $_SERVER is a PHP super global variable which holds information about headers, paths, and script locations. The example below shows how to use some of the elements in $_SERVER: example <?php echo $_SERVER['PHP_SELF']; echo "<br>"; echo $_SERVER['SERVER_NAME']; echo "<br>"; echo $_SERVER['HTTP_HOST']; echo "<br>"; echo $_SERVER['HTTP_REFERER']; echo "<br>"; echo $_SERVER['HTTP_USER_AGENT']; echo "<br>"; echo $_SERVER['SCRIPT_NAME']; ?>
  • 49. <!DOCTYPE html><html><body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit“ name=“submit”> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { // collect value of input field $name = $_REQUEST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } ?> </body></html> PHP Superglobal Variables PHP $_REQUEST PHP $_REQUEST is used to collect data after submitting an HTML form.
  • 50. PHP Superglobal Variables PHP $_POST PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. example <!DOCTYPE html><html><body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php // collect value of input field $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } ?> </body></html>
  • 51. PHP Superglobal Variables PHP $_GET PHP $_GET can also be used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Note: You will learn more about $_POST and $_GET in the PHP Forms chapter.