0% found this document useful (0 votes)
14 views115 pages

Debremarkos University Computer Science Department: Web Programming

PHP (1)

Uploaded by

aregadaniel9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views115 pages

Debremarkos University Computer Science Department: Web Programming

PHP (1)

Uploaded by

aregadaniel9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 115

Debremarkos University

Computer Science Department


Web Programming
CoSc 3082
Chapter Five:
Sever Side Scripting Language (PHP)
1
PHP
What is PHP?
• PHP is an acronym for "PHP: Hypertext Preprocessor"
• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP is free to download and use

What is a PHP File?


• PHP files can contain text, HTML, CSS, JavaScript, and PHP code.
• PHP code is executed on the server, and the result is returned to the
browser as plain HTML.
• PHP files have extension ".php“. 2
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
 With PHP you are not limited to output HTML.
 You can output images, PDF files, and even Flash movies.
 You can also output any text, such as XHTML and XML. 3
Why PHP?
• PHP runs on various 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's new in PHP 7
• PHP 7 is much faster than the previous popular stable release (PHP
5.6)
• PHP 7 has improved Error Handling
• PHP 7 supports stricter Type Declarations for function arguments
• PHP 7 supports new operators (like the spaceship operator: <=>)
4
PHP Syntax
• A PHP script can be placed anywhere in the document.
• A PHP script starts with <?php and ends with ?>:
<?php
// PHP code goes here
?>The default file extension for PHP files is ".php".
• A PHP file normally contains HTML tags, and some PHP scripting
code.
• 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:
5
Example:
<!DOCTYPE html>
<html>
<body>
<h1>My first PHP page</h1>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
6
PHP Case Sensitivity
• In PHP, 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 equal and
legal:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
Note: However; all variable names are case-sensitive!
7
• Look at the example below; only the first statement will display the
value of the $color variable!
• This is because $color, $COLOR, and $coLOR are treated as three
different variables:
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
</body>
</html>
8
PHP Variables
• Variables are "containers" for storing information.
Creating (Declaring) PHP Variables
• In PHP, a variable starts with the $ sign, followed by the name of the
variable:
<!DOCTYPE html><html><body>
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
echo $txt;
echo "<br>";
echo $x;
echo "<br>";
echo $y;
?>
9
</body></html>
Rules for 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).
 NB: Remember that PHP variable names are case-sensitive!

10
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:
Example:
<!DOCTYPE html>
<html>
<body>
<?php
$txt = "W3Schools.com";
echo "I like $txt!";
?>
</body>
</html>

11
PHP is a Loosely Typed Language
• In the example above, notice that we did not have to tell PHP which
data type the variable is.
• PHP automatically associates a data type to the variable, depending
on its value.
• Since the data types are not set in a strict sense, you can do things like
adding a string to an integer without causing an error.
• In PHP 7, type declarations were added.
• This gives an option to specify the data type expected when declaring
a function, and by enabling the strict requirement, it will throw a
"Fatal Error" on a type mismatch.
12
PHP Variables Scope
• In PHP, variables can be declared anywhere in the script.
• The scope of a variable is the part of the script where the variable can
be referenced/used.
• PHP has three different variable scopes:
 local
 global
 static

13
Global and Local Scope
 A variable declared outside a function has a GLOBAL SCOPE and
can only be accessed outside a function
Example : a variable with global scope
<!DOCTYPE html><html><body>
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
</body></html>
14
• A variable declared within a function has a LOCAL SCOPE and can
only be accessed within that function:
Example :
<!DOCTYPE html><html><body>
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
</body></html>

15
PHP The global Keyword
• The global keyword is used to access a global variable from within a
function.
• To do this, use the global keyword before the variables (inside the
function):
Example:
<!DOCTYPE html><html><body>
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest(); // run function
echo $y; // output the new value for variable $y
?>
16
</body></html> // outputs 15
• PHP also stores all global variables in an array called
$GLOBALS[index].
• The index holds the name of the variable.
• This array is also accessible from within functions and can be used to
update global variables directly.
 The example above can be rewritten like this:
<!DOCTYPE html>
<html>
<body>
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y;
?></body></html> // outputs 15 17
PHP The static Keyword
• Normally, when a function is completed/executed, all of its variables are
deleted. However, sometimes we want a local variable NOT to be deleted.
• To do this, use the static keyword when you first declare the variable:
Example:
<!DOCTYPE html><html><body>
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
echo "<br>";
myTest();
echo "<br>";
myTest();
?> </body></html>
Note: The variable is still local to the function. 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 (although such usage is rare).
• while print can take one argument.
• echo is marginally faster than print.

19
PHP Data Types
 Variables can store data of different types, and different data types can
do different things.
 PHP supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource: It is the special resource type is not an actual data type.
It is the storing of a reference to functions and resources external
to PHP. A common example of using the resource data type is a
database call.
20
1. Scalar types

Boolean, integer, float, double, string

2. Compound types

Array, object

3. Special types

Resource, null

String. String of characters.


Array. An array of values, possibly other arrays. Arrays can be indexed
or associative (i.e., a hash map).
Object. Similar to a class in C++ or Java.
21
• Resource:

• A handle to something that is not PHP data (e.g., image data,


database query result).
• Or in other words, Resource is to represent a PHP extension
resource (e.g. Database query, open file, database connection, etc).
You will never directly touch this type, it will be passed to the
relevant functions that know how to interact with the specified
resource.

•Null :

• data type with only one possible value: null. Marks variables as
being empty. Works with the isset() operator; will return ‘false’ for
null. Example: $var=NULL;
22
PHP String
• A string is a sequence of characters, like "Hello world!".
• A string can be any text inside quotes. You can use single or double
quotes:
<!DOCTYPE html><html><body><?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?></body></html>
• The PHP var_dump() function returns the data type and value.
<?php
$x = 5985;
var_dump($x); O/p: int(5985)
?> 23
PHP String Functions
 The PHP strlen() function returns the length of a string.
<!DOCTYPE html><html><body>
<?php
echo strlen("Hello world!");
?> </body></html>

str_word_count() - Count Words in a String


 The PHP str_word_count() function counts the number of words in a
string.
<!DOCTYPE html>
<html>
<body>
<?php
echo str_word_count("Hello world!");
?> </body></html>
24
strrev() - Reverse a String
 The PHP strrev() function reverses a string.
<!DOCTYPE html><html><body>
<?php
echo strrev("Hello world!");
?> </body></html>

strpos() - Search For a Text Within a String


• The PHP strpos() function searches for a specific text within a string.
• If a match is found, the function returns the character position of the
first match. If no match is found, it will return FALSE.
<?php
echo strpos("Hello world!", "world");
?> 25
PHP Math
• PHP has a set of math functions that allows you to perform
mathematical tasks on numbers.
PHP pi() Function
• The pi() function returns the value of PI:
<?php
echo(pi()); // returns 3.1415926535898
?>
PHP min() and max() Functions
• The min() and max() functions can be used to find the lowest or
highest value in a list of arguments:
<?php
echo(min(0, 150, 30, 20, -8, -200)); // returns -200
echo(max(0, 150, 30, 20, -8, -200)); // returns 150
?> 26
PHP Operators
 Operators are used to perform operations on variables and values.
 PHP divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Increment/Decrement operators
 Logical operators
 String operators
 Array operators
 Conditional assignment operators
27
PHP Arithmetic Operators
• The PHP arithmetic operators are used with numeric values to
perform common arithmetical operations, such as addition,
subtraction, multiplication etc.

Example: <?php
$x = 10;
$y = 3;
echo $x ** $y;
?> 28
PHP Assignment Operators
• The PHP assignment operators are used with numeric values to write
a value to a variable.
• The basic assignment operator in PHP is "=". It means that the left
operand gets set to the value of the assignment expression on the
right.

Example:
<?php
$x = 20;
$x += 100;
echo $x;
?>
29
PHP Conditional Statements
 In PHP we have the following conditional statements:
 if statement - executes some code if one condition is true
 if...else statement - executes some code if a condition is true and
another code if that condition is false
 if...elseif...else statement - executes different codes for more than
two conditions
 switch statement - selects one of many blocks of code to be
executed

30
PHP - The if Statement
 The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
Example
 Output "Have a good day!" if the current time (HOUR) is less than
20:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} 31
PHP - The if...else Statement
 The if...else statement executes some code if a condition is true and another code if
that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Example
 Output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
<?php
$t = date("H");

if ($t < "20") {


echo "Have a good day!";
} else {
echo "Have a good night!";
}
?> 32
PHP - The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if first condition is false and this condition is true;
} else {
code to be executed if all conditions are false;
}
Example:
<?php
$t = date("H");

if ($t < "10") {


echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}?> 33
The PHP switch Statement
 Use the switch statement to select one of many blocks of code to be
executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
} 34
Example:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
35
PHP Loops
 Loops are used to execute the same block of code again and again, as
long as a certain condition is true.
 In PHP, we have the following loop types:
 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
36
The PHP for Loop
 The for loop is used when you know in advance how many times the script
should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed for each iteration;
}
Parameters:
 init 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>";
}
?> 37
The PHP 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: This example displays the numbers from 1 to 5:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
Example Explained
?>
$x = 1; - Initialize the loop counter ($x), and set the start value to 1
$x <= 5 - Continue the loop as long as $x is less than or equal to 5
$x++; - Increase the loop counter value by 1 for each iteration 38
The PHP 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);
• The example below first sets a variable $x to 1 ($x = 1).
• Then, the do while loop will write some output, and then increment
the variable $x with 1.
• Then the condition is checked (is $x less than, or equal to 5?), and the
loop will continue to run as long as $x is less than, or equal to 5:

39
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
 Note: In a do...while loop the condition is tested AFTER executing
the statements within the loop.
 This means that the do...while loop will execute its statements at least
once, even if the condition is false.

40
The PHP 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;
}
• For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
Example: will output the values of the given array ($colors):
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}?> 41
PHP Arrays
• An array is a data structure that stores one or more similar type of
values in a single value.
– For example if you want to store 100 numbers then instead of
defining 100 variables its easy to define an array of 100 length.
• There are three different kind of arrays and each array value is
accessed using an ID which is called array index.
– Numeric array - An array with a numeric index. Values are
stored and accessed in linear fashion.
– Associative array - An array with strings as index. This stores
element values in association with key values rather than in a
strict linear index order.
– Multidimensional array - An array containing one or more
arrays and values are accessed using multiple indices
• NOTE: Built-in php array functions are found in www.
php.net 42
Numeric Array

• These arrays can store numbers, strings and any object but
their index will be represented by numbers. By default array
index starts from zero.
Example
• Following is the example showing how to create and access
numeric arrays.
• Here we have used array() function to create array.

43
<html><body> $numbers[1] = "two";
<?php $numbers[2] = "three";
/* First method to create $numbers[3] = "four";
array. */ $numbers[4] = "five";
$numbers = array( 1, 2, 3, 4, 5); foreach( $numbers as $value )
foreach( $numbers as $value ) {
{ echo "Value is $value <br />";
echo "Value is $value <br/>"; }
} ?>
/* Second method to create array. */ </body></html>
$numbers[0] = "one";

44
This will produce following result:
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five

45
Associative Arrays
• The associative arrays are very similar to numeric arrays in term of
functionality but they are different in terms of their index.
• Associative array will have their index as string so that you can establish
a strong association between key and values.
• To store the salaries of employees in an array, a numerically indexed
array would not be the best choice.
• Instead, we could use the employees names as the keys in our associative
array, and the value would be their respective salary.
– NOTE: Don't keep associative array inside double quote while
printing otherwise it would not return any value.

46
Example
<html><body>
<?php
/* First method to associate create array. */
$salaries = array(
“Amanu" => 2000,
“Selamawit" => 1000,
"zara" => 500
);
echo "Salary of Amanu is ". $salaries[‘Amanu'] . "<br />";
echo "Salary of Selamawit is ". $salaries[‘Selamawit']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

47
/* Second method to create array. */
$salaries[‘Amanu'] = "high";
$salaries[‘Selamawit'] = "medium";
$salaries['zara'] = "low";
echo "Salary of Amanu is ". $salaries[‘Amanu'] . "<br />";
echo "Salary of Selamawit is ". $salaries[‘Selamawit']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
</body></html>

48
Cont.....

This will produce following result:


Salary of Amanu is 2000
Salary of Selamawit is 1000
Salary of zara is 500
Salary of Amanu is high
Salary of Selamawit is medium
Salary of zara is low

49
Multidimensional Arrays
• A multi-dimensional 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.
• Values in the multi-dimensional array are accessed using multiple
index.
Example
• In this example we create a two dimensional array to store marks of
three students in three subjects:
• This example is an associative array, you can create numeric array in
the same fashion. 50
<html><body> "zara" => array
<?php (
"physics" => 31,
$marks = array(
"maths" => 22,
“Amanu" => array (
"chemistry" => 39
)
"physics" => 35, );
"maths" => 30, /*Accessing multi-dimensional array
"chemistry" => 39 ), values */
echo "Marks for Amanu in physics : " ;
"Selamawit" => array echo $marks['mohammad']['physics'] .
"<br />";
echo "Marks for Selamawit in maths : ";
( echo $marks[‘Selamawit']['maths'] .
"physics" => 30, "<br />";
"maths" => 32, echo "Marks for zara in chemistry : " ;
"chemistry" => 29 echo $marks['zara']['chemistry'] . "<br />";
?> </body></html>
),
51
This will produce the following result:
Marks for Amanu in physics : 35
Marks for Selamawit in maths : 32
Marks for zara in chemistry : 39

52
Arrays….

 We can even mix the two if we'd like


– PHP arrays are a cross between numbered arrays and
associative arrays.
– This means that you can use the same syntax and
functions to deal with either type of array, including arrays
that are:
• Indexed from 0

• Indexed by strings

• Indexed with non-continuous numbers


53
• Indexed by a mix of numbers and strings
Arrays….
In the example below, three literal arrays are declared as follows:
1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
Print ($array1[3], $array2["one"], $array3[6]);
?>

54
Arrays….
• From the above example, the indices in the array1 are
implicit, while the indices in array2 are explicit.
• When specifically setting the index to a number N with
the =>operator, the next value has the index N+1 by default.
• Explicit indices do not have to be listed in sequential order.
You can also mix numerical and string indexes, but it is not
recommended.
• Assigning a collection of values to an array variable is
simple using the array() construct:
• $colors = array("blue","indigo","yellow");
• Or, if you know that you want to create an array $colors but
don't yet know what values to fill it with, create an empty
array:
• $colors = array(); 55
Arrays….
• Adding new values to the array is a breeze:
– $colors[] = "hunter green";
• Now the array $colors contains four values.
• Often times, you need to access a single item in an array, such as for
output or a calculation.
• To do this, we can output the second color in the array via the key
1: print $colors[1];
...will output indigo.
– Next, it makes sense to use keys which are labels more meaningful
than a mere index (if you describe for example the car):
$colors = array("exterior"=>"blue",
• "trim"=>"indigo",
• "fabric"=>"yellow",
• "dashboard"=>"hunter green");
56
Arrays….
• It's now easy to output the fabric color of this car, because fabric is a
key in the list:
– print $colors[fabric];
...will output yellow.
• Next, we wanted to output each of the items in $colors, along with the
key associated with that item.
• These returned values are assigned on-the-fly to $key and $value.
foreach ($colors as $key=>$value) {
print "$colors[\"$key\"]== $value<br>"; }
• The similar result is courtesy of the list() function:
while (list($key,$value) = each($colors)) {
print "$key: $value<BR>"; }

57
Arrays….
• In the browser, the above code would output:

exterior: blue
trim: indigo
fabric: yellow
dashboard: hunter green
• Simply, use PHP's ksort() function to sort $colors by key, and then
step through the array as before:
ksort ($colors);
while (list($key,$value) = each($colors)) {
print "$key: $value<BR>"; }
58
Arrays….
• There are various predefined sort functions in PHP
4 sort (rsort for reverse)
• Sorts arrays of numbers numerically
• Sorts arrays of strings alphabetically
• If mixed, the strings count as 0
• Reindexes array so that keys start at 0 and increment from there
4 asort
• Same as sort but retains the original key values (arsort for
reverse)
59
PHP Global Variables – Superglobals
 Super global variables are built-in variables that are always available
in all scopes.
 Some 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 60
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).
• PHP stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable.
• The example below shows how to use the super global variable
$GLOBALS:
• Example:
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z; ?> 61
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:
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER[‘GATEWAY_INTERFACE'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
62
?>
The following table lists the most important elements that can go inside $_SERVER:

63
PHP $_REQUEST
• PHP $_REQUEST is a PHP super global variable which is used to
collect data after submitting an HTML form.
• The example below shows a form with an input field and a submit
button.
• When a user submits the data by clicking on "Submit", the form data
is sent to the file specified in the action attribute of the <form> tag.
• In this example, we point to this file itself for processing form data.
• If you wish to use another PHP file to process form data, replace that
with the filename of your choice.
• Then, we can use the super global variable $_REQUEST to collect the
value of the input field: 64
Example:
<form method="post" action="<?
php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="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;
}
}
?> 65
PHP $_POST
• PHP $_POST is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="post".
• $_POST is also widely used to pass variables.
• The example below shows a form with an input field and a submit
button.
• When a user submits the data by clicking on "Submit", the form data
is sent to the file specified in the action attribute of the <form> tag.
• In this example, we point to the file itself for processing form data.
• If you wish to use another PHP file to process form data, replace that
with the filename of your choice. Then, we can use the super global
variable $_POST to collect the value of the input field: 66
Example:
<form method="post" action="<?
php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
} ?>
67
PHP $_GET
• PHP $_GET is a PHP super global variable which is used to collect
form data after submitting an HTML form with method="get".
• $_GET can also collect data sent in the URL.
 Assume we have an HTML page that contains a hyperlink with
parameters:
<html><body>
<a href="test_get.php?
subject=PHP&web=W3schools.com">Test $GET</a>
</body></html>
 When a user clicks on the link "Test $GET", the parameters "subject"
and "web" are sent to "test_get.php", and you can then access their
values in "test_get.php" with $_GET.
 The example below shows the code in "test_get.php":
<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>
68
PHP Form Validation
 The HTML code of the form looks like this:
<form method="post" action="<?
php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
 When the form is submitted, the form data is sent with
method="post".
 What is the $_SERVER["PHP_SELF"] variable?
 The $_SERVER["PHP_SELF"] is a super global variable that returns
the filename of the currently executing script.
 So, the $_SERVER["PHP_SELF"] sends the submitted form data to
the page itself, instead of jumping to a different page.
69
 What is the htmlspecialchars() function?
 The htmlspecialchars() function converts special characters to HTML
entities.
 This means that it will replace HTML characters like < and > with
&lt; and &gt;.
 This prevents attackers from exploiting the code by injecting HTML
or Javascript code (Cross-site Scripting attacks) in forms.

70
Php form validation using required
• In the following code we have added some new variables:
• $nameErr, $emailErr, $genderErr, and $websiteErr.
• These error variables will hold error messages for the required fields.
• We have also added an if else statement for each $_POST variable.
• This checks if the $_POST variable is empty (with the PHP empty()
function).
• If it is empty, an error message is stored in the different error
variables, and
• if it is not empty, it sends the user input data through the test_input()
function:
71
<!DOCTYPE HTML> <html><head>
<style>.error {color: #FF0000;}</style></head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
function test_input($data) {
$data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data);
return $data; }
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?
>">
Name: <input type="text" name="name">
72
<span class="error">* <?php echo $nameErr;?></span>
Php input Data validation
 "Does the Name field contain only letters and whitespace?", and
 "Does the E-mail field contain a valid e-mail address syntax?", and if
filled out,
 "Does the Website field contain a valid URL?".
PHP - Validate Name
• The code below shows a simple way to check if the name field only
contains letters, dashes, apostrophes and whitespaces.
• If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
• The preg_match() function searches a string for pattern, returning
true if the pattern exists, and false otherwise.
73
PHP - Validate E-mail
• The easiest and safest way to check whether an email address is well-
formed is to use PHP's filter_var() function.
• In the code below, if the e-mail address is not well-formed, then store
an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}

74
PHP - Validate URL
• The code below shows a way to check if a URL address syntax is
valid (this regular expression also allows dashes in the URL).
• If the URL address syntax is not valid, then store an error message:
$website = test_input($_POST["website"]);
if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?
=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

75
PHP Date and Time
 The PHP date() function is used to format a date and/or a time.
The PHP Date() Function
 The PHP date() function formats a timestamp to a more readable date
and time.
Syntax
date(format,timestamp)
Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current
date and time
 A timestamp is a sequence of characters, denoting the date and/or time
at which a certain event occurred. 76
Get a Date
 The required format parameter of the date() function specifies how to
format the date (or time).
Example:

y i 20 20.1 1/03
<?php

ue -11 3
s T 20 1.0
sd -03
To day is 20 20/1
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";

To day is 20

ay
echo "Today is " . date("Y-m-d") . "<br>";

To day
echo "Today is " . date("l");

da is
To
?>

Automatic Copyright Year


• Use the date() function to automatically update the copyright year on
your website:
2020
&copy; 2010-<?php echo date("Y");?> 201
0-
: ©
O/p
77
Get a Time
• Here are some characters that are commonly used for times:
 H - 24-hour format of an hour (00 to 23)
 h - 12-hour format of an hour with leading zeros (01 to 12)
 i - Minutes with leading zeros (00 to 59)
 s - Seconds with leading zeros (00 to 59)
 a - Lowercase Ante meridiem and Post meridiem (am or pm)
Example: 6a m
1 9:0
1 0 :
<?php i s
m e
t i
echo "The time is " . date("h:i:sa");
The
O /p:
?>
• Note that the PHP date() function will return the current date/time of
the server!
78
Get Your Time Zone
Example:
<?php
date_default_timezone_set("America/New_York");
echo "The time is " . date("h:i:sa");
?>
3p m
07 :3
11:
e is
t i m
h e
p: T
O/

79
PHP Include Files
• Including files is very useful when you want to include the same PHP,
HTML, or text on multiple pages of a website.
PHP include and require Statements
• It is possible to insert the content of one PHP file into another PHP
file (before the server executes it), with the include or require
statement.
 The include and require statements are identical, except upon
failure:
 require will produce a fatal error and stop the script.
 include will only produce a warning and the script will continue.
Syntax
include 'filename';
or
require 'filename';
80
• Including files saves a lot of work.
• This means that you can create a standard header, footer, or menu file
for all your web pages.
• Then, when the header needs to be updated, you can only update the
header include file.
PHP include Examples
• Assume we have a standard footer file called "footer.php", that looks
like this:
<?php
echo "<p>Copyright &copy; 1999-" . date("Y") . "
W3Schools.com</p>";
?> 81
 To include the footer file in a page, use the include statement:
<!DOCTYPE html>
<html>
<body>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>
</body>
</html>

82
Sessions and Cookies management in PHP
What are Cookies?
• A cookie is often used to identify a user.
• A cookie is a small file that the server embeds on the user's computer.
• Each time the same computer requests a page with a browser, it will
send the cookie too.
• With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
• A cookie is created with the setcookie() function.
Syntax
 setcookie(name, value, expire);
83
• Only the name parameter is required.
• All other parameters are optional.
 The following example creates a cookie named "user" with the value
“Abebe".
• The cookie will expire after one hour.
<?php
$cookie_name = "user";
$cookie_value = “Abebe";
setcookie($cookie_name, $cookie_value, time() +3600);
?>
Note: The setcookie() function must appear BEFORE the <html> tag.
84
Retrieve a Cookie
• Use the isset() function to find out if the cookie is set:
• Then retrieve the value of the cookie "user" (using the global variable
$_COOKIE).
Example
<html>
<body>
<?php
if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
echo "Welcome guest!<br />";
?>
</body>
</html>
85
Delete a Cookie
• To delete a cookie, use the setcookie() function with an expiration
date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", “Abebe", time() - 3600);
?>
Check if Cookies are Enabled
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
86
What are sessions?
• A PHP session variable is used to store information about, or change
settings for a user session.
• Session variables hold information about one single user, and are
available to all pages in one application.
• When you are working with an application, you open it, do some
changes and then you close it.
• This is much like a Session. The computer knows who you are.
• It knows when you start the application and when you end.
• But on the internet there is one problem: the web server does not
know who you are and what you do because the HTTP address doesn't
maintain state. 87
Cont…
• A PHP session solves this problem by allowing you to store user
information on the server for later use.
• However, session information is temporary and will be deleted after
the user has left the website.
• Sessions work by creating a unique id (UID) for each visitor and store
variables based on this UID.

88
Starting a PHP Session
• Before you can store user information in your PHP session, you must
first start up the session.
 Note: The session_start() function must appear BEFORE the <html>
tag:
<?php session_start(); ?>
• The code above will register the user's session with the server, allow
you to start saving user information, and assign a UID for that user's
session.

89
Storing a Session Variable
• To store and retrieve session variables use the PHP $_SESSION
variable:
<?php
session_start();
// store session data
$_SESSION['visits']=1;
?>

90
Destroying a Session
• If you wish to delete session data, you can use the unset() or the
session_destroy() function.
• The unset() function is used to free the specified session variable:
<?php
unset($_SESSION['visits']);
?>
• You can also completely destroy the session by calling the
session_destroy() function:
<?php
session_destroy();
?> 91
Php Files

• PHP has several functions for creating, reading, uploading, and


editing files.
PHP readfile() Function
• The readfile() function reads a file and writes it to the output buffer.
• Assume we have a text file called “phpfile1.txt", stored on the server,
that looks like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
92
• The PHP code to read the file and write it to the output buffer is as
follows.
• The readfile() function returns the number of bytes read on success.
<?php
echo readfile(“phpfile1.txt");
?>
• The readfile() function is useful if all you want to do is open up a file
and read its contents.

93
PHP Open File - fopen()
• A better method to open files is with the fopen() function.
• This function gives you more options than the readfile() function.
 We will use the text file, “phpfile1.txt“
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
• The first parameter of fopen() contains the name of the file to be
opened and the second parameter specifies in which mode the file
should be opened.
94
• The following example also generates a message if the fopen()
function is unable to open the specified file:
<?php
$myfile = fopen(“phpfile1.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize(“phpfile1.txt"));
fclose($myfile);
?>

95
PHP Read File - fread()
• The fread() function reads from an open file.
• The first parameter of fread() contains the name of the file to read
from and the second parameter specifies the maximum number of
bytes to read.
 The following PHP code reads the “phpfile1.txt" file to the end:
fread($myfile,filesize(“phpfile1.txt"));
PHP Close File - fclose()
• The fclose() function is used to close an open file.
• The fclose() requires the name of the file (or a variable that holds the
filename) we want to close:
<?php
$myfile = fopen(“phpfile1.txt", "r");
// some code to be executed....
fclose($myfile);
?> 96
The file may be opened in one of the following mode;
Modes Description

r Open a file for read only. File pointer starts at the beginning of the file

w Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file

a Open a file for write only. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist

x Creates a new file for write only. Returns FALSE and an error if file already exists

r+ Open a file for read/write. File pointer starts at the beginning of the file

w+ Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file

a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist

x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
97
PHP Read Single Line - fgets()
• The fgets() function is used to read a single line from a file.
• The example below outputs the first line of the “phpfile1.txt" file:
<?php
$myfile = fopen(“phpfile1.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
 Note: After a call to the fgets() function, the file pointer has moved to
the next line.

98
PHP Check End-Of-File - feof()
• The feof() function checks if the "end-of-file" (EOF) has been reached.
• The feof() function is useful for looping through data of unknown length.
• The example below reads the "webdictionary.txt" file line by line, until
end-of-file is reached:
<?php
$myfile = fopen(“phpfile1.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

99
PHP Read Single Character - fgetc()
• The fgetc() function is used to read a single character from a file.
• The example below reads the “phpfile1.txt" file character by
character, until end-of-file is reached:
<?php
$myfile = fopen(“phpfile1.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
 Note: After a call to the fgetc() function, the file pointer moves to the
next character.
100
PHP File Create/Write
PHP Create File - fopen()
• The fopen() function is also used to create a file.
• Maybe a little confusing, but in PHP, a file is created using the same
function used to open files.
• If you use fopen() on a file that does not exist, it will create it, given
that the file is opened for writing (w) or appending (a).
• The example below creates a new file called "testfile.txt".
• The file will be created in the same directory where the PHP code
resides:
$myfile = fopen("testfile.txt", "w")
101
PHP Write to File - fwrite()
• The fwrite() function is used to write to a file.
• The first parameter of fwrite() contains the name of the file to write to
and the second parameter is the string to be written.
• The example below writes a couple of names into a new file called
"newfile.txt":
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = “Alemu Kebede\n";
fwrite($myfile, $txt);
$txt = “Gizew Kebede\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
102
 Notice that we wrote to the file "newfile.txt" twice.
• Each time we wrote to the file we sent the string $txt that first
contained “Alemu Kebede" and second contained “Gizew Kebede".
• After we finished writing, we closed the file using
the fclose() function.
• If we open the "newfile.txt" file it would look like this:
Alemu Kebede
Gizew Kebede

103
PHP Overwriting
• Now that "newfile.txt" contains some data we can show what happens
when we open an existing file for writing.
• All the existing data will be ERASED and we start with an empty file.
• In the example below we open our existing file "newfile.txt", and
write some new data into it:
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
104
• If we now open the "newfile.txt" file, both Alemu and Gizew have
vanished, and only the data we just wrote is present:
Mickey Mouse
Minnie Mouse

PHP Append Text


• You can append data to a file by using the "a" mode.
• The "a" mode appends text to the end of the file, while the "w" mode
overrides (and erases) the old content of the file.
• In the example below we open our existing file "newfile.txt", and
append some text to it:

105
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Donald Duck\n";
fwrite($myfile, $txt);
$txt = "Goofy Goof\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
• If we now open the "newfile.txt" file, we will see that Donald Duck
and Goofy Goof is appended to the end of the file:
Mickey Mouse
Minnie Mouse
Donald Duck
Goofy Goof 106
PHP File Upload
 With PHP, it is easy to upload files to the server.
Configure The "php.ini" File
 First, ensure that PHP is configured to allow file uploads.
 In your "php.ini" file, search for the file_uploads directive, and set it
to On:
file_uploads = On

107
Create The HTML Form
 Next, create an HTML form that allow users to choose the image file
they want to upload:
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/
form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

108
 Some rules to follow for the HTML form above:
• Make sure that the form uses method="post"
• The form also needs the following attribute:
enctype="multipart/form-data".
• It specifies which content-type to use when submitting the form.
 Without the requirements above, the file upload will not work.
 Other things to notice:
 The type="file" attribute of the <input> tag shows the input field as a
file-select control, with a "Browse" button next to the input control
 The form above sends data to a file called "upload.php", which we
will create next.
109
Create The Upload File PHP Script
The "upload.php" file contains the code for uploading a file:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType
= strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
} ?> 110
PHP script explained:
 $target_dir = "uploads/" - specifies the directory where the file is
going to be placed
 $target_file specifies the path of the file to be uploaded
 $uploadOk=1 is not used yet (will be used later)
 $imageFileType holds the file extension of the file (in lower case)
 Next, check if the image file is an actual image or a fake image
 Note: You will need to create a new directory called "uploads" in the
directory where "upload.php" file resides. The uploaded files will be
saved there.

111
Check if File Already Exists
 Now we can add some restrictions.
 First, we will check if the file already exists in the "uploads" folder.
 If it does, an error message is displayed, and $uploadOk is set to 0:
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

112
Limit File Size
 The file input field in our HTML form above is named
"fileToUpload".
 Now, we want to check the size of the file. If the file is larger than
500KB, an error message is displayed, and $uploadOk is set to 0:
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

113
Limit File Type
 The code below only allows users to upload JPG, JPEG, PNG, and
GIF files.
 All other file types gives an error message before setting $uploadOk
to 0:
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" &&
$imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
} 114
h !
u c
M
S o
o u
k Y
a n
T h
115

You might also like