SlideShare a Scribd company logo
Diploma in Web Engineering
Module VII: Advanced PHP
Concepts
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
Contents
1. Arrays
2. Indexed Arrays
3. Associative Arrays
4. Multidimensional arrays
5. Array Functions
6. PHP Objects and Classes
7. Creating an Object
8. Properties of Objects
9. Object Methods
10. Constructors
11. Inheritance
12. Method overriding
13. PHP Strings
14. printf() Function
15. String Functions
16. PHP Date/Time Functions
17. time() Function
18. getdate() Function
19. date() Function
20. mktime() function
21. checkdate() function
22. PHP Form Handling
23. Collecting form data with PHP
24. GET vs POST
25. Data validation against malicious code
26. Required fields validation
27. Validating an E-mail address
28. PHP mail() Function
29. Using header() function to redirect user
30. File Upload
31. Processing the uploaded file
32. Check if File Already Exists
33. Limit File Size
34. Limit File Type
35. Check if image file is an actual image
36. Uploading File
37. Cookies
38. 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 City
Roshan 23 Colombo
Nuwan 24 Kandy
Kamal 20 Galle
Ruwan 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”;
}
}
Constructors
A 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 Functions
Function 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 day
echo date("l") . "<br/>";
// Prints the day, date, month, year, time, AM or PM
echo date("l jS of F Y h:i:s A");
Format codes for use with date()
Format Description
d 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 day
S The English ordinal suffix for the day of the month
z 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 year
y 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 Friday
echo "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
<?php
function 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 Description
to Required. Specifies the receiver / receivers of the email
subject
Required. Specifies the subject of the email. Note: This
parameter cannot contain any newline characters
message
Required. 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 (rn).
parameters
Optional. Specifies an additional parameter to the sendmail
program
PHP mail() Example
<?php
// the message
$msg = "First line of textnSecond line of text";
// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg, 70);
// send email
mail("someone@example.com","My subject",$msg);
?>
PHP mail() Example
<?php
$to = "somebody@example.com";
$subject = "My subject";
$txt = "Hello world!";
$headers = "From: webmaster@example.com" .
"rn" .
"CC: somebodyelse@example.com";
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.
<?php
session_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 variables
session_unset();
// destroy the session
session_destroy();
The End
http://twitter.com/rasansmn

More Related Content

PPTX
JavaScript Basic
PPTX
Object oriented programming
PPS
Wrapper class
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPT
C# Basics
PDF
JavaScript - Chapter 8 - Objects
PPSX
Javascript variables and datatypes
JavaScript Basic
Object oriented programming
Wrapper class
JavaScript - Chapter 10 - Strings and Arrays
C# Basics
JavaScript - Chapter 8 - Objects
Javascript variables and datatypes

What's hot (20)

PPTX
Javascript 101
PPT
Introduction to Javascript
PPTX
Java script errors &amp; exceptions handling
PPT
PHP - Introduction to PHP Forms
PPTX
Lab #2: Introduction to Javascript
PPT
Introduction to JavaScript (1).ppt
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPSX
Data Types & Variables in JAVA
PPTX
Working with xml data
PPTX
Data types in java
PPT
9. Input Output in java
PPTX
Type casting in java
PPT
Javascript
PPT
Javascript
PDF
JavaScript - Chapter 12 - Document Object Model
PDF
Class and Objects in Java
PDF
Basics of JavaScript
PPTX
PHP FUNCTIONS
PPT
Introduction to method overloading &amp; method overriding in java hdm
PPT
Java Script ppt
Javascript 101
Introduction to Javascript
Java script errors &amp; exceptions handling
PHP - Introduction to PHP Forms
Lab #2: Introduction to Javascript
Introduction to JavaScript (1).ppt
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Data Types & Variables in JAVA
Working with xml data
Data types in java
9. Input Output in java
Type casting in java
Javascript
Javascript
JavaScript - Chapter 12 - Document Object Model
Class and Objects in Java
Basics of JavaScript
PHP FUNCTIONS
Introduction to method overloading &amp; method overriding in java hdm
Java Script ppt
Ad

Viewers also liked (20)

PPSX
DIWE - Fundamentals of PHP
PPSX
DIWE - File handling with PHP
PPSX
DIWE - Coding HTML for Basic Web Designing
PPSX
DIWE - Using Extensions and Image Manipulation
PPSX
DIWE - Working with MySQL Databases
PPSX
DIWE - Programming with JavaScript
PPT
Php Presentation
PPT
Php Security By Mugdha And Anish
PPTX
PHP Advanced
PDF
Advanced Php - Macq Electronique 2010
PDF
Advanced PHP Simplified
PPSX
Advanced PHP Web Development Tools in 2015
PDF
Advanced php testing in action
PPTX
Ahmad sameer types of computer
PDF
Yaazli International Hibernate Training
ODP
Toolbarexample
PPTX
For Loops and Variables in Java
DOCX
Java Exception handling
PDF
Yaazli International Web Project Workshop
DIWE - Fundamentals of PHP
DIWE - File handling with PHP
DIWE - Coding HTML for Basic Web Designing
DIWE - Using Extensions and Image Manipulation
DIWE - Working with MySQL Databases
DIWE - Programming with JavaScript
Php Presentation
Php Security By Mugdha And Anish
PHP Advanced
Advanced Php - Macq Electronique 2010
Advanced PHP Simplified
Advanced PHP Web Development Tools in 2015
Advanced php testing in action
Ahmad sameer types of computer
Yaazli International Hibernate Training
Toolbarexample
For Loops and Variables in Java
Java Exception handling
Yaazli International Web Project Workshop
Ad

Similar to DIWE - Advanced PHP Concepts (20)

PPT
Php my sql - functions - arrays - tutorial - programmerblog.net
PDF
0php 5-online-cheat-sheet-v1-3
PPT
Php basics
PPTX
Introduction to PHP_ Lexical structure_Array_Function_String
PPTX
Ch1(introduction to php)
PPT
Php Chapter 2 3 Training
PDF
Php Crash Course - Macq Electronique 2010
PDF
Array String - Web Programming
PPT
Php course-in-navimumbai
PPT
PHP and MySQL with snapshots
PPT
PHP Scripting
PPTX
Chapter 2 wbp.pptx
PPTX
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
DOCX
Array andfunction
PPTX
Php training in chandigarh
PPTX
PPTX
PHP Basics
PPTX
Lecture4 php by okello erick
Php my sql - functions - arrays - tutorial - programmerblog.net
0php 5-online-cheat-sheet-v1-3
Php basics
Introduction to PHP_ Lexical structure_Array_Function_String
Ch1(introduction to php)
Php Chapter 2 3 Training
Php Crash Course - Macq Electronique 2010
Array String - Web Programming
Php course-in-navimumbai
PHP and MySQL with snapshots
PHP Scripting
Chapter 2 wbp.pptx
PHPneweeeeeeeeeeeeeeeeeeeeeeeeeeeeee.pptx
Array andfunction
Php training in chandigarh
PHP Basics
Lecture4 php by okello erick

More from Rasan Samarasinghe (20)

PPTX
Managing the under performance in projects.pptx
PPTX
Agile project management with scrum
PPTX
Introduction to Agile
PPSX
IT Introduction (en)
PPSX
Application of Unified Modelling Language
PPSX
Advanced Web Development in PHP - Understanding REST API
PPSX
Advanced Web Development in PHP - Understanding Project Development Methodolo...
PPSX
Advanced Web Development in PHP - Code Versioning and Branching with Git
PPSX
DIWE - Multimedia Technologies
PPSX
Esoft Metro Campus - Programming with C++
PPSX
Esoft Metro Campus - Certificate in c / c++ programming
PPSX
Esoft Metro Campus - Certificate in java basics
PPSX
DISE - Software Testing and Quality Management
PPSX
DISE - Introduction to Project Management
PPSX
DISE - Windows Based Application Development in Java
PPSX
DISE - Windows Based Application Development in C#
PPSX
DISE - Database Concepts
PPSX
DISE - OOAD Using UML
PPSX
DISE - Programming Concepts
PPSX
DISE - Introduction to Software Engineering
Managing the under performance in projects.pptx
Agile project management with scrum
Introduction to Agile
IT Introduction (en)
Application of Unified Modelling Language
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Code Versioning and Branching with Git
DIWE - Multimedia Technologies
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in java basics
DISE - Software Testing and Quality Management
DISE - Introduction to Project Management
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in C#
DISE - Database Concepts
DISE - OOAD Using UML
DISE - Programming Concepts
DISE - Introduction to Software Engineering

Recently uploaded (20)

PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Structs to JSON How Go Powers REST APIs.pdf
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
additive manufacturing of ss316l using mig welding
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
composite construction of structures.pdf
PPTX
Construction Project Organization Group 2.pptx
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
Sustainable Sites - Green Building Construction
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Geodesy 1.pptx...............................................
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Foundation to blockchain - A guide to Blockchain Tech
CH1 Production IntroductoryConcepts.pptx
bas. eng. economics group 4 presentation 1.pptx
Structs to JSON How Go Powers REST APIs.pdf
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
OOP with Java - Java Introduction (Basics)
additive manufacturing of ss316l using mig welding
CYBER-CRIMES AND SECURITY A guide to understanding
composite construction of structures.pdf
Construction Project Organization Group 2.pptx
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Sustainable Sites - Green Building Construction
Arduino robotics embedded978-1-4302-3184-4.pdf
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Geodesy 1.pptx...............................................
Lecture Notes Electrical Wiring System Components
Model Code of Practice - Construction Work - 21102022 .pdf
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Internet of Things (IOT) - A guide to understanding
Foundation to blockchain - A guide to Blockchain Tech

DIWE - Advanced PHP Concepts

  • 1. Diploma in Web Engineering Module VII: Advanced PHP Concepts Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
  • 2. Contents 1. Arrays 2. Indexed Arrays 3. Associative Arrays 4. Multidimensional arrays 5. Array Functions 6. PHP Objects and Classes 7. Creating an Object 8. Properties of Objects 9. Object Methods 10. Constructors 11. Inheritance 12. Method overriding 13. PHP Strings 14. printf() Function 15. String Functions 16. PHP Date/Time Functions 17. time() Function 18. getdate() Function 19. date() Function 20. mktime() function 21. checkdate() function 22. PHP Form Handling 23. Collecting form data with PHP 24. GET vs POST 25. Data validation against malicious code 26. Required fields validation 27. Validating an E-mail address 28. PHP mail() Function 29. Using header() function to redirect user 30. File Upload 31. Processing the uploaded file 32. Check if File Already Exists 33. Limit File Size 34. Limit File Type 35. Check if image file is an actual image 36. Uploading File 37. Cookies 38. Sessions
  • 3. 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
  • 4. Arrays In PHP, there are three types of arrays • Indexed arrays • Associative arrays • Multidimensional arrays
  • 5. 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”;
  • 6. 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>"; }
  • 7. 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;
  • 8. 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>"; }
  • 9. 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
  • 10. Two dimensional Arrays Name Age City Roshan 23 Colombo Nuwan 24 Kandy Kamal 20 Galle Ruwan 21 Matara Two dimensional array is forming a grid of data.
  • 11. Creating a Two dimensional Array $students = array ( array(“Roshan”, 23, “Colombo”), array(“Nuwan”, 24, “Kandy”), array(“Kamal”, 20, “Galle”), array(“Ruwan”, 21, “Matara”) );
  • 12. Accessing a 2D Array Elements Syntax: Array name[row index][column index]; Ex: $age = $students[ 0 ][ 1 ];
  • 13. 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)
  • 14. 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)
  • 15. 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.
  • 16. Creating an Object class Class_name { // code will go here } $object_name = new Class_name();
  • 17. Properties of Objects Variables declared within a class are called properties class Car { var $color = “Red”; var $model = “Toyota”; var $VID = “GV - 5432”; }
  • 18. Accessing object properties $MyCar = new Car(); echo “Car color” . $MyCar -> color . “<br/>”; echo “Car model” . $MyCar -> model . “<br/>”; echo “Car VID” . $MyCar -> VID . “<br/>”;
  • 19. Changing object properties $MyCar = new Car(); $MyCar -> color = “White”; $MyCar -> model = “Honda”; $MyCar -> VID = “GC 4565”;
  • 20. 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”; } }
  • 21. Object Methods A call to an object function executes statements of the function. $MyCar = new Car(); $MyCar -> start();
  • 22. Accessing object properties within a method class Car { var $color; function setColor($color) { $this -> color = $color; } function start() { echo $this -> color . “ color car started”; } }
  • 23. Constructors A 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”);
  • 24. 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 }
  • 25. 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”; } }
  • 26. 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’
  • 27. 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);
  • 28. 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
  • 29. String Functions Function 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
  • 30. 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.
  • 31. 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/>";
  • 32. getdate() Function Returns an associative array with date/time information of a timestamp or the current local date/time. Syntax: getdate(timestamp);
  • 33. 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
  • 34. date() Function Format a local date and time and return the formatted date strings Syntax: date(format, timestamp); // Prints the day echo date("l") . "<br/>"; // Prints the day, date, month, year, time, AM or PM echo date("l jS of F Y h:i:s A");
  • 35. Format codes for use with date() Format Description d 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 day S The English ordinal suffix for the day of the month z 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 year y A two digit representation of a year
  • 36. 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)
  • 37. 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 Friday echo "Oct 3, 1975 was a " . date("l", mktime(0,0,0,10,3,1975));
  • 38. 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));
  • 39. PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data.
  • 40. 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.
  • 41. 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>
  • 42. 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>
  • 43. Collecting hidden field data with PHP Welcome <?php echo $_POST["txtName"]; ?><br> Your hidden field value was: <?php echo $_POST["txtHidden"]; ?>
  • 44. 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>
  • 45. Collecting select field form data with PHP <?php foreach($_POST["companies"] as $val){ echo $val . "<br/>"; } foreach($_POST["products"] as $val){ echo $val . "<br/>"; } ?>
  • 46. 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.
  • 47. 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.
  • 48. 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.
  • 49. Data validation against malicious code <?php function 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"]); } ?>
  • 50. 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"]); } } ?>
  • 51. 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>
  • 52. Validating an E-mail address $email = validate_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; }
  • 53. PHP mail() Function The mail() function allows you to send emails directly from a script. Syntax: mail(to, subject, message, headers, parameters);
  • 54. PHP mail() Function Parameter Description to Required. Specifies the receiver / receivers of the email subject Required. Specifies the subject of the email. Note: This parameter cannot contain any newline characters message Required. 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 (rn). parameters Optional. Specifies an additional parameter to the sendmail program
  • 55. PHP mail() Example <?php // the message $msg = "First line of textnSecond line of text"; // use wordwrap() if lines are longer than 70 characters $msg = wordwrap($msg, 70); // send email mail("someone@example.com","My subject",$msg); ?>
  • 56. PHP mail() Example <?php $to = "somebody@example.com"; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: webmaster@example.com" . "rn" . "CC: somebodyelse@example.com"; mail($to, $subject, $txt, $headers); ?>
  • 57. 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.
  • 58. header() function example <?php header(“Location: http://company.com”); ?> <html> <head><title>testing header</title></head> <body> </body> </html>
  • 59. 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>
  • 60. 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"
  • 61. 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
  • 62. 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']);
  • 63. 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; }
  • 64. Limit File Size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = false; }
  • 65. 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; }
  • 66. 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; }
  • 67. 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."; } }
  • 68. 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.
  • 69. Create Cookies A cookie is created with the setcookie() function. Syntax: setcookie(name, value, expire, path, domain, secure, httponly);
  • 70. Create Cookies $cookie_name = "user"; $cookie_value = “Roshan”; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
  • 71. 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]; }
  • 72. 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), "/");
  • 73. Delete a Cookie setcookie("user", "", time() – 3600, "/");
  • 74. 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."; }
  • 75. 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.
  • 76. 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. <?php session_start(); ?> <!DOCTYPE html> <html> </html>
  • 77. Set session variables $_SESSION["favcolor"] = "green"; $_SESSION["favanimal"] = "cat"; echo "Session variables are set.";
  • 78. Get PHP Session Variable Values echo "Favorite color is " . $_SESSION["favcolor"] . "<br>"; echo "Favorite animal is " . $_SESSION["favanimal"];
  • 79. Modify a PHP Session Variable To change a session variable, just overwrite it $_SESSION["favcolor"] = "yellow";
  • 80. Destroy a PHP Session // remove all session variables session_unset(); // destroy the session session_destroy();

Editor's Notes

  • #5: If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: $cars1="Volvo"; $cars2="BMW"; $cars3="Toyota"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is to create an array!
  • #14: $points = array(34,54,65,43); $x = each($points); echo $x[0], " ", $x[1], "<br/>"; // echo $x["key"], " ", $x["value"], "<br/>"; $x = each($points); echo $x[0], " ", $x[1], "<br/>"; // reset($points); // reset to beginning $x = each($points); echo $x[0], " ", $x[1], "<br/>"; $x = each($points); echo $x[0], " ", $x[1], "<br/>"; ----------------------------------------------------------------- $points = array(34,54,65,43); list($a, $b, $c, $d) = $points; echo $a, " ", $b, " ", $c, " ", $d, " ";
  • #28: The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string.
  • #30: $country = "sri lanka"; $n = 20; $str = sprintf("there are %u million people live in %s<br/>", $n, $country); echo $str; ----------------------------------------------------------------- $str = "hello world"; echo strlen($str); ----------------------------------------------------------------- $str = "hello world"; $retval = stristr($str, 'll'); //strstr() for case sensitive search echo $retval . "<br/>"; $retval = stristr($str, 'll', true); // returns text before first occurrence echo $retval . "<br/>"; ----------------------------------------------------------------- $str = "hello world"; $retval = stripos($str, 'll'); echo $retval . "<br/>"; ----------------------------------------------------------------- $str = "hello world"; $retval = substr($str, 6, 5); // substr(txt, start, length) echo $retval . "<br/>"; ----------------------------------------------------------------- //note that it is only the first call to strtok() that uses the string argument. After the first call, this function only needs the split argument, as it keeps track of where it is in the current string. $str = "my name is khan"; $retval = strtok($str, " "); ----------------------------------------------------------------- echo $retval . "<br/>"; $retval = strtok(" "); echo $retval . "<br/>"; $retval = strtok(" "); echo $retval . "<br/>"; $retval = strtok(" "); echo $retval . "<br/>"; $retval = strtok(" "); var_dump($retval); ----------------------------------------------------------------- $str = " Sri "; echo "Hello" . $str . "Lanka<br/>"; $retval = trim($str); echo "Hello" . $retval . "Lanka<br/>"; $retval = ltrim($str); echo "Hello" . $retval . "Lanka<br/>"; $retval = rtrim($str); echo "Hello" . $retval . "Lanka<br/>"; ----------------------------------------------------------------- $str = "<script>alert('hii');</script><b>text</b> <i>italic text</i> "; echo strip_tags($str); ----------------------------------------------------------------- $str = "hello world"; echo substr_replace($str,"sri lanka", 6, 5); ----------------------------------------------------------------- $str = "hello world"; echo strtoupper($str) . "<br/>"; echo strtolower($str) . "<br/>"; echo ucwords($str) . "<br/>"; echo ucfirst($str) . "<br/>"; ----------------------------------------------------------------- $str = "my name is khan and i'm not a terrorist.<br/>"; echo wordwrap($str, 5, "<br>"); // wordwrap (text, length of line width(default 75), character to break lines(default \n)) echo wordwrap($str, 5, "<br>", true); //true: Specifies whether words longer than the specified width should be wrapped ----------------------------------------------------------------- $str = "my name is \nkhan and \ni'm not a terrorist."; echo nl2br($str); ------------------------------------------------------------------------------------ $str = "my name is khan and i'm not a terrorist."; $retval = explode(" ", $str); var_dump($retval); echo "<br/>"; $retval = explode(" ", $str, 3); //limit…. 0-for one element, 3 for three elements, -3 excludes last three elements var_dump($retval);
  • #34: $t = getdate(); echo $t['seconds'] . "<br/>"; echo $t['minutes'] . "<br/>"; echo $t['hours'] . "<br/>"; echo $t['mday'] . "<br/>"; echo $t['wday'] . "<br/>"; echo $t['mon'] . "<br/>"; echo $t['year'] . "<br/>"; echo $t['weekday'] . "<br/>"; echo $t['month'] . "<br/>"; echo $t['0'] . "<br/>";
  • #36: echo date("l jS \of F Y h:i:s A") . "<br/>"; echo "day of the month: " . date(" d") . "<br/>"; echo "textual representation of the day: " . date(" D") . "<br/>"; echo "day of the month without leading zeros: " . date(" j") . "<br/>"; echo "full textual representation of the day: " . date(" l") . "<br/>"; echo "suffix of the day of the month: " . date(" S") . "<br/>"; echo "day of the year: " . date("z") . "<br/>"; echo "full textual representation of the month: " . date(" F") . "<br/>"; echo "numeric representation of the month: " . date(" m") . "<br/>"; echo "short textual representation of the month: " . date(" M") . "<br/>"; echo "numeric representation of the month without leading zero: " . date(" n") . "<br/>"; echo "Whether its a leap year: " . date("L") . "<br/>"; echo "four digit year: " . date("Y") . "<br/>"; echo "two digit year: " . date(" y") . "<br/>";
  • #37: echo "lowercase am or pm: " . date("a") . "<br/>"; echo "uppercase am or pm: " . date("A") . "<br/>"; echo "12 hour format of hour: " . date("g") . "<br/>"; echo "24 hour format of hour: " . date("G") . "<br/>"; echo "12 hour format of hour: " . date("h") . "<br/>"; echo "24 hour format of hour: " . date("H") . "<br/>"; echo "minutes with leading zeros: " . date("i") . "<br/>"; echo "seconds with leading zeros: " . date("s") . "<br/>"; echo "microseconds: " . date("u") . "<br/>"; echo "rfc 2822 format date: " . date("r") . "<br/>"; echo "seconds since unix epoch: " . date("U") . "<br/>"; echo "timezone offset in seconds: " . date("Z") . "<br/>";
  • #54: http://stackoverflow.com/questions/15965376/how-to-configure-xampp-to-send-mail-from-localhost in php.ini file find [mail function] and change SMTP=smtp.gmail.com smtp_port=587 sendmail_from = my-gmail-id@gmail.com sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t“ Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code [sendmail] smtp_server=smtp.gmail.com smtp_port=587 error_logfile=error.log debug_logfile=debug.log auth_username=my-gmail-id@gmail.com auth_password=my-gmail-password force_sender=my-gmail-id@gmail.com
  • #55: LF – Line Feed
  • #58: Incorrect!! <html> <head><title>testing header</title></head> <body> <?php header(“Location: http://company.com”); ?> </body> </html> Incorrect!! (whitespace before php block) <?php header(“Location: http://company.com”); ?> <html> <head><title>testing header</title></head> <body> </body> </html>
  • #62: $file_extension = pathinfo($_FILES[‘field_name']['name'], PATHINFO_EXTENSION)