Web Development and Applications: PHP (Hypertext Preprocessor)
Web Development and Applications: PHP (Hypertext Preprocessor)
Web Development and Applications: PHP (Hypertext Preprocessor)
APPLICATIONS
PHP (Hypertext Preprocessor)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
Install a web server on your own PC, and then install PHP and MySQL
PHP Syntax
Basic PHP Syntax?
<?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>
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
?>
Variables are used for storing values, such as numbers, strings or functions
results, so that they can be used many times in a script.
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
• 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
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
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
<?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
<?php
echo str_word_count("Hello world!"); 2
?>
Reverse 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.
<?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.
<?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
|| 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
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.
Use the if....elseif...else statement to specify a new condition to test, if the first
condition is false. Syntax
if (condition) {
} elseif (condition) {
} else {
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
The value of the expression is compared with the values for each case in the
structure.
After a code is executed, break is used to stop the code from running into the
next case.
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.
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.
The while loop executes a block of code as long as the specified condition is true.
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;
}
The foreach loop works only on arrays, and is used to loop through each
key/value pair in an array. Syntax
Example
<?php
$colors = array("red", "green",
"blue", "yellow");
Add a "{" - The function code starts after the opening curly brace.
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
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.
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.
• $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.