SlideShare a Scribd company logo
1 of 96
Download to read offline
PHP Basic
About Me
$orienter = new stdClass;
$orienter->name = “Vibol YOEUNG”;
$orienter->company = “Webridge Technologies”
$orienter->email = “youeng.vibol@gmail.com
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.
How PHP work?
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
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.
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>
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.
*/
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).
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.
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.
Variable Variables
$a = “hello”;
$$a = “world”;
echo “$a ${$a}”;
produce the same out put as
echo “$a $hello”;
Out put: hello world
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.
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;
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.
Some predefined constants include
• Example:
• <?php echo __FILE__ . "<br />"; // output:
C:wampwwwPHPtest.php echo __LINE__ . "<br />"; // output: 3
• echo __DIR__ . "<br />"; // output: C:wampwwwPHP
• echo DIRECTORY_SEPARATOR . "<br />"; // output: 
• echo PHP_VERSION . "<br />"; // output: 5.3.5 echo PHP_OS .
"<br />"; // output: WINNT ?>
• defined() Checks whether a given named constant exists
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
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).
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'];
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'];
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'];
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>
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.
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.
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.
Operator
• Assignment Operator(=)
• Arithmetic Operator
– + Add values
– - Subtract values
– * Multiple values
– / Device values
– % Modulus, or remainder
• Concatenation Operator(.)
– +=
– -=
– /=
– *=
– %=
– . =
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
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
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;
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;
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
}
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;
Ternary Operator
( expression )?true :false;
example
$st = 'Hi';
$result = ($st == 'Hello') ? 'Hello everyone in the
class': 'Hi every body in class';
print $result;
Looping statement
• While statement
while ( expression ) {
// do something
}
Or
while ( expression ) :
// do something
endwhile;
Looping statement
• do … while statement
• do {
// code to be executed
} while ( expression );
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;
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 />";
}
?>
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
}
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.
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");
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;
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";
}
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
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
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>
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
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>
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.
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 ]]]]]] )
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);
?>
PHP Classes
Reminder… a function
Reusable piece of code.
Has its own ‘local scope’.
function my_func($arg1,$arg2) {
<< function statements >>
}
Conceptually, what does a function
represent?
…give the function something (arguments), it
does something with them, and then returns
a result…
Action or Method
What is a class?
Conceptually, a class
represents an object, with
associated methods and
variables
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.
Class Definition
<?php
class dog {
public $name;
public function bark() {
echo ‘Woof!’;
}
}
?>
class dog {
Define the
name of the
class.
Class Definition
<?php
class dog {
var $name
public function bark() {
echo ‘Woof!’;
}
}
?>
public $name;
Define an object
attribute
(variable), the
dog’s name.
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.
Class Definition
Similar to defining a function..
A class is a collection of variables and functions
working with these variables.
Class Usage
<?php
require(‘dog.class.php’);
$puppy = new dog();
$puppy->name = ‘Rover’;
echo “{$puppy->name} says ”;
$puppy->bark();
?>
Class Usage
<?php
require(‘dog.class.php’);
$puppy = new dog();
$puppy->name = ‘Rover’;
echo “{$puppy->name} says ”;
$puppy->bark();
?>
require(‘dog.class.php’);
Include the
class definition
Class Usage
<?php
require(‘dog.class.php’);
$puppy = new dog();
$puppy->name = ‘Rover’;
echo “{$puppy->name} says ”;
$puppy->bark();
?>
$puppy = new dog();
Create a new
instance of the
class.
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’.
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..
Class Usage
<?php
require(‘dog.class.php’);
$puppy = new dog();
$puppy->name = ‘Rover’;
echo “{$puppy->name} says ”;
$puppy->bark();
?>
$puppy->bark();
Use the
dog object
bark
method.
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!’;
}
}
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!
Constructor Example
<?php
class dog {
public $name;
public function __construct($nametext) {
$this->name = $nametext;
}
public function bark() {
echo ‘Woof!’;
}
}
?>
Constructor function
Constructor Example
<?php
…
$puppy = new dog(‘Rover’);
…
?>
Constructor arguments
are passed during the
instantiation of the
object.
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..
OOP Concepts
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.
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.
Private
Example 1:
Result: Hello world
Private
Example 2:
This code will create error:
Fatal error: Cannot access private property MyClass::$private in
C:wampwwwe-
romCodeprivate.php on line 11
Private
Example 3:
This code will create error:
Notice: Undefined property: MyClass2::$private in C:wampwwwe-
romCodeprivate1.php on
line 14
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.
Protected
Example 1:
Result: Hello Mr. Bih
Protected
Example 2:
Fatal error: Cannot access protected property MyChildClass::$protected in
C:wampwwwe-
romCodepublic2.php on line 18
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.
Public
Example 1:
Result:
This is a man.
This is a man
This is a man.
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
Extending a Class (Inheritance)
Example:
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.
Encapsulation
Example:
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.
Polymorphism
Example:
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.
Interface
Example:
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
Abstract class
Example:
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).
Static Keyword
Example:
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.
Final Keyword
Example:
Fatal error: Cannot override final method Animal::getName()
Thanks for your time.

More Related Content

What's hot (20)

Php basics
Php basicsPhp basics
Php basics
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
 
Basic of PHP
Basic of PHPBasic of PHP
Basic of PHP
 
Introduction to php basics
Introduction to php   basicsIntroduction to php   basics
Introduction to php basics
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
PHP Web Programming
PHP Web ProgrammingPHP Web Programming
PHP Web Programming
 
Php
PhpPhp
Php
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Open Source Package PHP & MySQL
Open Source Package PHP & MySQLOpen Source Package PHP & MySQL
Open Source Package PHP & MySQL
 
PHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet SolutionPHP - Introduction to PHP - Mazenet Solution
PHP - Introduction to PHP - Mazenet Solution
 
Control Structures In Php 2
Control Structures In Php 2Control Structures In Php 2
Control Structures In Php 2
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Data Types In PHP
Data Types In PHPData Types In PHP
Data Types In PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP
PHPPHP
PHP
 
Class 6 - PHP Web Programming
Class 6 - PHP Web ProgrammingClass 6 - PHP Web Programming
Class 6 - PHP Web Programming
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 

Similar to PHP Basic

Similar to PHP Basic (20)

Learn PHP Basics
Learn PHP Basics Learn PHP Basics
Learn PHP Basics
 
Php
PhpPhp
Php
 
php.pdf
php.pdfphp.pdf
php.pdf
 
Php essentials
Php essentialsPhp essentials
Php essentials
 
FYBSC IT Web Programming Unit IV PHP and MySQL
FYBSC IT Web Programming Unit IV  PHP and MySQLFYBSC IT Web Programming Unit IV  PHP and MySQL
FYBSC IT Web Programming Unit IV PHP and MySQL
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
Introduction To Php For Wit2009
Introduction To Php For Wit2009Introduction To Php For Wit2009
Introduction To Php For Wit2009
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Lecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdfLecture2_IntroductionToPHP_Spring2023.pdf
Lecture2_IntroductionToPHP_Spring2023.pdf
 
LAB PHP Consolidated.ppt
LAB PHP Consolidated.pptLAB PHP Consolidated.ppt
LAB PHP Consolidated.ppt
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
PHP variables
PHP  variablesPHP  variables
PHP variables
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
Php using variables-operators
Php using variables-operatorsPhp using variables-operators
Php using variables-operators
 

Recently uploaded

Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"
UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"
UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"DianaGray10
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimization100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimizationarrow10202532yuvraj
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024Alexander Turgeon
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementNuwan Dias
 
Governance in SharePoint Premium:What's in the box?
Governance in SharePoint Premium:What's in the box?Governance in SharePoint Premium:What's in the box?
Governance in SharePoint Premium:What's in the box?Juan Carlos Gonzalez
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 

Recently uploaded (20)

Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"
UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"
UiPath Clipboard AI: "A TIME Magazine Best Invention of 2023 Unveiled"
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimization100+ ChatGPT Prompts for SEO Optimization
100+ ChatGPT Prompts for SEO Optimization
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API Management
 
Governance in SharePoint Premium:What's in the box?
Governance in SharePoint Premium:What's in the box?Governance in SharePoint Premium:What's in the box?
Governance in SharePoint Premium:What's in the box?
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 

PHP Basic

  • 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.
  • 16. Some predefined constants include • Example: • <?php echo __FILE__ . "<br />"; // output: C:wampwwwPHPtest.php echo __LINE__ . "<br />"; // output: 3 • echo __DIR__ . "<br />"; // output: C:wampwwwPHP • echo DIRECTORY_SEPARATOR . "<br />"; // output: • echo PHP_VERSION . "<br />"; // output: 5.3.5 echo PHP_OS . "<br />"; // output: WINNT ?> • defined() Checks whether a given named constant exists
  • 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.
  • 26. Operator • Assignment Operator(=) • Arithmetic Operator – + Add values – - Subtract values – * Multiple values – / Device values – % Modulus, or remainder • Concatenation Operator(.) – += – -= – /= – *= – %= – . =
  • 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.
  • 60. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?>
  • 61. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> require(‘dog.class.php’); Include the class definition
  • 62. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy = new dog(); Create a new instance of the class.
  • 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..
  • 65. Class Usage <?php require(‘dog.class.php’); $puppy = new dog(); $puppy->name = ‘Rover’; echo “{$puppy->name} says ”; $puppy->bark(); ?> $puppy->bark(); Use the dog object bark method.
  • 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
  • 69. Constructor Example <?php … $puppy = new dog(‘Rover’); … ?> Constructor arguments are passed during the instantiation of the object.
  • 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.
  • 81. Public Example 1: Result: This is a man. This is a man This is a man.
  • 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
  • 83. Extending a Class (Inheritance) Example:
  • 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.
  • 95. Final Keyword Example: Fatal error: Cannot override final method Animal::getName()