Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

PHP

Open Source 34
Agenda

What is PHP ?

History

Installation

Data Types

Control Structure

Functions

Global Variables

GET & POST

Cookies & Sessions

MySql

Include Files 2
What is PHP?

3
What is PHP ?

• PHP is an acronym for "PHP Hypertext Preprocessor"


• PHP is a widely-used, open source scripting language
• PHP scripts are executed on the server
• PHP costs nothing, it is free to download and use

4
History

PHP development began in 1994 when the developer
Rasmus Lerdorf wrote a series of Common Gateway
Interface (CGI) Binaries in the C programming language.
– CGI provides an interface between the Web server and
programs that generate the Web content.

Client request for page ---> webserver ---[CGI]----> Server side


Program


PHP early non-released versions were used on his home
page to keep track of who was looking at his online
resume
5
History (Cont’d)

• Lerdorf initially announced the release of PHP as "Personal


Home Page Tools (PHP Tools)" publicly on June 8, 1995.

• Zeev Suraski and Andi Gutmans rewrote the parser in


1997 and formed the base of PHP 3, changing the
language's name to the recursive acronym PHP: Hypertext
Preprocessor

6
History (Cont’d)

• On May 22, 2000, PHP 4, powered by the Zend Engine 1.0,


was released

• On July 13, 2004, PHP 5 was released, powered by the new


Zend Engine II. PHP 5 included new features such as
improved support for object-oriented programming

7
Installation

8
LAMP Installation


The installation of what is known as a "LAMP" system:
Linux, Apache, MySQL and PHP

$ sudo apt-get update


$ sudo apt-get install lamp-server^

• This Link is to help people set up and install a LAMP


https://help.ubuntu.com/community/ApacheMySQLPHP

9
Data Types

10
Data Types
Variables are "containers" for storing information

<?php
$x=5;
$y=6;
$z=$x+$y;
echo $z; // print 11
?>

11
Data Types (Cont’d)


A variable starts with the $ sign, followed by the name of the
variable

A variable name must start with a letter or the underscore
character

A variable name cannot start with a number

A variable name can only contain alpha-numeric characters
and underscores (A-z, 0-9, and _ )

Variable names are case sensitive ($y and $Y are two
different variables)

12
Data Types (Cont’d)


A variable is created the moment you first assign a value to it


Variables in PHP do not have intrinsic types - a variable does
not know in advance whether it will be used to store a
number or a string of characters.


PHP is a Loosely Typed Language
– we did not have to tell PHP which data type the variable is.
– PHP automatically converts the variable to the correct data
type, depending on its value.

13
Data Types (Cont’d)

• String
• Integer
• Floating point numbers
• Boolean
• Array
• Object
• NULL

14
Data Types – String

• A string is a sequence of characters, like "Hello world!".

• A string can be any text inside quotes. You can use single
or double quotes

<?php
$x = "Hello world!";
echo $x;
echo "<br>";
?>
15
Data Types - Integer

• An integer is a number without decimals.

• An integer cannot contain comma or blanks

• An integer must not have a decimal point

• An integer can be either positive or negative

16
Data Types – Integer (Cont’d)

Integers can be specified in three formats:


– decimal (10-based)
– hexadecimal (16-based - prefixed with 0x)
– octal (8-based - prefixed with 0)

Note: The PHP var_dump() function returns the data type


and value of variables:

17
Data Types – Integer (Cont’d)

<?php

$x = 5985;
var_dump($x); echo "<br>";
$x = -345; // negative number
var_dump($x); echo "<br>";
$x = 0x8C; // hexadecimal number
var_dump($x); echo "<br>";
$x = 047; // octal number
var_dump($x);
?> 18
Data Types – Floating Point

• A floating point number is a number with a decimal point


or a number in exponential form.

<?php
$x = 10.365; var_dump($x); echo "<br>";
$x = 2.4e3; var_dump($x); echo "<br>";
$x = 8E-5; var_dump($x);
?>

19
Data Types - Boolean

• Booleans can be either TRUE or FALSE.


• Booleans are often used in conditional testing.

$x=true;
$y=false;

20
Data Types - Array

An array stores multiple values in one single variable

<?php
$cars=array("Volvo","BMW","Toyota");
// OR
$cars[0]="Volvo"; $cars[1]="BMW"; $cars[2]="Toyota";
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] .".";
$arrlength=count($cars);
?>

21
Data Types – Associative Array

Associative arrays are arrays that use named keys that


you assign to them.

<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
// OR
$age['Peter']="35"; $age['Ben']="37"; $age['Joe']="43";
echo "Peter is " . $age['Peter'] . " years old.";
?>

22
Data Types - Object

An object is a data type which stores data and
information on how to process that data.


In PHP, an object must be explicitly declared.


First we must declare a class of object. For this, we use
the class keyword. A class is a structure that can contain
properties and methods.

23
Data Types – Object (Cont’d)

<?php

class Car
{
var $color;
function Car($color="green") { $this->color = $color; }
function what_color() { return $this->color; }
}
// instantiate one object
$object = new Car("white");
?>
24
Data Types - NULL

• The special NULL value represents that a variable has no


value. NULL is the only possible value of data type NULL.

• The NULL value identifies whether a variable is empty or


not. Also useful to differentiate between the empty string
and null values of databases.

<?php
$x="Hello world!";
$x=null;
?>
25
Control Structure

26
Conditional Statements

Very often when you write code, you want to perform
different actions for different decisions. You can use
conditional statements in your code to do this.

In PHP we have the following conditional statements
– if statement
– if...else statement
– if...elseif....else statement
– switch statement

27
The If Statement
The if statement is used to execute some code only if a
specified condition is true.

28
The If...Else Statement
Use the if....else statement to execute some code if a
condition is true and another code if the condition is
false.

29
The ElseIf Statement
Use the if....elseif...else statement to select one of several
blocks of code to be executed.

30
The Switch Statement
Use the switch statement to select one of many blocks
of code to be executed.

31
The Switch Statement (Cont’d)

32
Loops

Loops in PHP are used to execute the same block of code
a specified number of times.

PHP supports following four loop types.
– for
– while
– do .. while
– foreach

33
While Loop
The while loop executes a block of code as long as the
specified condition is true.

34
Do.. While Loop
The do...while loop will always execute the block of code
once, it will then check the condition, and repeat the loop
while the specified condition is true.

35
For Loop
The for loop is used when you know in advance how
many times the script should run.

36
For Loop (Cont’d)

37
Foreach Loop
The foreach loop works only on arrays, and is used to
loop through each key/value pair in an array.

38
Functions 39
Functions


Besides the built-in PHP functions, we can create our own
functions.

A function is a block of statements that can be used
repeatedly in a program.

A function will not execute immediately when a page
loads.

A function will be executed by a call to the function.

40
Functions (Cont’d)


A user defined function declaration starts with the word
"function"

A function name can start with a letter or underscore (not
a number).

Function names are NOT case-sensitive.

Information can be passed to functions through
arguments. An argument is just like a variable.

To let a function return a value, use the return statement:

41
Functions (Cont’d)

42
Default Argument Value

The following example shows how to use a default


parameter.

function sum($x = 3,$y = 5) {


$z=$x+$y;
return $z;
}
echo sum()
echo sum(3,7)
echo sum(5)
43
Global Variables

44
Local and Global Scope

• A variable declared outside a function has a GLOBAL SCOPE and can


only be accessed outside a function.

• A variable declared within a function has a LOCAL SCOPE and can


only be accessed within that function.

45
Local and Global Scope (Cont’d)

46
Local and Global Scope (Cont’d)

47
Local and Global Scope (Cont’d)

• The global keyword is used to access a global variable from within a


function.
• To do this, use the global keyword before the variables (inside the
function)

48
Post & Get

49
POST & GET

• Several predefined variables in PHP are "superglobals",


which means they are available in all scopes throughout a
script.

• There is no need to do global $variable; to access them


within functions or methods.

• The PHP superglobals $_GET and $_POST are used to


collect form-data.

50
POST & GET (Cont’d)

• Both GET and POST create an array.

• This array holds key/value pairs, where keys are the


names of the form controls and values are the input data
from the user.

51
POST
$_POST is an array of variables passed to the current
script via the HTTP POST method.

52
POST (Cont’d)

53
POST (Cont’d)

54
POST (Cont’d)

55
GET
$_GET is an array of variables passed to the current script
via the URL parameters.

56
GET (Cont’d)

http://www.w3schools.com/php/welcome_get.php?
name=user_name&email=user_email

57
Cookies & Sessions

58
PHP 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

• With PHP, you can both create and retrieve cookie values.

59
How to Create a Cookie?

• The setcookie() function is used to set a cookie.


• The setcookie() function must appear BEFORE the
<html> tag.

60
How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie


value.

61
How to Delete a Cookie?

When deleting a cookie you should assure that the


expiration date is in the past

62
PHP Sessions

The web server does know not when you start the
application and when you end because the HTTP address
doesn't maintain state.


A PHP session solves this problem by allowing you to
store user information on the server for later use (i.e.
username, shopping items, etc).


Session variables hold information about one single user,
and are available to all pages in one application.

63
PHP Sessions (Cont’d)


Session information is temporary and will be deleted
after the user has left the website.


Sessions work by creating a unique id (UID) for each
visitor and store variables based on this UID. The UID is
either stored in a cookie or is propagated in the URL.

64
Starting a PHP Session

Before you can store user information in your PHP
session, you must first start up the session.


The session_start() function must appear BEFORE the
<html> tag

65
Storing a Session Variable

66
Storing a Session Variable

67
Destroying a Session

68
MySql

69
MySql

• PHP will work with virtually all database software,


including Oracle and Sybase but most commonly used is
freely available MySQL database.

• Using PHP, You can Create DB/tables , Insert and select


records if you have these permissions on the database.

• Download and install a latest version of MySQL.

70
MySql (Cont’d)

• Create database called my_db.

• Create database user guest with password abc123.

• Before we can access data in a database, we must open a


connection to the MySQL server. To open the connection
use mysqli_connect() function.

• The connection will be closed automatically when the


script ends. To close the connection before, use the
mysqli_close() function:
71
MySql (Cont’d)

<?php
// Create connection
$con=mysqli_connect("localhost","guest","abc123","my_db");

// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " mysqli_connect_error();
}
mysqli_close($con);
?>
72
MySql (Cont’d)

<?php
$con=mysqli_connect("localhost","guest","abc123","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
73
?>
Include Files 74
Include Files
• The include (or require) statement takes all the
text/code/markup that exists in the specified file and copies it
into the file that uses the include statement.

• Including files is very useful when you want to include the same
PHP, HTML, or text on multiple pages of a website.

• The include and require statements are identical, except upon


failure:
– require will produce a fatal error (E_COMPILE_ERROR) and stop
the script
– include will only produce a warning (E_WARNING) and the script
will continue
75
Include Files (Cont’d)

76
Include Files (Cont’d)

77
Include

78
Include vs Require

79
Include vs Require (Cont’d)

The echo statement will not be executed because the script execution
dies after the require statement returned a fatal error:

80
Include Once

● The include_once statement includes and evaluates the specified


file during the execution of the script.
● This is a behavior similar to the include statement, with the only
difference being that if the code from a file has already been
included, it will not be included again. (require_once do the same)
<?php
include_once "a.php"; // this will include a.php
include_once "a.php"; // this won't
?>

81
References


W3Schools
http://www.w3schools.com/


Lynda
http://www.lynda.com/MySQL-tutorials/PHP-
MySQL-Essential-Training/119003-2.html

82
Thank
You
83

You might also like