diwe - advanced php concepts
TRANSCRIPT
Diploma in Web Engineering
Module VII: Advanced PHP Concepts
Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.
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
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
Arrays
In PHP, there are three types of arrays
• Indexed arrays• Associative arrays• Multidimensional arrays
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”;
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>";}
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;
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>";}
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
Two dimensional Arrays
Name Age CityRoshan 23 ColomboNuwan 24 KandyKamal 20 GalleRuwan 21 Matara
Two dimensional array is forming a grid of data.
Creating a Two dimensional Array
$students = array ( array(“Roshan”, 23, “Colombo”), array(“Nuwan”, 24, “Kandy”), array(“Kamal”, 20, “Galle”), array(“Ruwan”, 21, “Matara”) );
Accessing a 2D Array Elements
Syntax:
Array name[row index][column index];
Ex:
$age = $students[ 0 ][ 1 ];
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)
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)
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.
Creating an Object
class Class_name {
// code will go here
}
$object_name = new Class_name();
Properties of Objects
Variables declared within a class are called properties
class Car {var $color = “Red”;var $model = “Toyota”;var $VID = “GV - 5432”;}
Accessing object properties
$MyCar = new Car();
echo “Car color” . $MyCar -> color . “<br/>”;echo “Car model” . $MyCar -> model . “<br/>”;echo “Car VID” . $MyCar -> VID . “<br/>”;
Changing object properties
$MyCar = new Car();
$MyCar -> color = “White”;$MyCar -> model = “Honda”;$MyCar -> VID = “GC 4565”;
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”;}}
Object Methods
A call to an object function executes statements of the function.
$MyCar = new Car();
$MyCar -> start();
Accessing object properties within a method
class Car {var $color;
function setColor($color) {$this -> color = $color;}
function start() {echo $this -> color . “ color car started”;}}
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”);
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}
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”;}}
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’
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);
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
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
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.
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/>";
getdate() Function
Returns an associative array with date/time information of a timestamp or the current local date/time.
Syntax:getdate(timestamp);
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
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");
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
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)
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));
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));
PHP Form Handling
The PHP superglobals $_GET and $_POST are used to collect form-data.
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.
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>
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>
Collecting hidden field data with PHP
Welcome <?php echo $_POST["txtName"]; ?><br>Your hidden field value was: <?php echo $_POST["txtHidden"]; ?>
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>
Collecting select field form data with PHP
<?php foreach($_POST["companies"] as $val){echo $val . "<br/>";}
foreach($_POST["products"] as $val){echo $val . "<br/>";}?>
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.
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.
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.
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"]);}
?>
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"]); }}?>
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>
Validating an E-mail address
$email = validate_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
PHP mail() Function
The mail() function allows you to send emails directly from a script.
Syntax:mail(to, subject, message, headers, parameters);
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
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);?>
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);?>
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.
header() function example
<?php header(“Location: http://company.com”); ?> <html> <head><title>testing header</title></head> <body> </body> </html>
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>
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"
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
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']);
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;}
Limit File Size
if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = false;}
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;}
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;}
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."; }
}
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.
Create Cookies
A cookie is created with the setcookie() function.
Syntax:setcookie(name, value, expire, path, domain, secure, httponly);
Create Cookies
$cookie_name = "user";$cookie_value = “Roshan”;setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
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];}
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), "/");
Delete a Cookie
setcookie("user", "", time() – 3600, "/");
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.";}
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.
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>
Set session variables
$_SESSION["favcolor"] = "green";$_SESSION["favanimal"] = "cat";echo "Session variables are set.";
Get PHP Session Variable Values
echo "Favorite color is " . $_SESSION["favcolor"] . "<br>";echo "Favorite animal is " . $_SESSION["favanimal"];
Modify a PHP Session Variable
To change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
Destroy a PHP Session
// remove all session variablessession_unset();
// destroy the session session_destroy();
The End
http://twitter.com/rasansmn