Web Development and Applications: PHP (Hypertext Preprocessor)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

WEB DEVELOPMENT AND

APPLICATIONS
PHP (Hypertext Preprocessor)

By: Gheyath M. Othman


Introduction to PHP (Hypertext Preprocessor)
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 (OSS)

 PHP is free to download and use


Introduction
What is a PHP File ?

 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 Can PHP Do?

 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
Introduction
Why PHP?
 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


What Do You Need?

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
PHP Syntax
Basic PHP Syntax?

A PHP script can be placed anywhere in the document.

A PHP script starts with : <?php

and ends with : ?>


For Example:

<?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
Basic 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:

<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

Note: PHP statements end with a semicolon (;).


PHP Syntax
PHP Case Sensitivity

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

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 in PHP

 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:


$var_name = value;

Example:

Let's try creating a variable with a string, and a variable with a number as the
follow: <?php
$txt = "Hello World!";
$number = 16;
?>
PHP Variables
Variable Naming Rules

• 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)
PHP Variables
Output 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:

<?php
$txt = “Akre City";
echo "I love $txt!";
?>
PHP String
Strings in PHP

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:

<?php
$txt="Hello World";
echo $txt;
?>
PHP String
The Concatenation Operator

 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:

<?php
$txt1="Hello World";
$txt2="1234";
echo $txt1 . " " . $txt2;
?>
PHP String
Using the strlen() function

The strlen() function is used to find the length of a string.

Let's find the length of our string "Hello world!":

<?php
echo strlen("Hello world!"); 12
?>

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)
PHP String
Count The Number of Words in a String

The PHP str_word_count() function counts the number of words in a string:

<?php
echo str_word_count("Hello world!"); 2
?>

Reverse a String

The PHP strrev() function reverses a string:

<?php
echo strrev("Hello world!"); !dlrow olleH
?>
PHP String
Replace Text Within a 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":

<?php
echo str_replace("world", "Dolly", "Hello Hello Dolly
world!");
?>
PHP String
Using the strpos() function

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:

<?php
echo strpos("Hello world!","world"); 6
?>

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.
PHP echo and print Statements
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
The PHP echo Statement

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):

<?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
The PHP echo Statement

Display Variables

The following example shows how to output text and variables with the
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 PHP print Statement

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):

<?php
print "<h2>PHP is Fun!</h2>";
print "Hello world!<br>";
print "I'm about to learn PHP!";
?>
PHP echo and print Statements
The PHP print Statement

Display Variables

The following example shows how to output text and variables with the 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
Arithmetic Operators
Operator Description Example Result
+ Addition x=2 4
x+2
- Subtraction x=2 3
5-x
* Multiplication x=4 20
x*5
/ Division 15/5 3
5/2 2.5
% Modulus (division 5%2 1
remainder) 10%8 2
10%2 0
++ Increment x=5 x=6
x++
-- Decrement x=5 x=4
x--
PHP Operators
Assignment 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
PHP Operators
Comparison 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
PHP Operators
Logical 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
PHP Operators
PHP String Operators

Operator Description Example


. Concatenation $txt1 . $txt2
.= Concatenation $txt1 .= $txt2
assignment

PHP Array Operators


Operator Description Example
+ Union $x + $y
== Equality $x == $y
=== Identity $x === $y
!= Inequality $x != $y
<> Inequality $x <> $y
!== Non-identity $x !== $y
PHP Conditional Statements
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
The if Statement
The if statement is used to execute some code only if a specified condition is
true. Syntax
if (condition) {
code to be executed if condition is true;
}

The if...else Statement


Use the if....else statement to execute some code if a condition is true and
another code if the condition is false. Syntax
if (condition) {
code to be executed if condition is true;
}
else {
code to be executed if condition is false;
}
PHP Conditional Statements
The if...elseif....else Statement

Use the if....elseif...else statement to specify a new condition to test, if the first
condition is false. 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;


}
PHP Conditional Statements
The switch Statement
 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.

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
The switch Statement

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.


PHP Loops
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
The while Loop

The while loop executes a block of code as long as the specified condition is true.

Syntax while (condition is true) {


code to be executed;
}

Example

<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
PHP Loops
The do...while Loop

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 do {
code to be executed;
} while (condition is true);
Example

<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
PHP Loops
The for Loop
The for loop is used when you know in advance how many times the script
should run. Syntax
for (initialization counter; test counter; increment counter) {
code to be executed;
}

 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
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
PHP Loops
The foreach Loop

The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array. Syntax

foreach ($array as $value) {


code to be executed;
}

Example
<?php
$colors = array("red", "green",
"blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
PHP Functions
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
function functionName() {
code to be executed;
}

Example
A simple function that writes my name when it is called:

<?php
function writeMyName()
{
echo “Areen";
}
echo "Hello world!<br />";
echo "My name is ";
writeMyName();
?>
PHP Functions
PHP Functions - Adding parameters

To add more functionality to a function, we can add parameters. A parameter


is just like a variable.

Example

<?php

function writeMyName($fname)
{
echo $fname . " Ahmed<br />";
}
echo "My name is ";
writeMyName(“Arin");

?>
PHP Arrays
 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

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
PHP Arrays
Indexed Array : like
$cars = array("Volvo", "BMW", "Toyota");
example
<!DOCTYPE html><html> <!DOCTYPE html><html>
<body> <body>
<?php <?php
$cars = array("Volvo", "BMW", "Toyota"); $cars = array(“Volvo", “BMW", “Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " foreach ($cars as $value) {
and " . $cars[2] . "."; echo "$value <br>";
?> }
</body></html> ?>
</body></html>
PHP Arrays
Associative Array : like
$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
PHP Arrays
Multidimensional Array : example

<!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
Simple example
<!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>
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() { 100
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
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'];
?>
PHP Superglobal Variables
PHP $_REQUEST
PHP $_REQUEST is used to collect data after submitting an HTML form.

<!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 $_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.

You might also like