Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
67 views128 pages

M 04 S 01 Advanced PHP Day 2

This document provides an overview of file handling in PHP. It discusses opening, reading, writing, and closing files using functions like fopen(), fread(), fwrite(), fclose(), as well as shortcuts like file_get_contents() and file_put_contents(). It also covers checking the end of a file, renaming/deleting files, and applying some functions to URLs in addition to the local file system. The goal is to demonstrate the extensive functionality available in PHP for performing operations on files and the file system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views128 pages

M 04 S 01 Advanced PHP Day 2

This document provides an overview of file handling in PHP. It discusses opening, reading, writing, and closing files using functions like fopen(), fread(), fwrite(), fclose(), as well as shortcuts like file_get_contents() and file_put_contents(). It also covers checking the end of a file, renaming/deleting files, and applying some functions to URLs in addition to the local file system. The goal is to demonstrate the extensive functionality available in PHP for performing operations on files and the file system.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 128

Advanced

PHP
Day 2

v3.0

1
Agenda

1. Files
2. Exceptions
3. Filters
4. PHP Namespaces
5. Mail
6. XML
7. Traits

2
Files

3
Files

In PHP we have the ability to perform a lot of A key thing to remember when operating on a file
operations on the file system, such as: reading, system using PHP is that the user who runs the
writing, deleting, moving, creating directories, etc. PHP script (server) should have a permission to
modify files.
Thanks to built-in functions, all these activities can
be carried out easily.
The functionality is so extensive that we can write a
simple file manager.

4
Files
Opening a file
fopen() – opens the file with the option of selecting the mode. Returns a pointer to a file which we will
use for operations on this file.
r – read-only,
w – write-only, it starts from the beginning of the file and clears its contents (overwrites). If the file
does not exist, it creates it,
a – write-only, it starts writing at the end of the file (adds),
r+, w+ – the same as r+w,
a+ – the same as r+a.

$handle=fopen("/home/resource.txt","r");

5
Files
Reading a file
fread() – reads the specified number of bytes from a file,
fgets() – reads one line from the file,
fgetc() – reads one character from the file,
fpassthru() – reads the file to the end and sends the content to the output buffer.

$contents = fread($handle, filesize($filename));


$buffer = fgets($handle);

6
Files
Reading a file
fread() – reads the specified number of bytes from a file,
fgets() – reads one line from the file,
fgetc() – reads one character from the file,
fpassthru() – reads the file to the end and sends the content to the output buffer.

$contents = fread($handle, filesize($filename));


$buffer = fgets($handle);

The resource indicator is necessary for php to know on which file it should make changes when using the
function.

7
Files
Writing to a file Detecting the end of the file
fputs(), fwrite() – writes the string to a file, feof() – function returns true, if the end of the
returns the number of bytes. file has been reached (End Of File).
$length = fwrite($handle, $text); $file = fopen('example.txt', 'r');
$file = fopen("example.txt", "w"); while (!feof($file)) {
echo fwrite($file,"Hello World. Test!"); $c = fgetc($file);
fclose($file);//10 – number of bytes // ... do something with $c
}
echo 'End of file';

8
Files
Writing to a file Detecting the end of the file
fputs(), fwrite() – writes the string to a file, feof() – function returns true, if the end of the
returns the number of bytes. file has been reached (End Of File).
$length = fwrite($handle, $text); $file = fopen('example.txt', 'r');
$file = fopen("example.txt", "w"); while (!feof($file)) {
echo fwrite($file,"Hello World. Test!"); $c = fgetc($file);
fclose($file);//10 – number of bytes // ... do something with $c
}
echo 'End of file';

Loop while and reading fgetc will be done until


the function feof returns true.

9
Files
Closing a file Shortcuts
Each file pointer should be closed by the function Function file() reads the entire file with the
fclose(), if we finished working with the file. given name and returns its contents in the form of
an array.
$handle = fopen('example.txt', 'r');
//... One row of the array corresponds to one line of
//do something with file $handle text.
//...
fclose($handle); Often used for reading files with logs.
$array = file('example.txt');

10
Files
Closing a file Shortcuts
Each file pointer should be closed by the function Function file() reads the entire file with the
fclose(), if we finished working with the file. given name and returns its contents in the form of
an array.
$handle = fopen('example.txt', 'r');
//... One row of the array corresponds to one line of
//do something with file $handle text.
//...
fclose($handle); Often used for reading files with logs.
$array = file('example.txt');

Function does not require opening the file using


fopen and closing it using fclose, it does it
automatically.

11
Shortcuts

file_get_contents() – reads the entire file file_put_contents() – similarly, the function


with the given name and returns its contents. It lets lets you easily save the text to a file. The function
you easily read the contents of a file. overwrites the file by default!
$file = file_get_contents('people.txt'); We can pass built-in configuration constants as a
second argument so that the data will be
appended to the file.
file_put_contents($file, $txt);
file_put_contents($file, $txt,
FILE_APPEND | LOCK_EX);

12
Shortcuts

file_get_contents() – reads the entire file file_put_contents() – similarly, the function


with the given name and returns its contents. It lets lets you easily save the text to a file. The function
you easily read the contents of a file. overwrites the file by default!
$file = file_get_contents('people.txt'); We can pass built-in configuration constants as a
second argument so that the data will be
appended to the file.
file_put_contents($file, $txt);
file_put_contents($file, $txt,
FILE_APPEND | LOCK_EX);

Function does not require opening the file using


fopen and closing it using fclose, it does it
automatically.

13
Not just files

Some file handling functions can also be applied to Keep in mind that you may need to change the
URLs. These include: PHP configuration on the server to work with
fopen() URLs.
file_get_contents() $page=file_get_contents('http://xx.zz');
file() $handle=fopen("http://www.xx.zz/","r");
$handle = fopen(
file_exists() "ftp://user:[email protected]/a.txt", "w");
filesize()
Thanks to this, we can also easily retrieve data via
HTTP or FTP.

A better way to download data from websites is to use the curl library.

14
File operations

rename() – changes the file name,

unlink() – deletes the file,

filesize() – returns the file size in bytes,

filetype() – returns the resource type (file, dir, link, char, etc.),

fstat() – returns a table with information about the file (including size, time of creation,
modification, access).

15
Operations on directories

mkdir() – creates a directory,


rmdir() – deletes a directory.

is_*
is_dir() – checks if the argument is a directory,
is_file() – checks if the argument is a file,
is_link() – checks if the argument is a link,
is_readable() – checks if the file can be read,
is_writable() – checks if you can save to a file.

16
File upload

The HTTP protocol lets you transfer files only in the query type POST.

It is a very convenient way for users to submit files to our site.

It is typically used for small and medium files due to transfer restrictions.

17
Form

In order for the page to be able to select and <form action="upload.php" method="post"
upload a file, we use the tag <input> of the type enctype="multipart/form-data">
file. <input type="file"
name="fileToUpload"
In the form we choose the method POST and the id="fileToUpload">
coding type <input type="submit"
enctype="multipart/form-data". value="Upload Img"
name="submit">
</form>

18
$_FILES variable

On the server side, information about the files sent $_FILES['userfile']['name'] – the
in the request can be found in the superglobal original file name.
variable $_FILES. $_FILES['userfile']['type'] – the
mime type of the file, e.g. image/gif.
The key in the array is identical to the attribute $_FILES['userfile']['size'] – file
name of the input element type file, so in this size in bytes.
case: $_FILES['userfile']['tmp_name'] –
<input type="file" name="userfile"
temporary file name on the server, usually a
directory /tmp and random file name
id="fileToUpload">
$_FILES['userfile']['error'] – the
error code associated with the file.

19
$_FILES variable

After being received by the server, the file must be saved to the destination.

The www server stores the file in a temporary directory and if we do not transfer it,
it will be deleted after the request is completed.

For that purpose we use move_uploaded_file().

20
$_FILES variable

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.";
}
else {
echo "Possible file upload attack!";
}

21
$_FILES variable

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.";
}
else {
echo "Possible file upload attack!";
}

Function basename() returns the file name only from the path.

22
Uploading multiple files

We can send many files in one request:


<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />

23
Configuration variables

file_uploads – can you upload files,


The web server limits the size of accepted files.
We can control this limit using configuration upload_max_filesize – maximum
variables. accepted file size,
The variables are located in the file php.ini
max_file_uploads – maximum number of
files accepted,

post_max_size – maximum data size for


the request type POST.

24
Common problems

Value of upload_max_filesize or post_max_size is too low,

too small memory_limit,

too little time of the max_execution_time.

25
Exercises

Time to do exercises
Day 2
PHP files

26
Exceptions

27
Definition
Exception In other words
It is a control flow mechanism used in Exception – is a mechanism that handles an
microprocessors and modern programming exceptional situation in which further program
languages for handling exceptional events, in execution is either impossible or not
particular for handling errors, the occurrence recommended.
of which changes the proper course of
program execution. After reporting the exception, the work of the
program is interrupted and an attempt is
When an unexpected event occurs, an made to handle the exception.
exception is generated, which has to be
handled by saving the current state of the If the exception is not handled, the program
program and proceeding to the procedure for stops working and an unhandled exception
its operation. error is reported.

28
Exceptions in PHP
function inverse($x)
{
if (!$x) {
throw new Exception('Division by zero.');
} else {
return 1 / $x;
}
}
try {
$value = inverse(0);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
} finally {
echo 'First finally.';
}

29
Exceptions in PHP
function inverse($x)
{
if (!$x) {
throw new Exception('Division by zero.');
} else {
return 1 / $x;
}
}
try {
$value = inverse(0);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
} finally {
echo 'First finally.';
}

Value 0 (logically) is false, so if argument 0 is passed to the function, an exception will be thrown.

30
Exceptions in PHP
function inverse($x)
{
if (!$x) {
throw new Exception('Division by zero.');
} else {
return 1 / $x;
}
}
try {
$value = inverse(0);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
} finally {
echo 'First finally.';
}

This block of code will be checked if it throws an exception.

31
Exceptions in PHP
function inverse($x)
{
if (!$x) {
throw new Exception('Division by zero.');
} else {
return 1 / $x;
}
}
try {
$value = inverse(0);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
} finally {
echo 'First finally.';
}

This block of code will be called if an exception occurs.

32
Exceptions in PHP
function inverse($x)
{
if (!$x) {
throw new Exception('Division by zero.');
} else {
return 1 / $x;
}
}
try {
$value = inverse(0);
} catch (Exception $e) {
echo 'Caught exception: ' . $e->getMessage();
} finally {
echo 'First finally.';
}

This block of code will be called always.

33
Throwing an exception
Exception
In PHP exceptions are thrown.

When an exception is thrown, the program's work is interrupted.

The parameter of throw is an object which has to be of Exception class (built-in exception class)
or of a class inheriting from it.

In the class inheriting from the class Exception a parent class constructor always needs to be
called.

34
Throwing an exception

class MyException extends Exception {}


class AdvException extends Exception
{
public function __construct($message = null, $code = 0)
{
parent::__construct($message, $code);
}
}

35
Throwing an exception

class MyException extends Exception {}


class AdvException extends Exception
{
public function __construct($message = null, $code = 0)
{
parent::__construct($message, $code);
}
}

Calling the constructor of the parent class.

36
Throwing an exception

class InsufficientFundsException extends Exception


{
public function __construct($message = null, $code = 0)
{
parent::__construct($message, $code);
}
}

37
Throwing an exception

class InsufficientFundsException extends Exception


{
public function __construct($message = null, $code = 0)
{
parent::__construct($message, $code);
}
}

We define our own exception, the name will allow us to understand more easily what error has occurred
in our code.

38
Throwing an exception

function makeTransfer(float $balance, float $cash): void


{
if ($cash < $balance) {
throw new InsufficientFundsException("Can't transfer: " . $balance);
} elseif($balance < 50) {
throw new Exception("Low balance");
}
/* ... */
}

39
Throwing an exception

function makeTransfer(float $balance, float $cash): void


{
if ($cash < $balance) {
throw new InsufficientFundsException("Can't transfer: " . $balance);
} elseif($balance < 50) {
throw new Exception("Low balance");
}
/* ... */
}

We define a function that in the case of insufficient balance will throw the exception
InsufficientFundsException, and in the case of a low balance will throw the exception
Exception

40
Throwing an exception

function makeTransfer(float $balance, float $cash): void


{
if ($cash < $balance) {
throw new InsufficientFundsException("Can't transfer: " . $balance);
} elseif($balance < 50) {
throw new Exception("Low balance");
}
/* ... */
}

We throw the exception InsufficientFundsException

41
Throwing an exception

function makeTransfer(float $balance, float $cash): void


{
if ($cash < $balance) {
throw new InsufficientFundsException("Can't transfer: " . $balance);
} elseif($balance < 50) {
throw new Exception("Low balance");
}
/* ... */
}

We throw the exception Exception

42
Exception Class

class Exception
{
/* Properties */
protected string $message;
protected int $code;
protected string $file;
protected int $line;
}

43
Exception Class
class Exception
{
/* Methods */
public __construct([string $message = "" [, int $code = 0
[,Exception $previous = null]]])
final public string getMessage(void)
final public Exception getPrevious(void)
final public mixed getCode(void)
final public string getFile(void)
final public int getLine(void)
final public array getTrace(void)
final public string getTraceAsString(void)
public string __toString(void)
final private void __clone(void)
}

44
Handling the exception

To catch the thrown exception, we use the try {


block try...catch. throw new TestException();
In the block try there is a code for which we }
expect exceptions. catch (TestException $e) {
In the block catch there is an exception echo 'Caught TestException';
handling code. }
In one block try...catch more blocks can catch (Exception $e) {
occur catch which define different ways of echo 'Caught Exception';
handling various exceptions. }
To handle the exception we select the first
block we encounter catch which expects an
exception of a given type (a given class).

45
Handling the exception

To catch the thrown exception, we use the try {


block try...catch. throw new TestException();
In the block try there is a code for which we }
expect exceptions. catch (TestException $e) {
In the block catch there is an exception echo 'Caught TestException';
handling code. }
In one block try...catch more blocks can catch (Exception $e) {
occur catch which define different ways of echo 'Caught Exception';
handling various exceptions. }
To handle the exception we select the first Catches only exceptions from the class
block we encounter catch which expects an
exception of a given type (a given class). TestException and its derivatives.

46
Handling the exception

To catch the thrown exception, we use the try {


block try...catch. throw new TestException();
In the block try there is a code for which we }
expect exceptions. catch (TestException $e) {
In the block catch there is an exception echo 'Caught TestException';
handling code. }
In one block try...catch more blocks can catch (Exception $e) {
occur catch which define different ways of echo 'Caught Exception';
handling various exceptions. }
To handle the exception we select the first Catches all the exceptions.
block we encounter catch which expects an
exception of a given type (a given class).

47
Throwing an exception
class InsufficientFundsException extends Exception
{
public function __construct($message = null, $code = 0)
{
parent::__construct($message, $code);
}
}

48
Throwing an exception
class InsufficientFundsException extends Exception
{
public function __construct($message = null, $code = 0)
{
parent::__construct($message, $code);
}
}

We define our own exception, the name will let us understand more easily what kind of error occured in
our code

49
Throwing an exception
function makeTransfer(float $balance, float $cash): void
{
if ($cash < $balance) {
throw new InsufficientFundsException("Can't transfer: " . $balance);
} elseif ($balance < 50) {
throw new Exception("Low balance");
}
/* ... */
}

50
Throwing an exception
function makeTransfer(float $balance, float $cash): void
{
if ($cash < $balance) {
throw new InsufficientFundsException("Can't transfer: " . $balance);
} elseif ($balance < 50) {
throw new Exception("Low balance");
}
/* ... */
}

We define a function which, in the case of insufficient balances, will throw the exception
InsufficientFundsException, and in the case of a low balance will throw the exception
Exception

51
Throwing an exception
$balanceEUR = 10;
$cash = 5;
try {
makeTransfer($balanceEUR, $cash);
} catch (InsufficientFundsException $e){
echo 'Error: '.$e->getMessage();
} catch (Exception $e) {
echo 'Error: '.$e->getMessage();
}

52
Throwing an exception
$balanceEUR = 10;
$cash = 5;
try {
makeTransfer($balanceEUR, $cash);
} catch (InsufficientFundsException $e){
echo 'Error: '.$e->getMessage();
} catch (Exception $e) {
echo 'Error: '.$e->getMessage();
}

This call will be checked in the block try

53
Throwing an exception
$balanceEUR = 10;
$cash = 5;
try {
makeTransfer($balanceEUR, $cash);
} catch (InsufficientFundsException $e){
echo 'Error: '.$e->getMessage();
} catch (Exception $e) {
echo 'Error: '.$e->getMessage();
}

This fragment will be called when an exception occurs, here the method getMessage() will return the
exception message passed when it was thrown

54
Throwing an exception
$balanceEUR = 10;
$cash = 5;
try {
makeTransfer($balanceEUR, $cash);
} catch (InsufficientFundsException $e){
echo 'Error: '.$e->getMessage();
} catch (Exception $e) {
echo 'Error: '.$e->getMessage();
}

This fragment will be called when an exception occurs, as long as the earlier catch did not catch the
exception

55
Throwing an exception
$balanceEUR = 10;
$cash = 5;
try {
makeTransfer($balanceEUR, $cash);
} catch (InsufficientFundsException $e){
echo 'Error: '.$e->getMessage();
} catch (Exception $e) {
echo 'Error: '.$e->getMessage();
}

We can therefore handle various types of exceptions differently.


Don't forget that only Exception is capable of catching other types of exceptions.

56
Catching multiple exceptions at once in PHP 7.1

Starting with the 7.1 PHP version we can catch several exceptions at once in one instruction catch.

Example
try {

} catch (InsufficientFundsException | TransferException $e) {

}

57
Nesting

Blocks try...catch can be nested in one try {


another. try {
The given block try...catch doesn't have throw new MyException('foo!');
to catch all the exceptions. } catch (MyException $e) {
It can be done by one of the parent blocks. /* rethrow it */
throw $e;
In the block catch a caught exception can be }
rethrown or a completely new exception can
be thrown. } catch (Exception $e) {
var_dump($e->getMessage());
In such a case, the exception will be handled }
by the parent blocks catch.

58
finally

It could happen that in the block try before try {


throwing an exception, some resources will be inverse(0);
allocated that need to be released even in the
} catch (Exception $e) {
case an exception occurs.
echo 'Caught exception';
Block finally (starting with the PHP 5.5) is } finally {
always performed. Regardless whether an
exception has been reported or not. echo 'Finally.';
}
It enables the release of certain resources
(e.g. closing the connection to the database).

59
Exercises

Time to do exercises
Day 2
Exceptions

60
Filters

61
Filters

Filters allow validation of data processed by the script.

The data received in the query does not have to correspond to our assumptions. For example, an
email address may contain incorrect characters or be in a wrong format.

You can check the correctness of an email address using regular expressions, the pattern in this
situation will be very long and it is better to use filters for this purpose.

62
Filters - checking whether a variable exists

It is possible to check the if a variable of a given


type exists using the function: filter_has_var(INPUT_GET, 'name');
// true
filter_has_var($type, $var_name)
Checks if the variable named $varName of filter_has_var(INPUT_SERVER,
the type $type exists. 'nonExisting');
Possible types of variables: // false
INPUT_GET,
INPUT_POST,
INPUT_COOKIE,
INPUT_SERVER,
INPUT_ENV.
Returns true or false depending on
whether the variable exists.

63
Filters - filtering a variable

Filtering a variable is possible using the function: filter_var('www.google.com',


FILTER_VALIDATE_URL); // false
filter_var($var, $filter_type)

Filters the variable named $var using the filter_var('[email protected]',
filter $filterType. FILTER_VALIDATE_EMAIL);
Returns the filtered value or false in case of // [email protected]
failure.
The list of filters can be found at this address: filter_var('192.168.1.260',
http://php.net/manual/en/filter.filters.validate.p FILTER_VALIDATE_IP); // false
hp

64
Filters - filtering a variable

Filtering a variable is possible using the function: filter_var('www.google.com',


FILTER_VALIDATE_URL); // false
filter_var($var, $filter_type)

Filters the variable named $var using the filter_var('[email protected]',
filter $filterType. FILTER_VALIDATE_EMAIL);
Returns the filtered value or false in case of // [email protected]
failure.
The list of filters can be found at this address: filter_var('192.168.1.260',
http://php.net/manual/en/filter.filters.validate.p FILTER_VALIDATE_IP); // false
hp
Address doesn't contain http://

65
Filters - filtering a variable

Filtering a variable is possible using the function: filter_var('www.google.com',


FILTER_VALIDATE_URL); // false
filter_var($var, $filter_type)

Filters the variable named $var using the filter_var('[email protected]',
filter $filterType. FILTER_VALIDATE_EMAIL);
Returns the filtered value or false in case of // [email protected]
failure.
The list of filters can be found at this address: filter_var('192.168.1.260',
http://php.net/manual/en/filter.filters.validate.p FILTER_VALIDATE_IP); // false
hp
Correct email address

66
Filters - filtering a variable

Filtering a variable is possible using the function: filter_var('www.google.com',


FILTER_VALIDATE_URL); // false
filter_var($var, $filter_type)

Filters the variable named $var using the filter_var('[email protected]',
filter $filterType. FILTER_VALIDATE_EMAIL);
Returns the filtered value or false in case of // [email protected]
failure.
The list of filters can be found at this address: filter_var('192.168.1.260',
http://php.net/manual/en/filter.filters.validate.p FILTER_VALIDATE_IP); // false
hp
The last block of address is incorrect, it is not
within the range 0-255

67
Filters - filtering of an external variable

Filtering of an external variable is possible using


the function: filter_input(INPUT_GET, 'url',
FILTER_VALIDATE_URL);
filter_input($type, $varName,
$filterType) filter_input(INPUT_POST, 'email',
Filters the variable of the type $type named FILTER_VALIDATE_EMAIL);
$varName, using the filter $filterType.
Returns the filtered value or false in case of filter_input(INPUT_POST, 'ip',
failure, or null if the variable doesn't exist. FILTER_VALIDATE_IP);
The list of filters can be found at this address:
http://php.net/manual/en/filter.filters.validate.p
hp

68
Filters - filtering of an external variable

Filtering of an external variable is possible using


the function: filter_input(INPUT_GET, 'url',
FILTER_VALIDATE_URL);
filter_input($type, $varName,
$filterType) filter_input(INPUT_POST, 'email',
Filters the variable of the type $type named FILTER_VALIDATE_EMAIL);
$varName, using the filter $filterType.
Returns the filtered value or false in case of filter_input(INPUT_POST, 'ip',
failure, or null if the variable doesn't exist. FILTER_VALIDATE_IP);
The list of filters can be found at this address: Checks if $_GET['url'] is a correct url address
http://php.net/manual/en/filter.filters.validate.p
hp

69
Filters - sanitizing

All filtering functions can also sanitize the passed


variable from unwanted characters, for this filter_input(INPUT_POST, 'email',
purpose we use sanitizing filters. FILTER_SANITIZE_EMAIL);

The return value is a variable, after deleting filter_input(INPUT_POST, 'ip',
characters that the given filter does not represent. FILTER_SANITIZE_NUMBER_INT);
The list of sanitizing filters can be found here:
http://php.net/manual/en/filter.filters.sanitize.php

70
Filters - sanitizing

All filtering functions can also sanitize the passed


variable from unwanted characters, for this filter_input(INPUT_POST, 'email',
purpose we use sanitizing filters. FILTER_SANITIZE_EMAIL);

The return value is a variable, after deleting filter_input(INPUT_POST, 'ip',
characters that the given filter does not represent. FILTER_SANITIZE_NUMBER_INT);
The list of sanitizing filters can be found here: Deletes from $_POST['email'] all the
http://php.net/manual/en/filter.filters.sanitize.php characters which an email cannot contain

71
Filters - sanitizing

All filtering functions can also sanitize the passed


variable from unwanted characters, for this filter_input(INPUT_POST, 'email',
purpose we use sanitizing filters. FILTER_SANITIZE_EMAIL);

The return value is a variable, after deleting filter_input(INPUT_POST, 'ip',
characters that the given filter does not represent. FILTER_SANITIZE_NUMBER_INT);
The list of sanitizing filters can be found here: Deletes from $_POST['ip'] all the characters
http://php.net/manual/en/filter.filters.sanitize.php which are not integers and a + and –

72
Selected filter types

Validation Sanitizing
FILTER_VALIDATE_BOOLEAN FILTER_SANITIZE_EMAIL
FILTER_VALIDATE_EMAIL FILTER_SANITIZE_ENCODED
FILTER_VALIDATE_INT FILTER_SANITIZE_STRING
FILTER_VALIDATE_IP FILTER_SANITIZE_URL
FILTER_VALIDATE_URL

73
Exercises

Time to do exercises
Day 2
Filters

74
PHP Namespaces

75
PHP Namespaces
What are namespaces?
Namespaces let you create a more transparent and mainly encapsulated code.
They're useful in working with large projects containing two or more classes with the same name.
Defining the namespace
Enter as first the space name after the keyword namespace.
Namespaces should have their names in accordance with the directory structure in which files with
classes are located – it is not required, but very beneficial, as you're about to see on the following
slides.
Examples:
namespace Foo;
namespace Foo\Bar;
namespace Foo\Bar\Baz;

76
PHP Namespaces
File: class.userAccount.php File: class.userForum.php
namespace User\Account; namespace User\Forum;
class Register class Register
{ {
public function getFormData(): bool public function getFormData(): bool
{ {
return true; return true;
} }
} }
$uReg = new Register(); $uRegForum = new User\Forum\Register();
$uRegAccount =
new User\Account\Register();

77
PHP Namespaces
File: class.userAccount.php File: class.userForum.php
namespace User\Account; namespace User\Forum;
class Register class Register
{ {
public function getFormData(): bool public function getFormData(): bool
{ {
return true; return true;
} }
} }
$uReg = new Register(); $uRegForum = new User\Forum\Register();
$uRegAccount =
new User\Account\Register();

Fatal error: Class 'Register' not


found!

78
PHP Namespaces
File: class.userAccount.php File: class.userForum.php
namespace User\Account; namespace User\Forum;
class Register class Register
{ {
public function getFormData(): bool public function getFormData(): bool
{ {
return true; return true;
} }
} }
$uReg = new Register(); $uRegForum = new User\Forum\Register();
$uRegAccount =
new User\Account\Register();

Now, our class is: User\Account\Register


and no Register any more.

79
PHP Namespaces
Let's try to create objects of our classes
include('class.userAccount.php');
include('class.userForum.php');
$uRegAccount = new User\Account\Register();
$uRegForum = new User\Forum\Register();

80
PHP Namespaces
Let's try to create objects of our classes
include('class.userAccount.php');
include('class.userForum.php');
$uRegAccount = new User\Account\Register();
$uRegForum = new User\Forum\Register();

You created class objects with the same name thanks to namespaces. If you hadn't used then, you would
have seen the following error:
Fatal error: Cannot redeclare class Register

81
PHP Namespaces

It may happen that your namespace will be very long, which may cause the code to be unreadable.
plik class.userAccountDhl.php
namespace User\Account\Shop\Shipping\Dhl;
class SendParcel
{
public function prepareParcel(): bool
{
return true;
}
}
$dhl = new User\Account\Shop\Shipping\Dhl\SendParcel();

82
PHP Namespaces

It may happen that your namespace will be very long, which may cause the code to be unreadable.
plik class.userAccountDhl.php
namespace User\Account\Shop\Shipping\Dhl;
class SendParcel
{
public function prepareParcel(): bool
{
return true;
}
}
$dhl = new User\Account\Shop\Shipping\Dhl\SendParcel();

Our code becomes unreadable. What if you have a dozen or more classes?

83
PHP Namespaces

The use directive lets you define what namespace you are currently using.
use User\Account\Shop\Shipping\Dhl;
include('class.userAccountDhl.php');
$dhl = new SendParcel();

84
PHP Namespaces

The use directive lets you define what namespace you are currently using.
use User\Account\Shop\Shipping\Dhl;
include('class.userAccountDhl.php');
$dhl = new SendParcel();

Using the use directive lets PHP know that you mean the class SendParcel which has the namespace
User\Account\Shop\Shipping\Dhl.

85
PHP Namespaces

If you have two classes with the same name and By connecting namespaces, directives use and
want to use the use directive – it is possible, but aliases, you can create a clear code without having
you have to use name aliases. to worry it will collide with other classes having the
same names.
use User\Account as UA;
use User\Forum as UF;
include('class.userAccount.php');
include('class.userForum.php');
$uRegAccount = new UA\Register();
$uRegForum = new UF\Register();

86
PHP Namespaces

If you have two classes with the same name and By connecting namespaces, directives use and
want to use the use directive – it is possible, but aliases, you can create a clear code without having
you have to use name aliases. to worry it will collide with other classes having the
same names.
use User\Account as UA;
use User\Forum as UF;
include('class.userAccount.php');
include('class.userForum.php');
$uRegAccount = new UA\Register();
$uRegForum = new UF\Register();

Your space has the alias: UA.

87
PHP Namespaces

If you have two classes with the same name and By connecting namespaces, directives use and
want to use the use directive – it is possible, but aliases, you can create a clear code without having
you have to use name aliases. to worry it will collide with other classes having the
same names.
use User\Account as UA;
use User\Forum as UF;
include('class.userAccount.php');
include('class.userForum.php');
$uRegAccount = new UA\Register();
$uRegForum = new UF\Register();

We use both namespaces and aliases to exclude


an error in the same class name.

88
PHP Namespaces

Now, we can use the function myClassLoader.


Why is it important that the namespace names are
function myClassLoader($class)
consistent with the structure?
{
inc $c = str_replace('\\','/', $class);
|__ User require_once(__DIR__."/inc/$c.php");
|____ Account }
|______ Register.php spl_register_autoloader("myClassLoader");
$uRegAccount =
|____ Forum
new User\Account\Register();
|______ Register.php
Your space is, for example User\Account and a
file with a class from that space is located in the
directory inc/User/Account/Register.php

89
PHP Namespaces

Now, we can use the function myClassLoader.


Why is it important that the namespace names are
function myClassLoader($class)
consistent with the structure?
{
inc $c = str_replace('\\','/', $class);
|__ User require_once(__DIR__."/inc/$c.php");
|____ Account }
|______ Register.php spl_register_autoloader("myClassLoader");
$uRegAccount =
|____ Forum
new User\Account\Register();
|______ Register.php
By keeping the names of spaces consistent with
Your space is, for example User\Account and a
the directory structure the function
file with a class from that space is located in the
myClassLoader knows, it is to load the file
directory inc/User/Account/Register.php
Register.php from the directories
User/Account.

90
PHP Namespaces

Starting with version 7.0 PHP lets you shorten the syntax when loading multiple classes with similar
namespace.

// PHP7.0 group use syntax:


use FooLibrary\Bar\Baz\{
ClassA, ClassB, ClassC as Fizbo
};

// PHP5 syntax
use FooLibrary\Bar\Baz\ClassA;
use FooLibrary\Bar\Baz\ClassB;
use FooLibrary\Bar\Baz\ClassC as Fizbo;

91
Exercises

Time to do exercises
Day 2
Namespace

92
Mail

93
Sending a mail message

telnet: >
telnet mx1.example.com smtp
telnet: Connected to mx1.example.com.
server: 220 mx1.example.com ESMTP server ready Tue, 20 Jan 2004 22:33:36 +0200
client: HELO client.example.com
server: 250 mx1.example.com
client: MAIL from: <[email protected]>
server: 250 Sender <[email protected]> Ok
client: RCPT to: <[email protected]>
server: 250 Recipient <[email protected]> Ok
client: DATA
server: 354 Ok Send data ending with <CRLF>. <CRLF>
client: From: [email protected]
client: To: [email protected]
client: Subject: Test message
client:
client: This is a test message.
client: .
server: 250 Message received: [email protected]
client: QUIT
server: 221 mx1.example.com ESMTP server closing connection

94
The mail function

bool mail ( string $to , string $subject , string $message [, string


$additional_headers] )

This function sends an e-mail addressed to $to on the subject of $subject and the text: $message

$additional_headers – additional headers, such as From, Bcc, Cc, Reply-To, X-Mailer.

95
The mail function
Example
$to = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers ='From: [email protected]'. "\r\n" .
'Reply-To: [email protected]' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);

96
Example

$message = '<html><body>Hello world</body></html>';


$to = '[email protected]' . ',' . '[email protected]';
$subject = 'Example';
// To send HTML mail, the Content-type header must be set
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);

97
Header

From – field defining the sender,


e.g.: From: John Smith [email protected]
CC – recipient of the copy of the message,
e.g.: Cc: Tom Brown [email protected]
Bcc – recipient of a hidden copy of the message
Reply-To – address to repply to.
Content-type – content type,
e.g.: Content-type: text/html; charset=utf-8
X-mailer – identifies the program sending the message.

98
PHPMailer
Example
PHPMailer is a library written in PHP which lets $mail = new PHPMailer;
you send a mail in a simple way while offering $mail->setFrom('[email protected]', 'Mailer');
many advanced options. $mail->addAddress('[email protected]', 'Joe');
$mail->addReplyTo('[email protected]', 'Doe');
Sending text and HTML e-mails.
$mail->addAttachment('/path/file.zip');
Sending via SMTP. $mail->isHTML(true);
Supports UTF-8 encoding. $mail->Subject = 'Here is the subject';
Supports signing DKIM and S/MIME. $mail->Body='<h1>HTML</h1><b>text</b>';
$mail->AltBody = 'Plain text,not HTML';
if (!$mail->send()) {
Installing PHPMailer using Composer: echo 'Message could not be sent.';
composer require phpmailer/phpmailer echo 'Mail Error: '.$mail->ErrorInfo;
} else {
https://github.com/PHPMailer/PHPMailer echo 'Message has been sent';
}

99
Exercises

Time to do exercises
Day 2
Mails

100
XML

101
XML
Decoding <?xml version="1.0" encoding="UTF-8"?>
<book
Two basic methods of reading XML data:
category="comic-book characters">
In the form of a tree (SimpleXML) <!-- comment -->
Simple, easy to implement. <person character="hero">
<name>Clark</name>
Natural.
<surname>Kent</surname>
Requires a lot of memory and resources. <phone>123-456-789</phone>
</person>
Via events
<person character="villain">
Fast and efficient. <name>Lex</name>
Complicated and difficult to maintain. <surname>Luthor</surname>
<phone/>
</person>
</book>

102
SimpleXML

simplexml_load_file() – loads the SimpleXMLElement requires that the XML


structure from the file, document tree be stored in memory.
simplexml_load_string() – loads the
structure from the string, e.g. a variable
containing XML. If the XML code contains more such elements,
then these elements will be placed in the table (in
Objects SimpleXML create a tree, whose our example these are persons) which you will see
structure corresponds to the structure of the XML on the next slide.
code. Let's assume that the file from the previous slide is
Each XML element corresponds to one object called book.xml.
SimpleXML, and the attributes are returned in the
form of an associative array.

103
Example
$book=simplexml_load_file('book.xml'); [person] => Array (
$book->getName(); [0] => SimpleXMLElement Object (
$book->person[0]['character']; [@attributes] => Array (
$book->person[1]->surname; [character] => hero )
[name] => Clark
SimpleXMLElement Object ( [surname] => Kent
[@attributes] => Array ( [phone] => 123-456-789 )
[category] => [1] => SimpleXMLElement Object (
'comic-book characters' ) [@attributes] => Array (
[comment] => [character] => villain )
SimpleXMLElement Object() [name] => Lex
[surname] => Luthor
[phone] =>
SimpleXMLElement Object())
)
)

104
Example
$book=simplexml_load_file('book.xml'); [person] => Array (
$book->getName(); [0] => SimpleXMLElement Object (
$book->person[0]['character']; [@attributes] => Array (
$book->person[1]->surname; [character] => hero )
[name] => Clark
SimpleXMLElement Object ( [surname] => Kent
[@attributes] => Array ( [phone] => 123-456-789 )
[category] => [1] => SimpleXMLElement Object (
'comic-book characters' ) [@attributes] => Array (
[comment] => [character] => villain )
SimpleXMLElement Object() [name] => Lex
[surname] => Luthor
book [phone] =>
SimpleXMLElement Object())
)
)

105
Example
$book=simplexml_load_file('book.xml'); [person] => Array (
$book->getName(); [0] => SimpleXMLElement Object (
$book->person[0]['character']; [@attributes] => Array (
$book->person[1]->surname; [character] => hero )
[name] => Clark
SimpleXMLElement Object ( [surname] => Kent
[@attributes] => Array ( [phone] => 123-456-789 )
[category] => [1] => SimpleXMLElement Object (
'comic-book characters' ) [@attributes] => Array (
[comment] => [character] => villain )
SimpleXMLElement Object() [name] => Lex
[surname] => Luthor
hero [phone] =>
SimpleXMLElement Object())
)
)

106
Example
$book=simplexml_load_file('book.xml'); [person] => Array (
$book->getName(); [0] => SimpleXMLElement Object (
$book->person[0]['character']; [@attributes] => Array (
$book->person[1]->surname; [character] => hero )
[name] => Clark
SimpleXMLElement Object ( [surname] => Kent
[@attributes] => Array ( [phone] => 123-456-789 )
[category] => [1] => SimpleXMLElement Object (
'comic-book characters' ) [@attributes] => Array (
[comment] => [character] => villain )
SimpleXMLElement Object() [name] => Lex
[surname] => Luthor
Luthor [phone] =>
SimpleXMLElement Object())
)
)

107
SimpleXML with xpath()

The function xpath() lets you search the XML tree using queries xpath().

$book = simplexml_load_file('book.xml');
$people = $book->xpath('person');
foreach ($people as $person) {
echo $person->name . ' ' . $person->surname;
};

108
SimpleXML with xpath()
EXPRESSION MEANING
person Finds all the nodes for person.
person/name Finds all the nodes for name which children of the person node.
person/name[1] Selects the first name node which is a child of the person node.
person/* Selects all of the children of the person node.
person[@character] Selects all the person nodes with the character attribute.
person/name[text()] Selects text of the node name.

109
XMLReader

Reads the XML document node after node. $xml=file_get_contents('book.xml');


It is not possible to view the entire document, $book = new XMLReader();
except for the current node. $book->xml($xml);
Since it does not load the entire file into while ($book->read()) {
memory, it allows you to read even very large echo($book->name);
files. if ($book->hasValue) {
echo($book->value);
}
if ($book->name == 'person') {
echo($book->
getAttribute('character'));
}
}

110
XMLReader
PROPERTY MEANING
attributeCount Number of attributes in the node.
baseURI The URI addres of the node.
depth The depth of the node in the XML document.
hasAttributes Does the element have attributes?
hasValue Does the element have a text value?

111
XMLReader
PROPERTY MEANING
isDefault Is the attribute default?
isEmptyElement Is the HTML tag empty?
localName Local name of the node.
name Fully qualified name of the node.
namespaceURI The URI address of the node namespace from the set.
nodeType Code representing the node type.
prefix Node's namespace prefix.
value The text value of the node.
xmlLang Range xml:lang, in which the node is located.

112
XMLReader

METHOD MEANING
XMLReader::open() Get the URI that contains the XML document that you want to
analyze.
XMLReader::close() Close the document.
XMLReader::read() Go to the next node.
XMLReader::next() Go to the next node, skip subtrees.
XMLReader::getAttribute() Get the value of the attribute.
XMLReader::expand() Return a copy of the current node as a DOM document.
XMLReader::readString() Gets the value of the current node as a string.

113
Traits

114
Traits

What are Traits?


Traits let you to repeatedly use the same code (methods) in different classes, without the necessity for
inheritance.
Trait is similar to a class. It contains definitions of methods and attributes.
You can't create an object from a Trait, as in the case of abstract class.

Traits are sometimes referred to as interfaces with implementation.

115
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();

116
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();

We define Trait by entering a keyword trait and


its name.

117
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();

Then we add methods to it for later use, and we


can add a lot of them.

118
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();

To add a trait to our class we use the keyword use


just like in namespace.

119
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();

By adding a trait, our class gets access to the


method hello() and we can call it on the object
of our class.

120
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi, SayBye;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();
$m->bye();
trait SayBye
{
public function bye(): void
{
echo 'Goodbye my friend';
}
}

121
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi, SayBye;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();
$m->bye();
trait SayBye
{ You can add more traits to your class.
public function bye(): void
{
echo 'Goodbye my friend';
}
}

122
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi, SayBye;
{ }
echo 'Hello my friend';
} $m = new Mark();
} $m->hello();
$m->bye();
trait SayBye
{ Then you will be able to use the methods of each
public function bye(): void one of them.
{
echo 'Goodbye my friend';
}
}

123
Traits
trait SayHi trait Greetings
{ {
public function hello(): void use SayHi;
{
echo 'Hello my friend'; public function bye(): void
} {
} echo 'Goodbye my friend';
}
}

124
Traits
trait SayHi trait Greetings
{ {
public function hello(): void use SayHi;
{
echo 'Hello my friend'; public function bye(): void
} {
} echo 'Goodbye my friend';
}
}

You can create a new trait that "inherits" from


another one, then it will have methods from the
trait sayHi as well as its own.

125
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ public $name;
echo 'Hello my name is ' . }
$this->name;
} $m = new Mark();
} $m->name = 'Mark';
$m->hello();
//Hello my name is Mark

126
Traits
trait SayHi class Mark
{ {
public function hello(): void use SayHi;
{ public $name;
echo 'Hello my name is ' . }
$this->name;
} $m = new Mark();
} $m->name = 'Mark';
$m->hello();
//Hello my name is Mark

The method defined by the trait can use $this,


then it will function as every other method in the
given class.

127
Exercises

Time to do exercises
Day 2
XML

128

You might also like