diwe - advanced php concepts

81
Diploma in Web Engineering Module VII: Advanced PHP Concepts Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.

Upload: rasan-samarasinghe

Post on 19-Feb-2017

35 views

Category:

Engineering


1 download

TRANSCRIPT

Page 1: DIWE - Advanced PHP Concepts

Diploma in Web Engineering

Module VII: Advanced PHP Concepts

Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.

Page 2: DIWE - Advanced PHP Concepts

Contents1. Arrays2. Indexed Arrays3. Associative Arrays4. Multidimensional arrays5. Array Functions6. PHP Objects and Classes7. Creating an Object8. Properties of Objects9. Object Methods10. Constructors11. Inheritance12. Method overriding13. PHP Strings14. printf() Function15. String Functions16. PHP Date/Time Functions17. time() Function18. getdate() Function19. date() Function

20. mktime() function21. checkdate() function22. PHP Form Handling23. Collecting form data with PHP24. GET vs POST25. Data validation against malicious code26. Required fields validation 27. Validating an E-mail address28. PHP mail() Function29. Using header() function to redirect user30. File Upload31. Processing the uploaded file32. Check if File Already Exists33. Limit File Size34. Limit File Type35. Check if image file is an actual image36. Uploading File37. Cookies38. Sessions

Page 3: DIWE - Advanced PHP Concepts

Arrays

10 30 20 50 15 35

0 1 2 3 4 5

Size = 6

Element Index No

An array can hold many values under a single name. you can access the values by

referring an index.

A single dimensional array

Page 4: DIWE - Advanced PHP Concepts

Arrays

In PHP, there are three types of arrays

• Indexed arrays• Associative arrays• Multidimensional arrays

Page 5: DIWE - Advanced PHP Concepts

Indexed Arrays

The index can be assigned automatically starts from 0

$fruits = array(“apple”, “mango”, “grapes”);

or the index can be assigned manually

$fruits[0] = “apple”;$fruits[1] = “mango”;$fruits[2] = “grapes”;

Page 6: DIWE - Advanced PHP Concepts

Loop Through an Indexed Array

$fruits = array(“apple”, “mango”, “grapes”);

$length = count($fruits);

for($i = 0; $i <= $length-1; $i++) { echo $fruits[$i]; echo "<br>";}

Page 7: DIWE - Advanced PHP Concepts

Associative Arrays

Associative arrays use named keys that you assign to them

$age = array(“Roshan”=>23, “Nuwan”=>24, “Kamal”=>20);

Or

$age = array();$age[“Roshan”] = 23;$age[“Nuwan”] = 24;$age[“Kamal”] = 20;

Page 8: DIWE - Advanced PHP Concepts

Loop Through an Associative Array

$age = array(“Roshan”=>23, “Nuwan”=>24, “Kamal”=>20);

foreach($age as $x=>$x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>";}

Page 9: DIWE - Advanced PHP Concepts

Multidimensional arrays

• A multidimensional array is an array containing one or more arrays.

• A two-dimensional array is an array of arrays

• A three-dimensional array is an array of arrays of arrays

Page 10: DIWE - Advanced PHP Concepts

Two dimensional Arrays

Name Age CityRoshan 23 ColomboNuwan 24 KandyKamal 20 GalleRuwan 21 Matara

Two dimensional array is forming a grid of data.

Page 11: DIWE - Advanced PHP Concepts

Creating a Two dimensional Array

$students = array ( array(“Roshan”, 23, “Colombo”), array(“Nuwan”, 24, “Kandy”), array(“Kamal”, 20, “Galle”), array(“Ruwan”, 21, “Matara”) );

Page 12: DIWE - Advanced PHP Concepts

Accessing a 2D Array Elements

Syntax:

Array name[row index][column index];

Ex:

$age = $students[ 0 ][ 1 ];

Page 13: DIWE - Advanced PHP Concepts

Array Functions

Function Description Example

count() Counts the number of elements in the array

$n = count($ArrayName)

sizeof() Counts the number of elements in the array

$n = sizeof($ArrayName)

each() Return the current element key and value, and move the internal pointer forward

each($ArrayName)

reset() Rewinds the pointer to the beginning of the array

reset($ArrayName)

list() Assign variables as if they were an array

list($a, $b, $c) = $ArrayName

array_push() Adds one or more elements to the end of the array

array_push($ArrayName, “element1”, “element2”, “element3”)

array_pop() Removes and returns the last element of an array

$last_element = array_pop($ArrayName)

Page 14: DIWE - Advanced PHP Concepts

Array Functions

Function Description Example

array_unshift() Adds one or more elements to the beginning of an array

array_unshift($ArrayName, “element1”, “element2”, “element3”)

array_shift() Removes and returns the first element of an array

$first_element = array_shift($ArrayName)

array_merge() Combines two or more arrays $NewArray = array_merge($array1, $array2)

array_keys() Returns an array containing all the keys of an array

$KeysArray = array_keys($ArrayName)

array_values() Returns an array containing all the values of an array

$ValuesArray = array_values($ArrayName)

shuffle() Randomize the elements of an array

shuffle($ArrayName)

Page 15: DIWE - Advanced PHP Concepts

PHP Objects and Classes

• An object is a theoretical box of thing consists from properties and functions.

• An object can be constructed by using a template structure called Class.

Page 16: DIWE - Advanced PHP Concepts

Creating an Object

class Class_name {

// code will go here

}

$object_name = new Class_name();

Page 17: DIWE - Advanced PHP Concepts

Properties of Objects

Variables declared within a class are called properties

class Car {var $color = “Red”;var $model = “Toyota”;var $VID = “GV - 5432”;}

Page 18: DIWE - Advanced PHP Concepts

Accessing object properties

$MyCar = new Car();

echo “Car color” . $MyCar -> color . “<br/>”;echo “Car model” . $MyCar -> model . “<br/>”;echo “Car VID” . $MyCar -> VID . “<br/>”;

Page 19: DIWE - Advanced PHP Concepts

Changing object properties

$MyCar = new Car();

$MyCar -> color = “White”;$MyCar -> model = “Honda”;$MyCar -> VID = “GC 4565”;

Page 20: DIWE - Advanced PHP Concepts

Object Methods

A method is a group of statements performing a specific task.

class Car {var $color = “Red”;var $model = “Toyota”;var $VID = “GV - 5432”;

function start() {echo “Car started”;}}

Page 21: DIWE - Advanced PHP Concepts

Object Methods

A call to an object function executes statements of the function.

$MyCar = new Car();

$MyCar -> start();

Page 22: DIWE - Advanced PHP Concepts

Accessing object properties within a method

class Car {var $color;

function setColor($color) {$this -> color = $color;}

function start() {echo $this -> color . “ color car started”;}}

Page 23: DIWE - Advanced PHP Concepts

ConstructorsA constructor is a function within a class given the same name as the class.

It invokes automatically when new instance of the class is created.

class Student {var $name;

function Student($name) {$this -> name = $name;}}

$st = new Student(“Roshan”);

Page 24: DIWE - Advanced PHP Concepts

Inheritance

In inheritance, one class inherits the functionality from it’s parent class.

class super_class {// code goes here}

class sub_class extends super_class {// code goes here}

Page 25: DIWE - Advanced PHP Concepts

Method overriding

class Person {var $name;function sayHello(){echo “My name is “ . $this -> name;}}

class Customer extends Person {function sayHello(){echo “I will not tell you my name”;}}

Page 26: DIWE - Advanced PHP Concepts

PHP Strings

A string is a sequence of characters, like:

"Hello world!"

‘Even single quotes are works fine but $variable values and special characters like \n \t are not working here’

Page 27: DIWE - Advanced PHP Concepts

printf() Function

The printf() function outputs a formatted string and returns the length of the outputted string.

$number = 20;$str = “Sri Lanka”;printf(“There are %u million people live in %s.”, $number, $str);

Page 28: DIWE - Advanced PHP Concepts

Type specifiers in printf()Specifier Description

%b Binary number

%c The character according to the ASCII value

%d Signed decimal number (negative, zero or positive)

%e Scientific notation using a lowercase (e.g. 1.2e+2)

%E Scientific notation using a uppercase (e.g. 1.2E+2)

%u Unsigned decimal number (equal to or greater than zero)

%f Floating-point number

%o Octal number

%s String

%x Hexadecimal number (lowercase letters)

%X Hexadecimal number (uppercase letters)

[0-9] Specifies the minimum width held of to the variable value. Example: %10s

' Specifies what to use as padding. Example: %'x20s

.[0-9] Specifies the number of decimal digits or maximum string length. Example: %.2d

Page 29: DIWE - Advanced PHP Concepts

String FunctionsFunction Description

sprintf() Writes a formatted string to a variable and returns it

strlen() Returns the length of a string

strstr() Find the first occurrence of a string, and return the rest of the string

strpos() Returns the position of the first occurrence of a string inside another string

substr() Returns a part of a string

strtok() Splits a string into smaller strings

trim() Removes whitespace or other characters from both sides of a string

ltrim() Removes whitespace or other characters from the left side of a string

rtrim() Removes whitespace or other characters from the right side of a string

strip_tags() Strips HTML and PHP tags from a string

substr_replace() Replaces a part of a string with another string

str_replace() Replaces all instances of a string with another string

strtoupper() Converts a string to uppercase letters

strtolower() Converts a string to lowercase letters

ucwords() Converts the first character of each word in a string to uppercase

ucfirst() Converts the first character of a string to uppercase

wordwrap() Wraps a string to a given number of characters

nl2br() Inserts HTML line breaks in front of each newline in a string

explode() Breaks a string into an array

Page 30: DIWE - Advanced PHP Concepts

PHP Date/Time Functions

• The date/time functions allow you to get the date and time from the server where your PHP script runs.

• You can use the date/time functions to format the date and time in several ways.

Page 31: DIWE - Advanced PHP Concepts

time() Function

Returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

$t=time();echo $t . "<br/>";

Page 32: DIWE - Advanced PHP Concepts

getdate() Function

Returns an associative array with date/time information of a timestamp or the current local date/time.

Syntax:getdate(timestamp);

Page 33: DIWE - Advanced PHP Concepts

Elements contained in the returned array by gettdate()

Key Description[‘seconds’] Seconds past the minutes[‘minutes’] Minutes past the hour[‘hours’] Hours of the day[‘mday’] Day of the month[‘wday’] Day of the week[‘mon’] Month of the year[‘year’] Year[‘yday’] Day of the year[‘weekday’] Name of the weekday[‘month’] Name of the month[‘0’] seconds since Unix Epoch

Page 34: DIWE - Advanced PHP Concepts

date() Function

Format a local date and time and return the formatted date strings

Syntax:date(format, timestamp);

// Prints the dayecho date("l") . "<br/>";

// Prints the day, date, month, year, time, AM or PMecho date("l jS \of F Y h:i:s A");

Page 35: DIWE - Advanced PHP Concepts

Format codes for use with date()Format Descriptiond The day of the month (from 01 to 31)D A textual representation of a day (three letters)j The day of the month without leading zeros (1 to 31)l A full textual representation of a dayS The English ordinal suffix for the day of the monthz The day of the year (from 0 through 365)F A full textual representation of a month (January through December)m A numeric representation of a month (from 01 to 12)M A short textual representation of a month (three letters)n A numeric representation of a month, without leading zeros (1 to 12)L Whether it's a leap year (1 if it is a leap year, 0 otherwise)Y A four digit representation of a yeary A two digit representation of a year

Page 36: DIWE - Advanced PHP Concepts

Format codes for use with date()Format Description

a Lowercase am or pm

A Uppercase AM or PM

g 12-hour format of an hour (1 to 12)

G 24-hour format of an hour (0 to 23)

h 12-hour format of an hour (01 to 12)

H 24-hour format of an hour (00 to 23)

i Minutes with leading zeros (00 to 59)

s Seconds, with leading zeros (00 to 59)

u Microseconds (added in PHP 5.2.2)

r The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)

U The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)

Z Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)

Page 37: DIWE - Advanced PHP Concepts

mktime() function

Returns the Unix timestamp for a date.

Syntax:mktime(hour,minute,second,month,day,year,is_dst);

// Prints: October 3, 1975 was a Fridayecho "Oct 3, 1975 was a " . date("l", mktime(0,0,0,10,3,1975));

Page 38: DIWE - Advanced PHP Concepts

checkdate() function

Used to validate a Gregorian date.

Syntax:checkdate(month, day, year);

var_dump(checkdate(2,29,2003));var_dump(checkdate(2,29,2004));

Page 39: DIWE - Advanced PHP Concepts

PHP Form Handling

The PHP superglobals $_GET and $_POST are used to collect form-data.

Page 40: DIWE - Advanced PHP Concepts

A Simple HTML Form

<form action="welcome.php" method="post">Name: <input type="text" name=“txtname”><br>E-mail: <input type="text" name=“txtemail”><br><input type="submit"></form>

When the user fills out the form above and clicks the submit button, the form data is sent to a PHP file named "welcome.php". The form data is sent with the HTTP POST method.

Page 41: DIWE - Advanced PHP Concepts

Collecting form data with PHP

The "welcome.php" looks like this:

<body>Welcome <?php echo $_POST[“txtname”]; ?><br>Your email address is: <?php echo $_POST[“txtemail”]; ?></body>

Page 42: DIWE - Advanced PHP Concepts

A Form with a hidden field

<form action="welcome.php" method="post" name="myForm">Name: <input name="txtName" type="text" /><input name="txtHidden" type="hidden" value="This is the hidden value" /><input name="" type="submit" /></form>

Page 43: DIWE - Advanced PHP Concepts

Collecting hidden field data with PHP

Welcome <?php echo $_POST["txtName"]; ?><br>Your hidden field value was: <?php echo $_POST["txtHidden"]; ?>

Page 44: DIWE - Advanced PHP Concepts

Form including multiple select elements

<form name="myForm" action="details.php" method="post">Company: <br /><select name="companies[]" multiple="multiple"><option value="microsoft">Microsoft</option><option value="google">Google</option><option value="oracle">Oracle</option></select>Products: <input type="checkbox" name="products[]" value="tab" />Tab<input type="checkbox" name="products[]" value="mobile" />Mobile<input type="checkbox" name="products[]" value="pc" />PC<input type="submit" /></form>

Page 45: DIWE - Advanced PHP Concepts

Collecting select field form data with PHP

<?php foreach($_POST["companies"] as $val){echo $val . "<br/>";}

foreach($_POST["products"] as $val){echo $val . "<br/>";}?>

Page 46: DIWE - Advanced PHP Concepts

GET vs POST

• Both GET and POST create an array. This array holds key/value pairs.

• Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope.

• $_GET is an array of variables passed via the URL parameters.

• $_POST is an array of variables passed via the HTTP POST method.

Page 47: DIWE - Advanced PHP Concepts

GET vs POST

When to use GET?• Information sent from a form with the GET

method is visible to everyone.• GET also has limits on the amount of information

to send about 2000 characters.• Because the variables are displayed in the URL, it

is possible to bookmark the page.• GET may be used for sending non-sensitive data.

Page 48: DIWE - Advanced PHP Concepts

GET vs POST

When to use POST?• Information sent from a form with the POST

method is invisible to others.• POST method has no limits on the amount of

information to send.• Because the variables are not displayed in the

URL, it is not possible to bookmark the page.• POST may be used for sending sensitive data.

Page 49: DIWE - Advanced PHP Concepts

Data validation against malicious code<?phpfunction validate_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data;}

$name = $email = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = validate_input($_POST["name"]); $email = validate_input($_POST["email"]);}

?>

Page 50: DIWE - Advanced PHP Concepts

Required fields validation <?php$nameErr = $emailErr = "";if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = validate_input($_POST["name"]); }

if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = validate_input($_POST["email"]); }}?>

Page 51: DIWE - Advanced PHP Concepts

Display the error messages in form

<form action="welcome.php" method="post">Name: <input type="text" name="name">* <?php echo $nameErr; ?><br/>

E-mail: <input type="text" name="email">* <?php echo $emailErr; ?><br/>

<input type="submit"></form>

Page 52: DIWE - Advanced PHP Concepts

Validating an E-mail address

$email = validate_input($_POST["email"]);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }

Page 53: DIWE - Advanced PHP Concepts

PHP mail() Function

The mail() function allows you to send emails directly from a script.

Syntax:mail(to, subject, message, headers, parameters);

Page 54: DIWE - Advanced PHP Concepts

PHP mail() Function

Parameter Descriptionto Required. Specifies the receiver / receivers of the email

subject Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters

messageRequired. Defines the message to be sent. Each line should be separated with a LF (\n). Lines should not exceed 70 characters.

headers Optional. Specifies additional headers, like From, Cc, and Bcc. The additional headers should be separated with a CRLF (\r\n).

parameters Optional. Specifies an additional parameter to the sendmail program

Page 55: DIWE - Advanced PHP Concepts

PHP mail() Example

<?php// the message$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters$msg = wordwrap($msg, 70);

// send emailmail("[email protected]","My subject",$msg);?>

Page 56: DIWE - Advanced PHP Concepts

PHP mail() Example

<?php$to = "[email protected]";$subject = "My subject";$txt = "Hello world!";$headers = "From: [email protected]" . "\r\n" ."CC: [email protected]";

mail($to, $subject, $txt, $headers);?>

Page 57: DIWE - Advanced PHP Concepts

Using header() function to redirect user

The header() function sends a raw HTTP header to a client.

Syntax:header(“Location: URL”);

Note: The header statement can only be used before any other output is sent.

Page 58: DIWE - Advanced PHP Concepts

header() function example

<?php header(“Location: http://company.com”); ?> <html> <head><title>testing header</title></head> <body> </body> </html>

Page 59: DIWE - Advanced PHP Concepts

File Upload

Using a form to upload the file

<form action="upload.php" method="post" enctype="multipart/form-data" name="myForm">File: <input name="user_file" type="file" /><input name="" type="submit" value="Upload File" /></form>

Page 60: DIWE - Advanced PHP Concepts

Points regarding the form

• 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• The form above sends data to a file called

"upload.php"

Page 61: DIWE - Advanced PHP Concepts

Processing the uploaded file

Information about the uploaded file is stored in the PHP built-in array called $_FILES

$_FILES[‘fieldname’][‘name’] // file name$_FILES[‘fieldname’][‘type’] // file type$_FILES[‘fieldname’][‘tmp_name’] // temp file path$_FILES[‘fieldname’][‘size’] // file size

Page 62: DIWE - Advanced PHP Concepts

Processing the uploaded file

The processing program must move the uploaded file from the temporary location to a permanent location.

Syntax: move_uploaded_file(path/tempfilename, path/permfilename);

Ex:move_uploaded_file($_FILES['user_file']['tmp_name'],"uploads/" . $_FILES['user_file']['name']);

Page 63: DIWE - Advanced PHP Concepts

Check if File Already Exists

$target_file = "uploads/" . basename($_FILES["user_file"]["name"]);

if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = false;}

Page 64: DIWE - Advanced PHP Concepts

Limit File Size

if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = false;}

Page 65: DIWE - Advanced PHP Concepts

Limit File Type

$imageFileType = pathinfo($_FILES['user_file']['name'], PATHINFO_EXTENSION);

if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"&& $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = false;}

Page 66: DIWE - Advanced PHP Concepts

Check if image file is an actual image

$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);

if($check === false) { echo "File is not an image."; $uploadOk = false;}

Page 67: DIWE - Advanced PHP Concepts

Uploading File

if (!$uploadOk) { echo "Sorry, your file was not uploaded.";} else {

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; }

}

Page 68: DIWE - Advanced PHP Concepts

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.

Page 69: DIWE - Advanced PHP Concepts

Create Cookies

A cookie is created with the setcookie() function.

Syntax:setcookie(name, value, expire, path, domain, secure, httponly);

Page 70: DIWE - Advanced PHP Concepts

Create Cookies

$cookie_name = "user";$cookie_value = “Roshan”;setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

Page 71: DIWE - Advanced PHP Concepts

Retrieve a Cookie

$cookie_name = "user";

if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!";} else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name];}

Page 72: DIWE - Advanced PHP Concepts

Modify a Cookie Value

To modify a cookie, just set the cookie again using the setcookie() function

$cookie_name = "user";$cookie_value = “Ruwan Perera”;setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");

Page 73: DIWE - Advanced PHP Concepts

Delete a Cookie

setcookie("user", "", time() – 3600, "/");

Page 74: DIWE - Advanced PHP Concepts

Check if Cookies are Enabled

First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable

setcookie("test_cookie", "test", time() + 3600, '/');

if(count($_COOKIE) > 0) { echo "Cookies are enabled.";} else { echo "Cookies are disabled.";}

Page 75: DIWE - Advanced PHP Concepts

Sessions

• A session is a way to store information (in variables) to be used across multiple pages.

• Unlike a cookie, the information is not stored on the users computer.

Page 76: DIWE - Advanced PHP Concepts

Start a PHP Session

A session is started with the session_start() function.

The session_start() function must be the very first thing in your document. Before any HTML tags.

<?phpsession_start();?><!DOCTYPE html><html>

</html>

Page 77: DIWE - Advanced PHP Concepts

Set session variables

$_SESSION["favcolor"] = "green";$_SESSION["favanimal"] = "cat";echo "Session variables are set.";

Page 78: DIWE - Advanced PHP Concepts

Get PHP Session Variable Values

echo "Favorite color is " . $_SESSION["favcolor"] . "<br>";echo "Favorite animal is " . $_SESSION["favanimal"];

Page 79: DIWE - Advanced PHP Concepts

Modify a PHP Session Variable

To change a session variable, just overwrite it

$_SESSION["favcolor"] = "yellow";

Page 80: DIWE - Advanced PHP Concepts

Destroy a PHP Session

// remove all session variablessession_unset();

// destroy the session session_destroy();

Page 81: DIWE - Advanced PHP Concepts

The End

http://twitter.com/rasansmn