Module-IV-PHP
Introduction to PHP
Introduction to the structure of PHP
Variables, Operators, Variable Typing, Constants, Predefined
constants,
Functions, variable scope
Expression and Control Flow-Conditionals, Looping,
Implicit and Explicit casting,
PHP dynamic linking - Functions and Objects
Including and Requiring Files,
Objects – Arrays-
Practical PHP - Date and Time functions, File Handling –Form
Handling- Regular Expression - PHP validation and Error
handling.
Introduction
PHP is a server scripting language and is a powerful tool for making
dynamic and interactive Web pages quickly.
PHP written in the C by Rasmus Lerdorf in 1994 and originally
stood for "Personal Home Page“
Zeev Suraski and Andi Gutmans rewrote the parser in 1997 and
formed the base of PHP 3 (Zend engine in 1999)
PHP is a widely used, free, and efficient alternative to competitors
like Microsoft's ASP.
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.
PHP takes most of its syntax from C, Java, and Perl.
What is a PHP File?
PHP files can contain text, HTML, CSS, JavaScript, and PHP
code.
PHP code are executed on the server, and the result is returned
to the browser as plain HTML.
PHP files have extension ".php“.
With PHP you are not limited to output HTML. You can output
images, PDF files, and even Flash movies. You can also output any
text, such as XHTML and XML,JSON.
It is powerful enough to be at the core of the biggest blogging
system on the web (WordPress)!
It is deep enough to run the largest social network (Facebook)!
PHP can do
generate dynamic page content
create, open, read, write, delete, and close files on the server
collect form data
send and receive cookies
add, delete, modify data in your database
used to control user-access
encrypt data
Why PHP?
PHP runs on various platforms (Windows, Linux, Unix,
Mac OS X, etc.)
PHP is compatible with almost all servers used today
(Apache, IIS, etc.)
PHP supports a wide range of databases.
PHP is free. Download it from the official PHP resource:
www.php.net
PHP is easy to learn and runs efficiently on the server side.
How it works?
WEB Gets Page
SERVER
<HTML>
<?php echo ‘hello’; ?>
HTTP Request
(url) </HTML>
Interprets the PHP code
Server response
<HTML>
<B>Hello</B>
</HTML>
CLIENT
Browser creates
the web page
Basic Syntax
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>
<html> <body>
<h1>My first PHP page</h1>
<?php Don’t give space
echo "Hello World!<br>";
echo "Introduction", " to". " PHP"; comma & dot for concatenation
?> Don’t give space
</body> </html>
Type program Notepad
Save program c:\xampp\htdocs\basics.php
In Lab:\var\www\html\basics.php
Run in web browser http://localhost/basics.php
Comments
<?php
// This is a single line comment
# This is also a single line comment
/*
This is a multiple lines comment block
that spans over more than
one line
*/
?>
Case Sensitivity
In PHP, all user-defined However; in PHP, all variables are
functions, classes, and case-sensitive.
keywords (e.g. if, else, while, <?php
echo, etc.) are NOT case- $color="red";
sensitive. echo "My car is " . $color . "<br>";
<?php echo "My pen is " , $COLOR;
ECHO "Hello World!<br>"; echo "My boat is " . $coLOR;
echo "Hello World!<br>"; ?>
EcHo "Hello World!<br>";
?> Output:
My car is red
Error : Undefined variable
Rules for PHP variables
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).
Note:When you assign a text value to a variable, put quotes
around the value. Eg:$color=“red”
PHP is a Loosely Typed Language
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
<?php
$txt="Hello world!";
$x=5;
$y=10.5;
?>
In the example above, notice that 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.
In other languages such as C, C++, and Java, the programmer must
declare the name and type of the variable before using it.
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
<?php A variable declared outside a
$x=5; // global scope function has a GLOBAL SCOPE
and can only be accessed outside a
function myTest() { function.
$y=10; // local scope
echo "<p>Test variables inside the function:</p>";
echo "Variable x is: $x";
A variable declared within a
echo "<br>"; function has a LOCAL SCOPE
echo "Variable y is: $y"; and can only be accessed within
} that function.
myTest();
echo "<p>Test variables outside the function:</p>";
echo "Variable x is: $x";
echo "<br>";
echo "Variable y is: $y";
Output
Notice: Undefined variable: x in
\var\www\html\basics.php on line 28
Variable x is:
Variable y is: 10
Test variables outside the function:
Variable x is: 5
Notice: Undefined variable: y in
\var\www\html\basics.php on line 38
Variable y is:
The global Keyword
The global keyword is used to PHP also stores all global variables in
access a global variable from an array called $GLOBALS[index]. The
within a function. index holds the name of the variable.
<?php This array is also accessible from
within functions and can be used to
$x=5; update global variables directly.
$y=10;
<?php
function myTest() { $x=5;
global $x,$y; $y=10;
$y=$x+$y; function myTest() {
} $GLOBALS['y']=
$GLOBALS['x']+$GLOBALS['y'];
myTest(); }
echo $y; // outputs 15 myTest();
?> echo $y; // outputs 15
?>
The static Keyword
<?php Normally, when a function is
function myTest() { completed/executed, all of its
static $x=0; variables are deleted. However,
sometimes we want a local variable
echo $x;
NOT to be deleted. We need it for a
$x++; further job.
}
Then, each time the function is called,
myTest();
that variable will still have the
myTest(); information it contained from the last
myTest(); time the function was called.
Note: The variable is still local to the
?> function.
echo and print Statements
There are some differences between echo and print:
echo - can output one or more strings
print - can only output one string, and returns always 1
Tip: echo is marginally faster compared to print as echo does not return
any value.
echo and print is a language construct, and can be used with or without
parentheses: echo or echo() and print or print().
Example:
echo "This", " string", " was”. " made", " with multiple parameters.";
echo "Study PHP at $txt2";
print "Study PHP at $txt2";
Data types
String, Integer, Floating point numbers, Boolean, Array, Object, NULL.
Examples:
$x = "Hello world!";
$x = 'Hello world!';
$x = 5985; var_dump($x); int(5985)
$x = -345; // negative number
$x = 0x8C; // hexadecimal number
$x = 047; // octal number
$x = 10.365; $x = 2.4e3;
$x=true; $y=false; The PHP var_dump() function
$x=null; returns the data type and value of
variables.
Settype
In PHP, Variable type can be changed by Settype
Settype
Syntax:
settype(Variablename, “newDataType”);
E.g.
$pi = 3.14 //float
settype($pi,”string”); //now string – “3.14”
settype($pi,”integer”);// now integer - 3
Settype & Gettype
In PHP, Variable type and can know by Gettype.
Syntax:
gettype(Variablename);
E.g.
$pi = 3.14; //float
print gettype($pi);
Print “---$pi <br>”;
settype($pi,”string”);
print gettype($pi);
Print “---$pi <br>”;
settype($pi,”integer”);
print gettype($pi);
Print “---$pi <br>”;
Type Casting
To change type through casting you indicate the name of a data
type, in parentheses, in front of the variable you are copying.
Eg: $newvar=(integer) $originalvar
It creates a copy of the $originalvar variable, with a specific type
(int) and a new name $newvar.
The $originalvar variable will still be available, and will be its
original type;
$newvar is a completely new variable.
Casting a Variable
1: <html>
2: <head>
3: <title> Casting a variable</title>
4: </head>
5: <body>
6: <?php
7: $undecided = 3.14;
8: $holder = ( double ) $undecided;
9: print gettype( $holder ) ; // double
10: print " -- $holder<br>"; // 3.14
11: $holder = ( string ) $undecided;
12: print gettype( $holder ); // string
13: print " -- $holder<br>"; // 3.14
14: $holder = ( integer ) $undecided;
15: print gettype( $holder ); // integer
16: print " -- $holder<br>"; // 3
17: $holder = ( double ) $undecided;
18: print gettype( $holder ); // double
19: print " -- $holder<br>"; // 3.14
20: $holder = ( boolean ) $undecided;
21: print gettype( $holder ); // boolean
22: print " -- $holder<br>"; // 1
23: ?>
24: </body>
25: </html>
We never actually change the type of $undecided, which remains a
double throughout. Where we use the gettype() to determine the
type of $undecided.
Variable Variables
A variable variable creates a new variable and assigns the
current value of a variable as its name.
Example:
<?php
$a = 'hello';
$$a = 'world';
echo "$a $hello";
echo $hello;
?>
Constant
Constants are automatically global across the entire script.
The first parameter defines the name of the constant,
the second parameter defines the value of the constant,
and the optional third parameter specifies whether the constant name
should be case-insensitive. Default is false.
<?php
define("GREETING", "Welcome", true);
echo GREETING; // Welcome
echo "<br>";
echo greeting; //Welcome greeting is printed when sets false
?>
Operators
$txt1 = "Hello“ ;
$txt2 = $txt1 . " world!“; "Hello world!“ Concatenation
$txt1 = "Hello“;
$txt1 .= " world!“; "Hello world!“ Concatenation assignment
$x=100; $y="100";
($x == $y); // returns true because values are equal
($x === $y); // returns false because types are not equal
($x != $y); // returns false because values are equal // $x <>
$y
($x !== $y); // returns true because types are not equal
Defining Function
Syntax:
function functionName() {
code to be executed;
}
Example:
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
Default argument
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
User Defined Functions
Function with argument:
Formal Argument
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br />";
} Fn. Call with Actual Argument
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege"); Output:
echo "My brother's name is ";
writeName("Stale"); My name is Kai Jim Refsnes.
?> My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
User Defined Functions
Function with arguments & return value:
<?php
function calculateAmt($cost, $num)
{
return ($cost * $num);
}
$price=10;
$tot=5;
Echo “ Total Amount “, calculateAmt($price, $tot);
?>
Output:
Total Amount 50
User Defined Functions
Fn. Call by Ref.:
<?php
$cost = 20.99;
$tax = 0.0575;
function calculateCost(&$cost, $tax) Output:
{
// Modify the $cost variable (bfr fn call) Cost is 20.99
$cost = $cost + ($cost * $tax); Tax is 5.75
// Perform some random change to the (aft fn call) Cost is: 22.20
$tax variable.
$tax += 4;
}
Echo “(bfr fn call) Cost is $cost <br>”;
calculateCost($cost, $tax);
Echo "Tax is $tax*100 <br>";
Echo “(aft fn call) Cost is: $cost”;
?>
String Functions
The count_chars(string,mode ) function returns how many times an
ASCII character occurs within a string and returns the information.
Output:
Array
E.g: (
[32] => 1
[33] => 1
<?php [72] => 1
$str = "Hello World!"; [87] => 1
print_r(count_chars($str,1)); [100] => 1
?> [101] => 1
[108] => 3
[111] => 2
[114] => 1
)
String Functions
The different return modes are:
0 - an array with the ASCII value as key and number of
occurrences as value
1 - an array with the ASCII value as key and number of
occurrences as value, only lists occurrences greater than zero
2 - an array with the ASCII value as key and number of
occurrences as value, only lists occurrences equal to zero are
listed
3 - a string with all the different characters used
4 - a string with all the unused characters
String Functions
The explode(separator, string, limit) function breaks a string into an
array.
Output:
Array
(
E.g: [0] => Hello
[1] => world.
[2] => It's
<?php
[3] => a
$str = "Hello world. It's a beautiful day.";
[4] => beautiful
print_r (explode(" ",$str));
[5] => day.
?>
)
String Functions
The implode(separator,array ) & join(separator,array ) function
returns a string from the elements of an array.
E.g: Output:
Hello World! Beautiful Day!
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
String Functions
The ltrim(string,charlist) & rtrim(string,charlist) function will remove
whitespaces or other predefined character from the left and right side of a string respectively.
The str_shuffle(string) function randomly shuffles all the characters of a string.
String Functions
The strlen(string) function returns the length of a string.
E.g: Output:
<?php Length = 12
$a= “hello World!”;
echo “Length = “, strlen($a);
?>
String Functions
The strrev(string) reverses the given string.
E.g: Output:
<?php Reverse of “hello World!” is !dlroW olleh
$a= “hello World!”;
echo “Reverse of \”$a\” is “, strrev($a);
?>
String Functions
The strtoupper(string) converts to upper case character
The strtolower(string) converts to lower case character
E.g: Output:
<?php
$a= “hello World!”; Upper of “hello World!” is HELLO
echo “Upper of \”$a\” is “, strtoupper($a); WORLD!
echo “Lower of \”$a\” is “, strtolower($a); Lower of “hello World!” is hello world
?>
String Functions
The strpos(string,exp) returns the numerical position of first appearance
of exp.
The strrpos(string,exp) returns the numerical position of last appearance
of exp.
strripos() - Finds the position of the last occurrence of a string inside another
string (case-insensitive)
E.g: Output:
<?php 2
$a= “hello World!”; 10
echo strpos($a,”l”),”<br>”;
echo strrpos($a,”l”);
?>
String Functions
The substr(string,start,length) function returns a sub string of the size
“length” from the position of “start”.
E.g: Output:
<?php lo
$a= “hello World!”; ld!
echo substr($a,3,2); l
echo substr($a,-3); hello Wor
echo substr($a,-3,1);
echo substr($a,0,-3);
?>
String Functions
The substr_count(string,substr) counts number of times a sub string
occurred in given string.
E.g: Output:
<?php 2
$a= “hello Worlod!”;
echo substr_count($a,”lo”);
?>
String Functions
The substr_replace(string,replacement,start,len) replaces a
portion of a string with a replacement string, beginning the substitution at a specified
starting position and ending at a predefined replacement length.
E.g: Output:
<?php heaaorld!
$a= “hello World!”;
echo substr_replace($a,”aa”,2,5);
?>
String Functions
The ucfirst(string) converts the first character to upper case.
The ucwords(string) converts the first character of each word to upper case.
E.g: Output:
<?php Hello world!
$a= “hello world!”; Hello World!
echo ucfirst($a),”<br>”;
echo ucwords($a);
?>
String Functions
The parse_str(string,arr) function parses a query string into variables.
E.g: Output:
<?php 23
parse_str("id=23&name=Kai Jim"); Kai Jim
echo $id."<br />";
echo $name;
?>
String Functions
The str_replace(find,replace,string,count ) function replaces some
characters with some other characters in a string.
Note: str_ireplace() – for case insensitive
Output:
E.g:
Array
<?php (
$arr = array("blue","red","green","yellow"); [0] => blue
print_r(str_ireplace("RED","pink",$arr,$i)); [1] => pink
echo "Replacements: $i"; [2] => green
?> [3] => yellow
)
Replacements: 1
String Functions
The str_pad(string,length,padchar,padtype) function pads a string to a
new length.
E.g:
Output:
<?php .........Hello World
$str = "Hello World";
echo str_pad($str,20,".",STR_PAD_LEFT);
?>