0% found this document useful (0 votes)
6 views84 pages

PHP I Slides

Php overview

Uploaded by

Land lord
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
6 views84 pages

PHP I Slides

Php overview

Uploaded by

Land lord
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 84

Introduction to PHP

● “PHP is a server-side scripting language


designed specifically for the Web. Within an
HTML page, you can embed PHP code that will
be executed each time the page is visited. Your
PHP code is interpreted at the Web server and
generates HTML or other output that the visitor
will see” (“PHP and MySQL Web
Development”, Luke Welling and Laura
Thomson, SAMS)
Introduction to PHP
Introduction to PHP
“PHP is a server-side scripting language
designed specifically for the Web. Within an
HTML page, you can embed PHP code that will
be executed each time the page is visited. Your
PHP code is interpreted at the Web server and
generates HTML or other output that the visitor
will see”

(“PHP and MySQL Web Development”, Luke


Welling and Laura Thomson, SAMS)
PHP Introduction

PHP is a recursive acronym for “PHP: Hypertext


Preprocessor” -- It is a widely-used open source
general-purpose scripting language that is
especially suited for web development and can
be embedded into HTML.
PHP Introduction

> PHP is a server-side scripting language


> PHP scripts are executed on the server
> PHP supports many databases (MySQL,
Informix, Oracle, Sybase, Solid, PostgreSQL,
Generic ODBC, etc.)
> PHP is open source software
> PHP is free to download and use
PHP Introduction

> PHP runs on different platforms (Windows,


Linux, Unix, etc.)
> PHP is compatible with almost all servers used
today (Apache, IIS, etc.)
> PHP is FREE to download from the official PHP
resource: www.php.net
> PHP is easy to learn and runs efficiently on the
server side
(Good) Topics about PHP
Open-source
Easy to use ( C-like and Perl-like syntax)
Stable and fast
Multiplatform
Many databases support
Many common built-in libraries
Pre-installed in Linux distributions
How PHP generates
HTML/JS Web pages
Client
Browser

4
1
3 PHP
module
Apache
2

1: Client from browser send HTTP request (with POST/GET


variables)
2: Apache recognizes that a PHP script is requested and sends
the request to PHP module
3: PHP interpreter executes PHP script, collects script output
and sends it back
4: Apache replies to client using the PHP script output as HTML
output
PHP Introduction

Instead of lots of commands to output HTML (as


seen in C or Perl), PHP pages contain HTML with
embedded code that does "something" (like in the
next slide, it outputs "Hi, I'm a PHP script!").

The PHP code is enclosed in special start and


end processing instructions <?php and ?> that
allow you to jump into and out of "PHP mode."
PHP Introduction
PHP Introduction

PHP code is executed on the server, generating


HTML which is then sent to the client. The client
would receive the results of running that script, but
would not know what the underlying code was.

A visual, if you please...


PHP Introduction
How PHP Pages are Accessed
and Interpreted
Client: Web browser Web server
1.Form submitted with a submit button
2.----- Action sends a request to the php file in server
3. Receive the request, find the file,
and read it
4. Execute the PHP commands
5. Send the results back
6. ---- results returned as HTML file
7. Web browser renders the HTML file, displaying the results
PHP Getting Started

On windows, you can download and install


XAMPP. With one installation and you get an
Apache webserver, database server and php.

https://www.apachefriends.org/download.html

On mac, you can download and install MAMP.


http://www.mamp.info/en/index.html
What is PHP (cont’d)
Interpreted language, scripts are parsed at run-
time rather than compiled beforehand
Executed on the server-side
Source-code not visible by client
‘View Source’ in browsers does not display the PHP code
Various built-in functions allow for fast
development
Compatible with many popular databases
What does PHP code look like?
Structurally similar to C/C++
Supports procedural and object-oriented paradigm
(to some degree)
All PHP statements end with a semi-colon
Each PHP script must be enclosed in the reserved
PHP tag

<?php

?>
PHP Hello World

Above is the PHP source code.


PHP Hello World

It renders as HTML that looks like this:


PHP Hello World

This program is extremely simple and you really


did not need to use PHP to create a page like this.
All it does is display: Hello World using the PHP
echo() statement.

Think of this as a normal HTML file which


happens to have a set of special tags available to
you that do a lot of interesting things.
PHP Comments
In PHP, we use // to
make a single-line
comment or /* and */ to
make a large comment
block.
PHP Variables
> Variables are used for storing values, like text
strings, numbers or arrays.
> When a variable is declared, it can be used over
and over again in your script.
> All variables in PHP start with a $ sign symbol.
> The correct way of declaring a variable in PHP:
PHP Variables

> In PHP, a variable does not need to be declared


before adding a value to it.
> In the example above, you see that you do 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.
PHP Variables

> A variable name must start with a letter or an


underscore "_" -- not a number
> A variable name can only contain alpha-numeric
characters, underscores (a-z, A-Z, 0-9, and _ )

A variable name should not contain spaces. If a
variable name is more than one word, it should be
separated with an underscore ($my_string) or with
capitalization ($myString)
Variables (I)

To use or assign variable $ must be present before the
name of the variable

The assign operator is '='

There is no need to declare the type of the variable

the current stored value produces an implicit type-casting
of the variable.

A variable can be used before to be assigned
$A = 1;
$B = 2;
$C = ($A + $B); // Integer sum
$D = $A . $B; // String concatenation
echo $C; // prints 3
echo $D;// prints 12
PHP Variables Scope
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the
variable can be referenced/used.

PHP has three different variable scopes:


local
global
static
GLOBAL SCOPE
A variable declared outside a function has a GLOBAL SCOPE and can only be
accessed outside a function:

<?php
$x = 5; // global scope

function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

echo "<p>Variable x outside function is: $x</p>";


?>

Output:
Variable x inside function is:
Variable x outside function is: 5
LOCAL SCOPE
A variable declared within a function has a LOCAL SCOPE and can only be accessed
within that function:

<?php
function myTest() {
$x = 5; // local scope
echo "Variable x inside function is: $x";
}
myTest();

// using x outside the function will generate an error


echo "Variable x outside function is: $x";
?>

Output:
Variable x inside function is: 5
Notice: Undefined variable: x in C:\xampp\
htdocs\square.php on line 12
Variable x outside function is:
global keyword
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):
<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

Output:
15
Global Array
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds
the name of the variable. This array is also accessible from within functions and can be
used to update global variables directly.

<?php

$x = 5;
$y=15;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo "<p>Variable x outside function is: $y</p>";
?>
myTest();
echo $y; // outputs 20
?>
Output:
20
Static Scope
Normally, when a function is completed/executed, all of its variables are deleted.
However, sometimes we want a local variable NOT to be deleted. We need it for a
further job

<?php
Function mytest()
{
Static $x=0;
echo $x;
$x++;
}
mytest();
mytest();
mytest();
?>

Output:
0
1
2
Echo
The PHP command ‘echo’ is used to output the
parameters passed to it
The typical usage for this is to send data to the
client’s web-browser
Syntax
void echo (string arg1 [, string argn...])
In practice, arguments are not passed in
parentheses since echo is a language construct
rather than an actual function
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable

echo $bar; // Outputs Hello


echo $foo,$bar; // Outputs 25Hello
echo “5x5=”,$foo; // Outputs 5x5=25
echo “5x5=$foo”; // Outputs 5x5=25
echo ‘5x5=$foo’; // Outputs 5x5=$foo
?>

Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as “\n”
or “\\”)
PHP Echo

PHP echo is a language construct not a function, so you don't
need to use parenthesis with it. But if you want to use more than
one parameters, it is required to use parenthesis.
The syntax of PHP echo is given below:
void echo ( string $arg1 [, string $... ] )

PHP echo statement can be used to print string, multi line
strings, escaping characters, variable, array etc.
PHP echo: printing string
PHP echo and print Statements


echo and print are more or less the same. They
are both used to output data to the screen.

The differences are small: echo has no return
value while print has a return value of 1 so it
can be used in expressions. echo can take
multiple parameters (although such usage is
rare) while print can take one argument. echo is
marginally faster than print.
PHP Variable
PHP Variable: Sum of two variables
PHP Variable: case sensitive
PHP Variable: Rules

PHP variables must start with letter or underscore only.

PHP variable can't be start with numbers and special symbols.

File: variablevalid.php
<?php
$a="hello";//letter (valid)
$_b="hello";//underscore (valid)
echo "$a <br/> $_b";
?>

Output:
hello hello
PHP Data Types

Variables can store data of different types

PHP supports the following data types:

String

Integer

Float (floating point numbers - also called double)

Boolean

Array

Object

NULL

Resource
PHP 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!";
$y = 'Hello world!';
echo $x;
echo "<br>"; echo $y;
?>
PHP Integer
An integer data type is a non-decimal number between -2,147,483,648 and
2,147,483,647.

Rules for integers:


An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in three formats: decimal (10-based),
hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed
with 0)
In the following example $x is an integer. The PHP var_dump() function
returns the data type and value:
<?php
$x = 5985;
var_dump($x);
?>
PHP Float

A float (floating point number) is a number with a


decimal point or a number in exponential form.
In the following example $x is a float.
<?php
$x = 10.365;
var_dump($x);
?>
Output:
float(10.365)
PHP Boolean


A Boolean represents two possible states:
TRUE or FALSE.

$x = true;
$y = false;

Booleans are often used in conditional testing.
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP
var_dump() function returns the data type and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
Output:
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW"
[2]=> string(6) "Toyota" }
PHP 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:

<?php
class Car {
function Car() {
$this->model = "VW";
}}
// create an object
$herbie = new Car();
// show object properties
echo $herbie->model; ?>
PHP NULL Value

Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to
it.
Note: If a variable is created without a value, it is automatically assigned
a value of NULL.
Variables can also be emptied by setting the value to NULL:
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
Output
NULL
PHP Resource

The special resource type is not an actual data type. It is the
storing of a reference to functions and resources external to
PHP(such as database connections).

A common example of using the resource data type is a
database call.

The following code shows how to get the database resource
identifier by requesting the MySQL connection. In this code, the
database information is specified for the mysqli_connect() and it
returns MySQL connection object as a resource identifier.

$conn = mysqli_connect(localhost,"root","admin","animals");
While working with files, we need to get the file resource
identifier. with the reference to this identifier, we can perform
the write, append and more file manipulation operations. The
following PHP code is used to create a file resource object
reference.

$fp = fopen("index.php",'r');
PHP String

They are sequences of characters, like "PHP supports string
operations".

Following are valid examples of string

$string_1 = "This is a string in double quotes“;

$string_2 = "This is a somewhat longer, singly quoted string“;

$string_39 = "This string has thirty-nine characters";

$string_0 = ""; // a string with zero characters

Singly quoted strings are treated almost literally, whereas
doubly quoted strings replace variables with their values as well
as specially interpreting certain character sequences.
PHP String
<?php $variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n"; print($literally);
?>
This will produce the following result −
My $variable will not print!\n
My name will print
String Concatenation Operator


To concatenate two string variables together,
use the dot (.) operator −

<?php $string1="Hello World";
$string2="1234"; echo $string1 . " " .
$string2;

?>

This will produce the following result −

Hello World 1234
strlen() function

The strlen() function is used to find the length of a string.

find the length of our string "Hello world!":

<?php

echo strlen("Hello world!");

?>

This will produce the following result −

12

The length of a string is often used in loops or other functions,
when it is important to know when the string ends. (i.e. in a
loop, we would want to stop the loop after the last character in
the string)
strpos() function

The strpos() function is used to search for a string or character
within a string.

If a match is found in the string, this function will return the
position of the first match. If no match is found, it will return
FALSE.

Let's see if we can find the string "world" in our string −

<?php echo strpos("Hello world!","world");?>

This will produce the following result −

6

As you see the position of the string "world" in our string is
position 6. The reason that it is 6, and not 7, is that the first
position in the string is 0, and not 1.
Strings (I)

A string is a sequence of chars
$stringTest = “this is a sequence of chars”;
echo $stringTest[0]; output: t
echo $stringTest; output: this is a sequence of chars

A single quoted strings is displayed “as-is”
$age = 37;
$stringTest = 'I am $age years old'; // output: I am $age years old
$stringTest = “I am $age years old”; // output: I am 37 years old

Concatenation
$conc = ”is “.”a “.”composed “.”string”;
echo $conc; // output: is a composed string
$newConc = 'Also $conc '.$conc;
echo $newConc; // output: Also $conc is a composed string
PHP Concatenation
> The concatenation operator (.) is used to put
two string values together.
> To concatenate two string variables together,
use the concatenation operator:
PHP Concatenation

The output of the code on the last slide will be:

If we look at the code you see that we used the


concatenation operator two times. This is because
we had to insert a third string (a space character),
to separate the two strings.
Concatenation
Use a period to join strings into one.
<?php
$string1=“Hello”;
$string2=“PHP”;
$string3=$string1 . “ ” . $string2;
Print $string3;
?>

Hello PHP
PHP Operators

Operators are used to operate on values. There


are four classifications of operators:

> Arithmetic
> Assignment
> Comparison
> Logical
PHP Operators
PHP Operators
PHP Operators
Comparison Operator

===

Identical

$x === $y Returns true if $x is equal to $y, and
they are of the same type

!==

Not identical

$x !== $y Returns true if $x is not equal to $y,
or they are not of the same type
PHP Operators
PHP Increment / Decrement
Operators

The PHP increment operators are used to
increment a variable's value.

The PHP decrement operators are used to
decrement a variable's value.

Operator Name Description

++$x Pre-increment Increments $x by one, then returns $x

$x++ Post-increment Returns $x, then increments $x by one

--$x Pre-decrement Decrements $x by one, then returns $x

$x-- Post-decrement Returns $x, then decrements $x by one
PHP Array Operators


The PHP array operators are used to compare
arrays.

Operator Name Example Result

+ Union $x + $y Union of $x and $y

== Equality $x == $y Returns true if $x and $y have the same
key/value pairs

=== Identity $x === $y Returns true if $x and $y have the same
key/value pairs in the same order and of the same types

!= Inequality $x != $y Returns true if $x is not equal to $y

<> Inequality $x <> $y Returns true if $x is not equal to $y

!== Non-identity $x !== $y Returns true if $x is not identical to $y
Example

<!DOCTYPE html>
<html>
<body>
<?php
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
var_dump($x === $y);
?>
</body>
</html>

Output:

bool(false)
Bitwise Operators

& (Bitwise AND) : This is a binary operator i.e.
it works on two operand. Bitwise AND operator
in PHP takes two numbers as operands and
does AND on every bit of two numbers. The
result of AND is 1 only if both bits are 1.

| (Bitwise OR) : This is also binary operator i.e.
works on two operand. Bitwise OR operator
takes two numbers as operands and does OR
on every bit of two numbers. The result of OR is
1 any of the two bits is 1.
Bitwise Operators

^ (Bitwise XOR ) : This is also binary operator
i.e. works on two operand. This is also known
as Exclusive OR operator. Bitwise XOR takes
two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is
1 if the two bits are different.

~ (Bitwise NOT) : This is a unary operator i.e.
works on only one operand. Bitwise NOT
operator takes one number and inverts all bits
of it.
Bitwise Operators

<< (Bitwise Left Shift) : This is a binary
operator i.e. works on two operand. Bitwise Left
Shift operator takes two numbers, left shifts the
bits of the first operand, the second operand
decides the number of places to shift.

Input: First = 5, Second = 1

Explanation: Binary representation of 5 is
0101 . Therefore, bitwise << will shift the bits of
5 one times towards the left (i.e. 01010 )
Bitwise Operators

>> (Bitwise Right Shift) : This is also binary
operator i.e. works on two operand. Bitwise
Right Shift operator takes two numbers, right
shifts the bits of the first operand, the second
operand decides the number of places to shift.

Input: First = 5, Second = 1 Output: The bitwise
>> of both these value will be 2. Explanation:
Binary representation of 5 is 0101 . Therefore,
bitwise >> will shift the bits of 5 one times
towards the right(i.e. 010)
PHP 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...
PHP Conditional Statements
> if statement - use this statement to execute
some code only if a specified condition is true
> if...else statement - use this statement to
execute some code if a condition is true and
another code if the condition is false
> if...elseif....else statement - use this statement
to select one of several blocks of code to be
executed
> switch statement - use this statement to select
one of many blocks of code to be executed
PHP Control Structures

Control Structures: Are the structures within a language
that allow us to control the flow of execution through a
program or script.

Grouped into conditional (branching) structures (e.g.
if/else) and repetition structures (e.g. while loops).

Example if/else if/else statement:

if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}
If ... Else...
If (condition)
<?php
{ If($user==“John”)
{
Print “Hello John.”;
Statements; }
Else
} {
Print “You are not John.”;
}
Else ?>

{
Statement;
No THEN in PHP
}
PHP Conditional Statements
The following example will output "Have a nice
weekend!" if the current day is Friday:
PHP Conditional Statements
Use the if....else statement to execute some code
if a condition is true and another code if a
condition is false.
PHP Conditional Statements

If more than one line


should be executed if a
condition is true/false,
the lines should be
enclosed within curly
braces { }
PHP Conditional Statements

The following example


will output "Have a nice
weekend!" if the current
day is Friday, and "Have
a nice Sunday!" if the
current day is Sunday.
Otherwise it will output
"Have a nice day!":
PHP Conditional Statements
Use the switch statement to select one of many
blocks of code to be executed.
PHP Conditional Statements
For switches, first we have a single expression n
(most often a variable), that is evaluated once.

The value of the expression is then compared with


the values for each case in the structure. If there
is a match, the block of code associated with that
case is executed.

Use break to prevent the code from running into


the next case automatically. The default statement
is used if no match is found.
PHP Conditional Statements
PHP date function

PHP date function is an in-built function that
simplify working with date data types. The PHP
date function is used to format a date or time
into a human readable format. It can be used to
display the date of article was published. record
the last updated a data in a database.
Variables (II)

Function isset tests if a variable is assigned or not
$A = 1;
if (isset($A))
print “A isset”
if (!isset($B))
print “B is NOT set”;


Using $$
$help = “hiddenVar”;
$$help = “hidden Value”;
echo $$help; // prints hidden Value
$$help = 10;
$help = $$help * $$help;
echo $help; // print 100

You might also like