2. About Me
$orienter = new stdClass;
$orienter->name = “Vibol YOEUNG”;
$orienter->company = “Webridge Technologies”
$orienter->email = “youeng.vibol@gmail.com
3. What is PHP?
PHP stands for PHP: Hypertext Preprocessor
and is a server--‐side language. This means
that when a visitor opens the page, the server
processes the PHP commands and then sends
the results to the visitor's browser.
5. What can php do?
• Allow creation of shopping carts for e--‐
commerce websites.
• Allow creation of CMS(Content Management
System) Website.
• Allow creation of forum website
• Allow creation of Web application
6. Installation
• Following things are required for using php on windows
– Apache Server or IIS Server
– MySql
– Php
WampServer is a Windows web development environment.
With this we can create web applications with Apache, PHP
and the MySQL database. Even PHPMyAdmin is provided to
manage your databases.
7. Basic PHP Syntax
• Standard Tags: Recommended
<?php
code goes here
?>
• Short tags
<?
code goes here
?>
• HTML or script tags
<script language=”php”>
code goes here
</script>
8. Comments
• PHP has two form of comments
1. Single--‐line comments begin with a double slash (//) or
sharp (#).
2. Multi--‐line comments begin with "/*" and end with "*/".
Syntax
Ex.
// This is a single-line comment
# This is a single-line comment
/*
This is
a multi-line
comment.
*/
9. Introducing Variables
A variable is a representation of a particular value,
such as hello or 87266721. By assigning a value to a
variable, you can reference the variable in other places
in your script, and that value will always remain the
same (unless you change it).
10. Naming Your Variables
• Variable names should begin with a dollar($)
symbol.
• Variable names can begin with an underscore.
• Variable names cannot begin with a numeric
character.
• Variable names must be relevant and self--‐
explanatory.
11. Naming Your Variables
Here are some examples of valid and invalid
variable names:
• $_varname valid
• $book valid
• sum invalid: doesn’t start with dollar sign($)
$18varname invalid: starts with number; it doesn’t
start with letter or underscore
• $x*y invalid: contains multiply sign which only
letters, digits, and underscore are allowed.
12. Variable Variables
$a = “hello”;
$$a = “world”;
echo “$a ${$a}”;
produce the same out put as
echo “$a $hello”;
Out put: hello world
13. Data type
You will create two main types of variables in
your PHP code: scalar and array. Scalar
variables contain only one value at a time, and
arrays contain a list of values or even another
array.
14. Constant Variable
• A constant is an identifier for a value that cannot
change during the course of a scrip.
• define("CONSTANT_NAME", value [, true | false]);
• Example
define(“MYCONSTANT”, “This is my constant”);
echo MYCONSTANT;
15. Some predefined constants include
• __FILE__ Return the path and file name of the script
file being parsed.
• __LINE__ Return the number of the line in the script
being parsed.
• __DIR__ Return the path of the script file being
parsed.
• DIRECTORY_SEPARATOR Return the (on
Windows) or / (on Unix) depending on OS(Operating
System)
• PHP_VERSION Return the version of PHP in use.
• PHP_OS Return the operating system using PHP.
17. Using Environment Variables in
PHP
$_SERVER is an array containing information such as headers,
paths, and script locations. The entries in this array are created
by the web server.
- $_SERVER['SERVER_ADDR'] : Return address: ex. 127.0.01
- $_SERVER['SERVER_NAME']: Return server name: ex.
Localhost
- $_SERVER['HTTP_USER_AGENT']: Return User Agent which
request
18. Function testing on variable
• is_int( value ) Returns true if value is an integer, false otherwise
• is_float( value ) Returns true if value is a float, false otherwise
• is_string( value ) Returns true if value is a string, false otherwise
• is_bool( value ) Returns true if value is a Boolean, false otherwise
• is_array( value ) Returns true if value is an array, false otherwise
• is_null( value ) Returns true if value is null, false otherwise
• isset ( $var [, $var [, $... ]] ) return true if a variable is set and is not NULL.
If multiple parameters are supplied then isset() will return TRUE only if all
of the parameters are set. Evaluation goes from left to right
• unset( $var ) Unset a given variable
• is_numeric($var) Returns true if a variable contains a number or numeric
string (strings containing a sign, numbers and decimal points).
19. Getting Variables from Form in PHP
• In case: method="get": To return data from a
HTML form element in case form has attribute
method=”get”, you use the following
syntax:
$_GET['formName'];
You can assign this to a variable:
$myVariable = $_GET['formName'];
20. Getting Variables from Form in PHP
• In case: method="post": To return data from a
HTML form element in case form has attribute
method=”post”, you use the following
syntax:
$_POST['formName'];
You can assign this to a variable:
$myVariable = $_POST['formName'];
21. Getting Variables from Form in PHP
• In case: method=”get” or method="post": To
return data from a HTML form element in case
form has attribute method=”get” or
method=”post”, you use the following
syntax:
$_REQUEST['formName'];
You can assign this to a variable:
$myVariable = $_REQUEST['formName'];
22. Getting Variables from Form in PHP
• Example:
<html>
<head> <title>A BASIC HTML FORM</title>
<?php $username = $_POST['username']; print ($username); ?>
</head>
<body>
<form action="test.php" method="post">
<input type="text" name="username" />
<input type="submit" name="btnsubmit" value="Submit" /> </form>
</body>
</html>
23. Import External PHP File
• include() generates a warning, but the script will continue execution
• include_once() statement is identical to include() except PHP will
check if the file has already been included, and if so, not include
(require) it again.
• include() except PHP will check if the file has already been included,
and if so, not include (require) it again.
• require() generates a fatal error, and the script will stop
• require_once() statement is identical to require() except PHP will
check if the file has already been included, and if so, not include
(require) it again.
24. Import External PHP File
Example
– Error Example include() Function
<html>
<head><title>Import External PHP File</title>
<?php include("wrongFile.php"); echo "Hello World!"; ?>
</head>
<body> </body>
</html>
Error message: Warning: include(wrongFile.php) [function.include]: failed to
open stream: No such file or directory in C:homewebsitetest.php on line 5
Warning: include() [function.include]: Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:php5pear') in C:homewebsitetest.php on line 5
Hello World!
Notice that the echo statement is executed! This is because a Warning does not
stop the script execution.
25. Import External PHP File
Example
– Error Example require() Function
<html>
<head><title>Import External PHP File</title>
<?php require("wrongFile.php"); echo "Hello World!"; ?>
</head>
<body> </body>
</html>
Warning: require(wrongFile.php) [function.require]: failed to open stream:
No such file or directory in C:homewebsitetest.php on line 5
Fatal error: require() [function.require]: Failed opening required
'wrongFile.php' (include_path='.;C:php5pear') in
C:homewebsitetest.php on line 5
The echo statement is not executed, because the script execution stopped
after the fatal error. It is recommended to use the require() function instead
of include(), because scripts should not continue after an error.
27. Operator
• Comparison Operator
– == Equal: True if value of value1 equal to the value of
value2
– === Identical: True if value of value1 equal to the value of
value2 and they are of the same type
– != Not equal
– <> Not equal
– !== Not identical
– < Less then
– > Greater then
– <= Less then or equal to
– >= Greater then or equal to
28. Logical Operator
• Logical operator
– and : $a and $b true if both $a and $b are true
– &&: the same and
– or: $a and $b true if either $a and $b are true
– ||: the same or
– xor: $a xor $b true if either $a and $b are true, but
not both.
– !: !$a true if $a is not true
29. Control Structure
• Conditional Statements
if ( expression ) // Single Statement
or
if ( expression ) {
//Single Statement or Multiple Statements
}
or
if ( expression ) :
//Single Statement or Multiple Statements
endif;
30. Control Structure
• Using else clause with the if statement
if ( expression ) // Single Statement
else // Single Statement
or
if ( expression ) {
// Single Statement or Multiple Statements
} else {
// Single Statement or Multiple Statements
}
or
if ( expression ) :
// Single Statement or Multiple Statements
else:
// Single Statement or Multiple Statements
endif;
31. Switch Statement
switch ( expression ) {
case result1:
execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement // has been
encountered hither to
}
32. Switch Statement
switch ( expression ) :
case result1:
execute this if expression results in result1
break;
case result2:
// execute this if expression results in result2
break;
default:
// execute this if no break statement // has been
encountered hither to
endswitch;
33. Ternary Operator
( expression )?true :false;
example
$st = 'Hi';
$result = ($st == 'Hello') ? 'Hello everyone in the
class': 'Hi every body in class';
print $result;
34. Looping statement
• While statement
while ( expression ) {
// do something
}
Or
while ( expression ) :
// do something
endwhile;
35. Looping statement
• do … while statement
• do {
// code to be executed
} while ( expression );
36. Looping Statment
• For statemement
• for (initialize variable exp; test expression; modify variable exp) // Single
Statement
Or
for (initialize variable exp; test expression; modify variable exp){
// Single Statement or Multiple Statements
}
Or
for (initialize variable exp; test expression; modify variable exp):
// Single Statement or Multiple Statements
endfor;
37. Looping statement
• Break statement:
Use for terminate the current for, foreach, while, do while or switch
structure
<?php
for ($i=0; $i<=10; $i++) {
if ($i==3){
break;
}
echo "The number is ".$i; echo "<br />";
}
?>
38. Function
function is a self--‐contained block of code that
can be called by your scripts. When called, the
function's code is executed.
• Define function
function myFunction($argument1, $argument2)
{
// function code here
}
39. Array
• There are two kinds of arrays in PHP: indexed and
associative. The keys of an indexed array are integers,
beginning at 0. Indexed arrays are used when you identify
things by their position. Associative arrays have strings as
keys and behave more like two--‐column tables. The first
column is the key, which is used to access the value.
40. Array
• Numeric array
Numerically indexed arrays can be created to start at
any index value. Often it's convenient to start an array at
index 1, as shown in the following example:
$numbers = array(1=>"one", "two", "three", "four");
Arrays can also be sparsely populated, such as:
$oddNumbers = array(1=>"one", 3=>"three", 5=>"five");
41. Array
• Associative array
An associative array uses string indexes—or keys—to access values stored in
the array. An associative array can be constructed using array( ), as shown in
the following example, which constructs an array of integers:
$array = array("first"=>1, "second"=>2, "third"=>3);
// Echo out the second element: prints "2"
echo $array["second"];
The same array of integers can also be created with the bracket syntax:
$array["first"] = 1;
$array["second"] = 2;
$array["third"] = 3;
42. Using foreach loop with array
• The foreach statement has two forms:
foreach(array_expression as $value) statement foreach(array_expression as
$key => $value) statement
Example:
// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);
// Convert an array of centimeter lengths to inches
foreach($lengths as $cm) {
$inch = $cm / 2.54;
echo "$cm centimeters = $inch inchesn";
}
foreach($lengths as $index => $cm) {
$inch = $cm / 2.54;
$item = $index + 1;
echo $index + 1 . ". $cm centimeters = $inch inchesn";
}
43. Basic array function
• count(mixed var): function returns the number of
elements in the array var
The following example prints 7 as expected:
$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sun");
echo count($days); // 7
• number max(array numbers)
• number min(array numbers)
$var = array(10, 5, 37, 42, 1, --‐56);
echo max($var); // prints 42
echo min($var); // prints --‐56
44. File Upload
• Before you start uploading files, check a few values in your
php.ini file. Look for this section of text:
• ;;;;;;;;;;;;;;;; ; File Uploads ; ;;;;;;;;;;;;;;;; ;
• Whether to allow HTTP file uploads.
File_uploads = On ;
Temporary directory for HTTP uploaded files (will use system
default if not ; specified).
upload_tmp_dir = /temp
Maximum allowed size for uploaded files.
Upload_max_filesize = 2M
45. File Upload
• Before you can use PHP to manage your uploads, you need
first construct an HTML form as an interface for a user to
upload his file. Have a look at the example below and save
this HTML code as index.php.
<html>
<body>
<form enctype="multipart/form--data" action="upload.php"
method="post"> ‘’ enctype for sent data “
Choose a file to upload: <input name="uploaded_file" type="file" />
<input type="submit" value="Upload" />
</form>
</body>
</html>
46. File Upload
Processing the Form Data (PHP Code)
• $_FILES["uploaded_file"]["name"]: the original name
of the file uploaded from the user's machine•
$_FILES["uploaded_file"]["type"]: the MIME type of
the uploaded file (if the browser provided the type)
• $_FILES["uploaded_file"]["size"]: the size of the
uploaded file in bytes
• $_FILES["uploaded_file"]["tmp_name"] : the location
in which the file is temporarily stored on the server
• $_FILES["uploaded_file"]["error"]: an error code
resulting from the file upload
47. 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.
• Note: The session_start() function must appear
BEFORE the <html> tag:
• Example:
<?php session_start(); ?>
<html>
<body> </body>
</html>
48. Sessions
• Destroying session
- If you wish to delete some session data, you can use the unset() or the
session_destroy() function. The unset() function is used to free the
specified session variable:
<?php
unset($_SESSION['views']);
?>
- You can also completely destroy the session by calling the session_destroy()
function:
<?php
session_destroy();
?>
Note: session_destroy() will reset your session and you will lose all your
stored session data.
49. Cookies
• A cookie is a small file that the server embeds on the
user's computer. Each time the same computer
requests a page with a browser, it will send the cookie
too. With PHP, you can both create and retrieve
cookie values.
• Syntax:
setcookie ( string $name [, string $value [, int $expire
= 0 [, string $path [, string $domain [, bool $secure =
false [, bool $httponly = false ]]]]]] )
50. Cookies
• Tip: The value of a cookie named "user" can be
accessed by $HTTP_COOKIE_VARS["user"] or
by $_COOKIE["user"].
Example:
<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
52. Reminder… a function
Reusable piece of code.
Has its own ‘local scope’.
function my_func($arg1,$arg2) {
<< function statements >>
}
53. Conceptually, what does a function
represent?
…give the function something (arguments), it
does something with them, and then returns
a result…
Action or Method
54. What is a class?
Conceptually, a class
represents an object, with
associated methods and
variables
55. Class Definition
<?php
class dog {
public $name;
public function bark() {
echo ‘Woof!’;
}
}
?>
An example class definition for a
dog. The dog object has a single
attribute, the name, and can
perform the action of barking.
56. Class Definition
<?php
class dog {
public $name;
public function bark() {
echo ‘Woof!’;
}
}
?>
class dog {
Define the
name of the
class.
57. Class Definition
<?php
class dog {
var $name
public function bark() {
echo ‘Woof!’;
}
}
?>
public $name;
Define an object
attribute
(variable), the
dog’s name.
58. Class Definition
<?php
class dog {
public $name;
function bark() {
echo ‘Woof!’;
}
}
?>
public function bark() {
echo ‘Woof!’;
}
Define an
object action
(function), the
dog’s bark.
59. Class Definition
Similar to defining a function..
A class is a collection of variables and functions
working with these variables.
63. Class Usage
<?php
require(‘dog.class.php’);
$puppy = new dog();
$puppy->name = ‘Rover’;
echo “{$puppy->name} says ”;
$puppy->bark();
?>
$puppy->name = ‘Rover’;
Set the name
variable of this
instance to
‘Rover’.
64. Class Usage
<?php
require(‘dog.class.php’);
$puppy = new dog();
$puppy->name = ‘Rover’;
echo “{$puppy->name} says ”;
$puppy->bark();
?>
echo “{$puppy->name} says ”;
Use the name
variable of this
instance in an
echo
statement..
66. Using attributes within the class..
•
If you need to use the class variables within
any class actions, use the special variable
$this in the definition:
class dog {
public $name;
public function bark() {
echo $this->name.‘ says Woof!’;
}
}
67. Constructor methods
•
A constructor method is a function that is
automatically executed when the class is first
instantiated.
•
Create a constructor by including a function
within the class definition with the __construct
name.
•
Remember.. if the constructor requires
arguments, they must be passed when it is
instantiated!
68. Constructor Example
<?php
class dog {
public $name;
public function __construct($nametext) {
$this->name = $nametext;
}
public function bark() {
echo ‘Woof!’;
}
}
?>
Constructor function
70. Class Scope
•
Like functions, each instantiated object has
its own local scope.
e.g. if 2 different dog objects are instantiated,
$puppy1 and $puppy2, the two dog names
$puppy1->name and $puppy2->name are
entirely independent..
72. Modifier
In object oriented programming, some Keywords
are private, protected and some are public in
class. These keyword are known as modifier.
These keywords help you to define how these
variables and properties will be accessed by the
user of this class.
73. Private
Properties or methods declared as private are not
allowed to be called from outside the class.
However any method inside the same class can
access them without a problem.
75. Private
Example 2:
This code will create error:
Fatal error: Cannot access private property MyClass::$private in
C:wampwwwe-
romCodeprivate.php on line 11
76. Private
Example 3:
This code will create error:
Notice: Undefined property: MyClass2::$private in C:wampwwwe-
romCodeprivate1.php on
line 14
77. Protected
•
When you declare a method (function) or a
property (variable) as protected, those
methods and properties can be accessed by
– The same class that declared it.
– The classes that inherit the above declared class.
79. Protected
Example 2:
Fatal error: Cannot access protected property MyChildClass::$protected in
C:wampwwwe-
romCodepublic2.php on line 18
80. Public
•
scope to make that variable/function available
from anywhere, other classes and instances of
the object.
– The same class that declared it.
– The classes that inherit the above declared class.
82. Extending a Class (Inheritance)
when you extend a class, the subclass inherits
each public and protected method from the
guardian class. Unless a class overrides those
techniques, they will hold their unique
functionality
84. Encapsulation
it’s the way we define the visibility of our
properties and methods. When you’re creating
classes, you have to ask yourself what properties
and methods can be accessed outside of the
class.
86. Polymorphism
This is an object oriented concept where same
function can be used for different purposes. For
example function name will remain same but it
make take different number of arguments and
can do different task.
88. Interface
Interfaces are defined to provide a common
function names to the implementors. Different
implementors can implement those interfaces
according to their requirements. You can say,
interfaces are skeletons which are implemented
by developers.
90. Abstract class
An abstract class is one that cannot be instantiated, only
inherited. You declare an abstract class with the keyword
abstract, like this:
When inheriting from an abstract class, all methods
marked abstract in the parent's class declaration must be
defined by the child; additionally, these methods must be
defined with the same visibility
92. Static Keyword
Declaring class members or methods as static
makes them accessible without needing an
instantiation of the class. A member declared as
static can not be accessed with an instantiated
class object (though a static method can).
94. Final Keyword
PHP 5 introduces the final keyword, which
prevents child classes from overriding a method
by prefixing the definition with final. If the class
itself is being defined final then it cannot be
extended.