PHP

advertisement
VI B.Tech I Sem A&B
OPEN SOURCE SOFTWARE
UNIT IV
OPEN SOURCE PROGRAMMING LANGUAGES
OPEN SOURCE PROGRAMMING LANGUAGES
Which programming languages are released under open-source licenses thus languages are called as
“Open Source Programming Languages”.
List of open-source programming languages
This is a selected list of open-source programming languages and implementations. Open-source
programming languages are those that are released under open-source licenses.
Title
Language
REXX
LGPL
Ada
Implementation
license
GPL
Regina
GNAT
Ruby MRI
Ruby
Ruby License or GPL
ALGOL 68G
ALGOL 68
GPL
YARV
Ruby
ELLA ALGOL 68
ALGOL 68
JRuby
Ruby
BWK awk
AWK
Public Domain – Crown
Copyright
Custom
Ruby License or BSD
License
CPL/GPL/LGPL
IronRuby
Ruby
Microsoft Public License
gawk
AWK
GPL v.3
Ruby.NET
Ruby
New BSD
mawk
AWK
GPL v.2
Rubinius
Ruby
BSD License
GCC
C/C++/ObjectiveC/ASM/Go
C/C++/Objective-C
GPL
Mac Ruby
Ruby
Ruby License
NCSA license
XRuby
Ruby
GPL v2
Scheme
GPL, LGPL
Chicken
Scheme
BSD License
Erlang
Erlang
GPLv2/MIT X11
License/LGPLv2/MIT
Mozilla
LicensePublic License
ER Public License
Bigloo
Candle
C#, Visual Basic
.NET
Candle
Gambit
Scheme
LGPL/Apache License
Gforth
Forth
GPL v.3
Guile
Scheme
LGPL
Open Firmware
Forth
BSD License
JScheme
Scheme
zlib
Pforth
Forth
Public Domain
BiwaScheme
Scheme
MIT License
Harbour
Harbour
GPL
Kawa
Scheme
MIT License
Glasgow Haskell
Compiler (GHC)
Haskell User's
Gofer System
nhc98
Haskell
BSD License
Racket
Scheme
LGPL
Haskell
BSD License
Scsh
Scheme
BSD License
Haskell
GPL v2
GNU Smalltalk
Smalltalk
GPL v2
Helium
Haskell
GPL
Pharo
Smalltalk
MIT License
Icon
Icon
Public Domain
Squeak
Smalltalk
IcedTea
Java
CSNOBOL4
SNOBOL4
WebKit
JavaScriptCore
SpiderMonkey
JavaScript
Tcl/Tk
Tcl/Tk
Apple Public Source
License/Apache License
Custom
(OLTPC)
Tcl/Tk License
JavaScript
GNU General Public
License
GNU Lesser General
Public License v2.1
MPL/GPL/LGPL
MINT
TRAC
GPL
V8
JavaScript
BSD license
ash
Unix Shell
BSD License
Emacs Lisp
Lisp
GPL v.3
bash
Unix Shell
GPL v.3
EGL
EGL
EPL
ksh93
Unix Shell
CPL
Lua
Lua
MIT License
Clojure
Clojure
Eclipse Public License
Obix
Obix
AGPL
ClojureCLR
Clojure
Eclipse Public License
Perl
Perl
Artistic License or GPL
Clojure-Py
Clojure
Eclipse Public License
PHP
PHP
Clojure
Eclipse Public License
Pike
PHP License (BSD
style)
GPL/LGPL/MPL
ClojureScript
Pike
Scala
Scala
BSD License
Free Poplog
Custom based on
MIT/XFree86
GPL v.2
F#
F#
Apache License
TypeScript
TypeScript
Apache License
SWI-Prolog
POP-11, Common
Lisp, Prolog,
Prolog
Standard ML
Prolog
LGPL
Gc
Go
BSD-style
Opa
Opa
Affero GPL
Rust
Rust
MIT License
Python
Python
Vala
Vala
LGPL
Jython
Python
Dart
Dart
BSD License
IronPython
Python
PSF License (GPL
Compatible)
PSF License (GPL
Compatible)
Microsoft Public License
PyPy
Python
MIT License
Clang/LLVM
Mono
GNU Prolog
UNIT – IV
1
OPEN SOURCE SOFTWARE
PHP is a server-side scripting language designed for web development but also used as a general-purpose programming
language. PHP is now installed on more than 244 million websites and 2.1 million web servers.[2] Originally created by Rasmus
Lerdorf in 1995, the reference implementation of PHP is now produced by The PHP
Group.[3] While PHP originally stood for Personal Home Page, it now stands for PHP:
Hypertext Preprocessor, a recursive acronym.[4]
PHP code is interpreted by a web server with a PHP processor module which generates the
resulting web page: PHP commands can be embedded directly into an HTML source
document rather than calling an external file to process data. It has also evolved to include a
command-line interface capability and can be used in standalone graphical applications.[5]
PHP is free software released under the PHP License, which is incompatible with the GNU
General Public License (GPL) due to restrictions on the usage of the term PHP.[6] PHP can be
deployed on most web servers and also as a standalone shell on almost every operating
system and platform, free of charge.
History
PHP development began in 1994 when the developer Rasmus Lerdorf wrote a series of
Common Gateway Interface (CGI) Perl scripts, which he used to maintain his personal
homepage. The tools performed tasks such as displaying his résumé and recording his
web traffic.[3][8][9] He rewrote these scripts in C for performance reasons, extending them to
add the ability to work with web forms and to communicate with databases and called this
implementation "Personal Home
Page/Forms
Interpreter"
or
PHP/FI. PHP/FI could be used to
build simple, dynamic web
applications.
Lerdorf
initially
announced the release of PHP/FI
as "Personal Home Page Tools
(PHP Tools) version 1.0" publicly
to accelerate bug location and
improve the code, on the
comp.infosystems.www.authoring.cgi Usenet discussion group on June
8, 1995.[10][11] This release already had the basic functionality that PHP
has today. This included Perl-like variables, form handling, and the
ability to embed HTML. The syntax was similar to Perl but was more
limited and simpler, although less consistent. [3] A development team began to form and, after months of work and beta testing,
officially released PHP/FI 2 in November 1997.
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.[3] Afterward, public testing of PHP 3 began, and the official launch came in June
1998. Suraski and Gutmans then started a new rewrite of PHP's core, producing the Zend Engine in 1999.[12] They also founded
Zend Technologies in Ramat Gan, Israel.[3]
On May 22, 2000, PHP 4, powered by the Zend Engine 1.0, was released. [3] As of August 2008 this branch is up to version 4.4.9.
PHP 4 is no longer under development nor will any security updates be released. [13][14]
On July 13, 2004, PHP 5 was released, powered by the new Zend Engine II. [3] PHP 5 included new features such as improved
support for object-oriented programming, the PHP Data Objects (PDO) extension (which defines a lightweight and consistent
interface for accessing databases), and numerous performance enhancements. [15] In 2008 PHP 5 became the only stable version
under development. Late static binding had been missing from PHP and was added in version 5.3.[16][17]
A new major version has been under development alongside PHP 5 for several years. This version was originally planned to be
released as PHP 6 as a result of its significant changes, which included plans for full Unicode support. However, Unicode support
took developers much longer to implement than originally thought, and the decision was made in March 2010 [18] to move the project
to a branch, with features still under development moved to trunk.
Changes in the new code include the removal of register_globals,[19] magic quotes, and safe mode.[13][20] The reason for the
removals was that register_globals had opened security holes by intentionally allowing runtime data injection, and the use of magic
quotes had an unpredictable nature. Instead, to escape characters, magic quotes may be replaced with the addslashes() function,
or more appropriately an escape mechanism specific to the database vendor itself like mysql_real_escape_string() for MySQL.
Functions that will be removed in future versions and have been deprecated in PHP 5.3 will produce a warning if used. [21]
Many high-profile open-source projects ceased to support PHP 4 in new code as of February 5, 2008, because of the GoPHP5
initiative,[22] provided by a consortium of PHP developers promoting the transition from PHP 4 to PHP 5.[23][24]
PHP interpreters are available on both 32-bit and 64-bit operating systems, but on Microsoft Windows the only official distribution is
a 32-bit implementation, requiring Windows 32-bit compatibility mode while using Internet Information Services (IIS) on a 64-bit
Windows platform. Experimental 64-bit versions of PHP 5.3.0 were briefly available for Microsoft Windows, but have since been
removed.
UNIT – I By P.V.Ravikanth, 8019594355
2
OPEN SOURCE SOFTWARE
Implementations
The PHP language was originally implemented as an interpreter, and this is still the most popular implementation. Several
compilers have been developed which decouple the PHP language from the interpreter. Advantages of compilation include better
execution speed, static analysis, and improved interoperability with code written in other languages. [81] PHP compilers of note
include Phalanger, which compiles PHP into Common Intermediate Language (CIL) bytecode, and HipHop, developed at Facebook
and now available as open source, which transforms the PHP Script into C++, then compiles it, reducing server load up to 50% .
PHP source code is compiled on-the-fly to an internal format that can be executed by the PHP engine.[82][83] In order to speed up
execution time and not have to compile the PHP source code every time the web page is accessed , PHP scripts can also be
deployed in executable format using a PHP compiler.
Code optimizers aim to enhance the performance of the compiled code by reducing its size , merging redundant instructions and
making other changes that can reduce the execution time. With PHP, there are often opportunities for code optimization.[84] An
example of a code optimizer is the eAccelerator PHP extension.
Another approach for reducing compilation overhead for PHP servers is using an opcode cache. Opcode caches work by caching
the compiled form of a PHP script (opcodes) in shared memory to avoid the overhead of parsing and compiling the code every time
the script runs. An opcode cache, APC, is planned to be built into an upcoming release of PHP (but not 5.4 [85] as previously
planned [86]).
Opcode caching and code optimization can be combined for best efficiency, as the modifications do not depend on each other (they
happen in distinct stages of the compilation).
Licensing
PHP is free software released under the PHP License, which insists that:[87]
Products derived from this software may not be called "PHP", nor may "PHP" appear in their name, without prior written permission
from group@php.net. You may indicate that your software works in conjunction with PHP by saying "Foo for PHP" instead of calling
it "PHP Foo" or "phpfoo".
This restriction on use of the name PHP makes it incompatible with the GNU General Public License (GPL).
Development and community
PHP includes free and open source libraries with the core build. PHP is a fundamentally Internet-aware system with modules built
in for accessing File Transfer Protocol (FTP) servers, many database servers, embedded SQL libraries such as embedded
PostgreSQL, MySQL, Microsoft SQL Server and SQLite, LDAP servers, and others. Many functions familiar to C programmers
such as those in the stdio family are available in the standard PHP build.[89]
PHP allows developers to write extensions in C to add functionality to the PHP language. These can then be compiled into PHP or
loaded dynamically at runtime. Extensions have been written to add support for the Windows API, process management on Unixlike operating systems, multibyte strings (Unicode), cURL, and several popular compression formats. Other features include
integration with IRC, dynamic generation of images and Adobe Flash content, and even speech synthesis. The language's core
functions such as those dealing with strings and arrays are also implemented as an extension. [90] The PHP Extension Community
Library (PECL) project is a repository for extensions to the PHP language.[91] PDO - (PHP Data Objects) is an interface for
accessing databases.[92] [93][94][95][96][97][98]
Zend Technologies provides a certification exam for programmers to become certified PHP developers.
Use
PHP is a general-purpose scripting language that is especially suited to server-side web development where PHP generally runs on
a web server. Any PHP code in a requested file is executed by the PHP runtime, usually to create dynamic web page content or
dynamic images used on websites or elsewhere. [100] It can also be used for command-line scripting and client-side graphical user
interface (GUI) applications. PHP can be deployed on most web servers, many operating systems and platforms, and can be used
with many relational database management systems (RDBMS). Most web hosting providers support PHP for use by their clients. It
is available free of charge, and the PHP Group provides the complete source code for users to build, customize and extend for their
own use.[7]
PHP acts primarily as a filter,[101] taking input from a file or stream containing text and/or PHP instructions and outputting another
stream of data; most commonly the output will be HTML. Since PHP 4, the PHP parser compiles input to produce bytecode for
processing by the Zend Engine, giving improved performance over its interpreter predecessor.[102]
Originally designed to create dynamic web pages, PHP now focuses mainly on server-side scripting,[103] and it is similar to other
server-side scripting languages that provide dynamic content from a web server to a client, such as Microsoft's ASP.NET, Sun
Microsystems' JavaServer Pages,[104] and mod_perl. PHP has also attracted the development of many software frameworks that
provide building blocks and a design structure to promote rapid application development (RAD). Some of these include CakePHP,
Symfony, CodeIgniter, Yii Framework, and Zend Framework, offering features similar to other web application frameworks.
The LAMP architecture has become popular in the web industry as a way of deploying web applications. PHP is commonly used as
the P in this bundle alongside Linux, Apache and MySQL, although the P may also refer to Python, Perl, or some mix of the three.
Similar packages are also available for Windows and OS X, then called WAMP and MAMP, with the first letter standing for the
UNIT – I By P.V.Ravikanth, 8019594355
3
OPEN SOURCE SOFTWARE
respective operating system. Although both PHP and Apache are provided as part of the Mac OS X base install, users of these
packages seek a simpler installation mechanism that can be more easily kept up to date.
As of April 2007, over 20 million Internet domains had web services hosted on servers with PHP installed and mod_php was
recorded as the most popular Apache HTTP Server module.[105] PHP is used as the server-side programming language on 75% of
all websites whose server-side programming language is known, [106] and PHP is the most-used open source software within
enterprises.[107] web content management systems written in PHP include MediaWiki,[108] Joomla, eZ Publish, SilverStripe,[109]
WordPress,[110] Drupal,[111] Moodle,[112] the user-facing portion of Facebook,[113] and Digg.
Security
About 30% of all vulnerabilities listed on the National Vulnerability Database are linked to PHP.[115] These vulnerabilities are caused
mostly by not following best practice programming rules; technical security flaws of the language itself or of its core libraries are not
frequent (23 in 2008, about 1% of the total). [116][117] Recognizing that programmers make mistakes, some languages include taint
checking to automatically detect the lack of input validation which induces many issues. Such a feature is being developed for
PHP,[118] but its inclusion in a release has been rejected several times in the past.[119][120]
There are advanced protection patches such as Suhosin and Hardening-Patch, especially designed for web hosting environments.
Programming in web environment
PHP is a scripting language designed to fill the gap between SSI (Server Side Includes) and Perl, intended largely for the web
environment. PHP has gained quite a following in recent times, and it is one of the frontrunners in the Open Source software
movement. Its popularity derives from its C-like syntax, its speed and its simplicity. PHP is currently divided into two major versions:
PHP 4 and PHP 5. PHP 6 is currently under development.
If you've ever been to a website that needs you to login, you've probably encountered a server-side scripting language. Due to its
market saturation, this means you've probably come across PHP. PHP was designed by Rasmus Lerdorf to display his resume
online and to collect data from his visitors.
Basically, PHP allows a static web document to become dynamic. "PHP" is a recursive acronym that stands for "PHP: Hypertext
Preprocessor". PHP preprocesses (that is, PHP processes before the output is sent to the browser) hypertext documents. Because
of this, the pages can change before the user sees them, based on conditions. This can be used to write something to the page,
create a table with a number of rows equal to the number of times the user has visited, or integrate the web page with a web
database, such as MySQL.
We have experienced PHP professionals who can help clients from Nepal, USA, UK, Canada and all over the world in the field of
website development, software development, website maintenance and much more. Our experienced PHP programmers are
dedicated to LAMP (Linux operating system; Apache Web server; My SQL database management system or database server;
PHP, Python scripting/programming languages).Ripple Tech Inc. has served clients from different industries including Retail,
Telecom, Travel, and other sectors. PHP Programming is widely used as an alternative of ASP Programming, ASP.NET
Programming, Coldfusion Development.
Our professional, experienced dedicated PHP development team ensures complete transparency and work in line with client. The
team will coordinate and adhere with the client’s requirements and time schedules to ensure timely completion of the process.
Some of the PHP Web Applications we can develop and have developed for our clients:

Job Boards/Portal Custom PHP Software Development

Classified and Online Ads Posting website using PHP and MySQL

On-demand Custom PHP Web Development

Customer Service Applications in PHP & MySQL

Secure Message boards Application Development in PHP & MySQL

E-Commerce Web Development in PHP & MySQL

Inventory Management System using PHP Application Development

Search Engine Friendly Shopping Cart using PHP Application Development

Search Engine Friendly Content Management System (CMS) using PHP Application Development

MySQL Database Driven Calendar Application Development in PHP

AJAX (Asynchronous JavaScript and XML) based PHP Web Application Development

Custom Webmasters Tools & Script Development

PHP and MySQL Web site Design and Development
Advantages of PHP / My SQL Application:
UNIT – I By P.V.Ravikanth, 8019594355
4
OPEN SOURCE SOFTWARE

Minimize costs with a cost-effective and affordable PHP & My SQL web application Development that reduces costs and improves profits.

Give your Online Store customers a personalized shopping experience through our PHP Web applications Development Services.

Improve your organization’s visibility by building high-performance data warehouse applications in PHP & My SQL.

Increase productivity and sales by building CRM using PHP & My SQL Applications Development that automate sales and marketing
process.

Minimize operational costs by developing automated applications systems that upgrade your manual processes.

Improve customer service by giving you the highly-responsive, continuously online systems with real-time support.
PHP Variables
As with algebra, PHP variables can be used to hold values (x=5) or expressions (z=x+y).
Variable can have short names (like x and y) or more descriptive names (age, carname, totalvolume).
Rules for PHP variables:

A variable starts with the $ sign, followed by the name of the variable

A variable name must begin with a letter or the underscore character

A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )

A variable name should not contain spaces

Variable names are case sensitive ($y and $Y are two different variables)
Both PHP statements and PHP variables are case-sensitive.
Variables are "containers" for storing information:
Example
<?php
$x=5;
$y=6;
$z=$x+$y;
echo
?>
$z;
OUT PUT:11
Much Like Algebra
x=5
y=6
z=x+y
In algebra we use letters (like x) to hold values (like 5).
From the expression z=x+y above, we can calculate the value of z to be 11.
In PHP these letters are called variables.
Think of variables as containers for storing data.
Creating (Declaring) PHP Variables
PHP has no command for declaring a variable.
A variable is created the moment you first assign a value to it:
$txt="Hello world!";
$x=5;
After the execution of the statements above, the variable txt will hold the value Hello world!, and the variable x will hold the value
5.
Note: When you assign a text value to a variable, put quotes around the value.
UNIT – I By P.V.Ravikanth, 8019594355
5
OPEN SOURCE SOFTWARE
PHP is a Loosely Typed Language
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 a strongly typed programming language, we will have to declare (define) the type and name of the variable before using it.
PHP Variable Scopes
The scope of a variable is the part of the script where the variable can be referenced/used.
PHP has four different variable scopes:

local

global

static

parameter
Local Scope
A variable declared within a PHP function is local and can only be accessed within that function:
Example
<?php
$x=5; // global scope
function myTest()
{
echo $x; // local scope
}
myTest();
?>
OUT PUT: Nill
The script above will not produce any output because the echo statement refers to the local scope variable $x, which has not been
assigned a value within this scope.
You can have local variables with the same name in different functions, because local variables are only recognized by the function
in which they are declared.
Local variables are deleted as soon as the function is completed.
Global Scope
A variable that is defined outside of any function, has a global scope.
Global variables can be accessed from any part of the script, EXCEPT from within a function.
To access a global variable from within a function, use the global keyword:
Example
<?php
$x=5; // global scope
$y=10; // global scope
function myTest()
{
global $x,$y;
$y=$x+$y;
}
myTest();
echo $y; // outputs 15
?>
OUT PUT:15
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.
UNIT – I By P.V.Ravikanth, 8019594355
6
OPEN SOURCE SOFTWARE
The example above can be rewritten like this:
Example
<?php
$x=5;
$y=10;
function myTest()
{
$GLOBALS['y']=$GLOBALS['x']+$GLOBALS['y'];
}
myTest();
echo $y;
?>
OUT PUT:15
Static Scope
When a function is completed, all of its variables are normally deleted. However, sometimes you want a local variable to not be
deleted.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest()
{
static $x=0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
OUT PUT:012
Then, each time the function is called, that variable will still have the information it contained from the last time the function was
called.
Note: The variable is still local to the function.
Parameter Scope
A parameter is a local variable whose value is passed to the function by the calling code.
Parameters are declared in a parameter list as part of the function declaration:
Example
<?php
function myTest($x)
{
echo $x;
}
myTest(5);
?>
OUT PUT:5
Data types
PHP stores whole numbers in a platform-dependent range, either a 64-bit or 32-bit signed integer equivalent to the C-language
long type. Unsigned integers are converted to signed values in certain situations; this behavior is different from other programming
UNIT – I By P.V.Ravikanth, 8019594355
7
OPEN SOURCE SOFTWARE
languages.[68] Integer variables can be assigned using decimal (positive and negative), octal, hexadecimal, and binary notations.
Floating point numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms
of scientific notation.[69] PHP has a native Boolean type that is similar to the native Boolean types in Java and C++. Using the
Boolean type conversion rules, non-zero values are interpreted as true and zero as false, as in Perl and C++.[69] The null data type
represents a variable that has no value. The only value in the null data type is NULL.[69] Variables of the "resource" type represent
references to resources from external sources. These are typically created by functions from a particular extension, and can only
be processed by functions from the same extension; examples include file, image, and database resources.[69] Arrays can contain
elements of any type that PHP can handle, including resources, objects, and even other arrays. Order is preserved in lists of values
and in hashes with both keys and values, and the two can be intermingled. [69] PHP also supports strings, which can be used with
single quotes, double quotes, nowdoc or heredoc syntax.[70]
The Standard PHP Library (SPL) attempts to solve standard problems and implements efficient data access interfaces and classes.
PHP supports eight primitive types.
Four scalar types:

boolean

integer

float (floating-point number, aka double)

string
Two compound types:

array

object
And finally two special types:

resource

NULL
This manual also introduces some pseudo-types for readability reasons:

mixed

number

callback
And the pseudo-variable $....
Some references to the type "double" may remain in the manual. Consider double the same as float; the two names exist only for
historic reasons.
The type of a variable is not usually set by the programmer; rather, it is decided at runtime by PHP depending on the context in
which that variable is used.
Note: To check the type and value of an expression, use the var_dump() function.
To get a human-readable representation of a type for debugging, use the gettype() function. To check for a certain type, do not use
gettype(), but rather the is_type functions. Some examples:
<?php
$a_bool = TRUE; // a boolean
$a_str = "foo"; // a string
$a_str2 = 'foo'; // a string
$an_int = 12; // an integer
echo gettype($a_bool); // prints out: boolean
echo gettype($a_str); // prints out: string
// If this is an integer, increment it by four
if (is_int($an_int)) {
$an_int += 4;
}
// If $a_bool is a string, print it out
// (does not print out anything)
if (is_string($a_bool)) {
UNIT – I By P.V.Ravikanth, 8019594355
8
OPEN SOURCE SOFTWARE
echo "String: $a_bool";
}
?>
To forcibly convert a variable to a certain type, either cast the variable or use the settype() function on it.
Note that a variable may be evaluated with different values in certain situations, depending on what type it is at the time. For more
information, see the section on Type Juggling. The type comparison tables may also be useful, as they show examples of various
type-related comparisons.
Booleans
This is the simplest type. A boolean expresses a truth value. It can be either TRUE or FALSE.
Syntax
To specify a boolean literal, use the keywords TRUE or FALSE. Both are case-insensitive.
<?php
$foo = True; // assign the value TRUE to $foo
?>
Typically, the result of an operator which returns a boolean value is passed on to a control structure.
Integers
An integer is a number of the set ℤ = {..., -2, -1, 0, 1, 2, ...}.
See also:

Arbitrary length integer / GMP

Floating point numbers

Arbitrary precision / BCMath
Syntax
Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally
preceded by a sign (- or +).
Binary integer literals are available since PHP 5.4.0.
To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x. To use binary
notation precede the number with 0b.
Floating point numbers
Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Formally:
LNUM
[0-9]+
DNUM
([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a
common value (the 64 bit IEEE format).
Strings
A string is series of characters, where a character is the same as a byte. This means that PHP only supports a 256-character set,
and hence does not offer native Unicode support. See details of the string type.
Note: string can be as large as 2GB.
Syntax
A string literal can be specified in four different ways:

single quoted
UNIT – I By P.V.Ravikanth, 8019594355
9
OPEN SOURCE SOFTWARE

double quoted

heredoc syntax

nowdoc syntax (since PHP 5.3.0)
Single quoted
The simplest way to specify a string is to enclose it in single quotes (the character ').
To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of
backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n,
will be output literally as specified rather than having any special meaning.
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be
expanded when they occur in single quoted strings.
<?php
echo 'this is a simple string';
echo 'You can also have embedded newlines in
strings this way as it is
okay to do';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';
// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';
// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';
// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>
Double quoted
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
Escaped characters
Sequence
Meaning
\n
linefeed (LF or 0x0A (10) in ASCII)
\r
carriage return (CR or 0x0D (13) in ASCII)
\t
horizontal tab (HT or 0x09 (9) in ASCII)
\v
vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\e
escape (ESC or 0x1B (27) in ASCII) (since PHP 5.4.0)
\f
form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\
backslash
\$
dollar sign
\"
double-quote
\[0-7]{1,3}
the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation
UNIT – I By P.V.Ravikanth, 8019594355
10
OPEN SOURCE SOFTWARE
As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP
5.1.1, the backslash in \{$var} had not been printed.
The most important feature of double-quoted strings is the fact that variable names will be expanded. See string
parsing for details.
Heredoc
A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline.
The string itself follows, and then the same identifier again to close the quotation.
The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules
as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a nondigit character or underscore.
Arrays
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for
several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary,
collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays
are also possible.
Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each
of them. For more information, look towards the considerable literature that exists about this broad topic.
Syntax
Specifying with array()
An array can be created using the array() language construct. It takes any number of comma-separated key => value
pairs as arguments.
array(
key => value,
key2 => value2,
key3 => value3,
...)
The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e.
array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used,
as it allows easier addition of new elements at the end.
As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].
Example #1 A simple array
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
The key can either be an integer or a string. The value can be of any type.
Additionally the following key casts will occur:

Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8.
On the other hand "08" will not be cast, as it isn't a valid decimal integer.

Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will
actually be stored under 8.
UNIT – I By P.V.Ravikanth, 8019594355
11
OPEN SOURCE SOFTWARE

Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.

Null will be cast to the empty string, i.e. the key null will actually be stored under "".

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
If multiple elements in the array declaration use the same key, only the last one will be used as all others are
overwritten.
Objects
Object Initialization
To create a new object, use the new statement to instantiate a class:
<?php
class foo
{
function do_foo()
{
echo "Doing foo.";
}
}
$bar = new foo;
$bar->do_foo();
?>
For a full discussion, see the Classes and Objects chapter.
Converting to object
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new
instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays
convert to an object with properties named by keys, and corresponding values. For any other value, a member
variable named scalar will contain the value.
<?php
$obj = (object) 'ciao';
echo $obj->scalar; // outputs 'ciao'
?>
Resources
A resource is a special variable, holding a reference to an external resource. Resources are created and used by
special functions. See the appendix for a listing of all these functions and the corresponding resource types.
See also the get_resource_type() function.
Converting to resource
As resource variables hold special handlers to opened files, database connections, image canvas areas and the like,
converting to a resource makes no sense.
Freeing resources
Thanks to the reference-counting system introduced with PHP 4's Zend Engine, a resource with no more references to
it is detected automatically, and it is freed by the garbage collector. For this reason, it is rarely necessary to free the
memory manually.
Note: Persistent database links are an exception to this rule. They are not destroyed by the garbage collector. See the
persistent connections section for more information.
NULL
The special NULL value represents a variable with no value. NULL is the only possible value of type null.
A variable is considered to be null if:

it has been assigned the constant NULL.

it has not been set to any value yet.
UNIT – I By P.V.Ravikanth, 8019594355
12
OPEN SOURCE SOFTWARE

it has been unset().
Syntax
There is only one value of type null, and that is the case-insensitive constant NULL.
<?php
$var = NULL;
?>
See also the functions is_null() and unset().
Casting to NULL
Casting a variable to null using (unset) $var will not remove the variable or unset its value. It will only return a NULL
value.
Callbacks
Callbacks can be denoted by callable type hint as of PHP 5.4. This documentation used callback type information for
the same purpose.
Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback
functions can not only be simple functions, but also object methods, including static class methods.
Passing
A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language
constructs such as: array(), echo, empty(), eval(), exit(), isset(), list(), print or unset().
A method of an instantiated object is passed as an array containing an object at index 0 and the method name at
index 1.
Static class methods can also be passed without instantiating an object of that class by passing the class name
instead of an object at index 0. As of PHP 5.2.3, it is also possible to pass 'ClassName::methodName'.
Apart from common user-defined function, create_function() can also be used to create an anonymous callback
function. As of PHP 5.3.0 it is possible to also pass a closure to a callback parameter.
Pseudo-types and variables used in this documentation
mixed
mixed indicates that a parameter may accept multiple (but not necessarily all) types.
gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.
number
number indicates that a parameter can be either integer or float.
callback
callback pseudo-types was used in this documentation before callable type hint was introduced by PHP 5.4. It means
exactly the same.
void
void as a return type means that the return value is useless. void in a parameter list means that the function doesn't
accept any parameters.
...
$... in function prototypes means and so on. This variable name is used when a function can take an endless number
of arguments.
Type Juggling
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the
context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a
string. If an integer value is then assigned to $var, it becomes an integer.
An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both
operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers,
UNIT – I By P.V.Ravikanth, 8019594355
13
OPEN SOURCE SOFTWARE
and the result will also be an integer. Note that this does not change the types of the operands themselves; the only
change is in how the operands are evaluated and what the type of the expression itself is.
<?php
$foo = "0"; // $foo is string (ASCII 48)
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs"; // $foo is integer (15)
?>
If the last two examples above seem odd, see String conversion to numbers.
To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a
variable, see the settype() function.
To test any of the examples in this section, use the var_dump() function.
Note:
The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following
example holds true for all PHP versions:
<?php
$a = 'car'; // $a is a string
$a[0] = 'b'; // $a is still a string
echo $a;
// bar
?>
See the section titled String access by character for more information.
Type Casting
Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the
variable which is to be cast.
<?php
$foo = 10; // $foo is an integer
$bar = (boolean) $foo; // $bar is a boolean
?>
The casts allowed are:

(int), (integer) - cast to integer

(bool), (boolean) - cast to boolean

(float), (double), (real) - cast to float

(string) - cast to string

(array) - cast to array

(object) - cast to object

(unset) - cast to NULL (PHP 5)
(binary) casting and b prefix forward support was added in PHP 5.2.1
PHP Operators
The assignment operator = is used to assign values to variables in PHP.
The arithmetic operator + is used to add values together in PHP.
PHP Arithmetic Operators
Operator
Name
Description
Example
Result
x+y
Addition
Sum of x and y
2+2
4
UNIT – I By P.V.Ravikanth, 8019594355
14
OPEN SOURCE SOFTWARE
x-y
Subtraction
Difference of x and y
5-2
3
x*y
Multiplication
Product of x and y
5*2
10
x/y
Division
Quotient of x and y
15 / 5
3
x%y
Modulus
-x
Negation
Remainder of x divided by y 5 % 2
10 % 8
Opposite of x
-102 % 2
1
2
0
a.b
Concatenation
Concatenate two strings
HiHa
"Hi" . "Ha"
PHP Assignment Operators
The basic assignment operator in PHP is "=". It means that the left operand gets set to the value of the expression on
the right. That is, the value of "$x = 5" is 5.
Assignment Same as...
Description
x=y
x=y
The left operand gets set to the value of the expression on the right
x += y
x=x+y
Addition
x -= y
x=x-y
Subtraction
x *= y
x=x*y
Multiplication
x /= y
x=x/y
Division
x %= y
x=x%y
Modulus
a .= b
a=a.b
Concatenate two strings
PHP Incrementing/Decrementing Operators
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 Comparison Operators
Comparison operators allows you to compare two values:
Operator
Name
Description
Example
x == y
Equal
True if x is equal to y
5==8 returns false
x === y
Identical
True if x is equal to y, and they are of same type
5==="5" returns false
x != y
Not equal
True if x is not equal to y
5!=8 returns true
x <> y
Not equal
True if x is not equal to y
5<>8 returns true
x !== y
Not identical
x>y
Greater than
True if x is not equal to y, or they are not of same 5!=="5" returns true
type
True if x is greater than y
5>8 returns false
x<y
Less than
True if x is less than y
5<8 returns true
x >= y
Greater than or equal to
True if x is greater than or equal to y
5>=8 returns false
x <= y
Less than or equal to
True if x is less than or equal to y
5<=8 returns true
UNIT – I By P.V.Ravikanth, 8019594355
15
OPEN SOURCE SOFTWARE
PHP Logical Operators
Operator
Name
Description
Example
x and y
And
True if both x and y are true
x=6
y=3
(x < 10 and y > 1) returns true
x or y
Or
True if either or both x and y are true
x=6
y=3
(x==6 or y==5) returns true
x xor y
Xor
x=6
True if either x or y is true, but not both y=3
(x==6 xor y==3) returns false
x && y
And
True if both x and y are true
x=6
y=3
(x < 10 && y > 1) returns true
x || y
Or
True if either or both x and y are true
x=6
y=3
(x==5 || y==5) returns false
!x
Not
True if x is not true
x=6
y=3
!(x==y) returns true
PHP Array Operators
Operator
Name
Description
x+y
Union
Union of x and y
x == y
Equality
True if x and y have the same key/value pairs
x === y
Identity
True if x and y have the same key/value pairs in the same order and are of the same type
x != y
Inequality
True if x is not equal to y
x <> y
Inequality
True if x is not equal to y
x !== y
Non-identity
True if x is not identical to y
PHP Statements
PHP If...Else Statements
Conditional statements are used to perform different actions based on different conditions.
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:

if statement - executes some code only if a specified condition is true

if...else statement - executes some code if a condition is true and another code if the condition is false

if...else if....else statement - selects one of several blocks of code to be executed
UNIT – I By P.V.Ravikanth, 8019594355
16
OPEN SOURCE SOFTWARE

switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time is less than 20:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
?>
Run » Have a good day!
PHP - 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.
Syntax
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good night!"
otherwise:
Example
<?php
$t=date("H");
if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Run » Have a good day!
PHP - The if...else if....else Statement
Use the if....else if...else statement to select one of several blocks of code to be executed.
Syntax
if (condition)
{
code to be executed if condition is true;
UNIT – I By P.V.Ravikanth, 8019594355
17
OPEN SOURCE SOFTWARE
}
else if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}
The example below will output "Have a good morning!" if the current time is less than 10, and "Have a good day!" if
the current time is less than 20. Otherwise it will output "Have a good night!":
Example
<?php
$t=date("H");
if ($t<"10")
{
echo "Have a good morning!";
}
else if ($t<"20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
Run » Have a good morning!
PHP Switch Statement
The switch statement is used to perform different actions based on different conditions.
The PHP Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
default:
code to be executed if n is different from both label1 and label2;
}
This is how it works: 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.
Example
<?php
$favcolor="red";
switch ($favcolor)
{
case "red":
UNIT – I By P.V.Ravikanth, 8019594355
18
OPEN SOURCE SOFTWARE
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>
Run » Your favorite color is red!
PHP Arrays
An array stores multiple values in one single variable:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Run example » I like Volvo, BMW and Toyota.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
$cars1="Volvo";
$cars2="BMW";
$cars3="Toyota";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is to create an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.
Create an Array in PHP
In PHP, the array() function is used to create an array:
array();
In PHP, there are three types of arrays:

Indexed arrays - Arrays with numeric index

Associative arrays - Arrays with named keys

Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0):
$cars=array("Volvo","BMW","Toyota");
or the index can be assigned manually:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text
containing the array values:
UNIT – I By P.V.Ravikanth, 8019594355
19
OPEN SOURCE SOFTWARE
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
Run example » I like Volvo, BMW and Toyota.
Get The Length of an Array - The count() Function
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
Run example » 3
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop, like this:
Example
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
Run example » Volvo
BMW
Toyota
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
or:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";
The named keys can then be used in a script:
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
Run example » Peter is 35 years old.
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
UNIT – I By P.V.Ravikanth, 8019594355
20
OPEN SOURCE SOFTWARE
Example
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
Run example » Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
PHP Looping - While Loops
Loops execute a block of code a specified number of times, or while a specified condition is true.
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a row. Instead of adding
several almost equal lines in a script we can use loops to perform a task like this.
In PHP, we have the following looping statements:

while - loops through a block of code while a specified condition is true

do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true

for - loops through a block of code a specified number of times

foreach - loops through a block of code for each element in an array
The while Loop
The while loop executes a block of code while a condition is true.
Syntax
while (condition)
{
code to be executed;
}
Example
The example below first sets a variable i to 1 ($i=1;).
Then, the while loop will continue to run as long as i is less than, or equal to 5. i will increase by 1 each time the loop
runs:
<html>
<body>
<?php
$i=1;
while($i<=5)
{
echo "The number is " . $i . "<br>";
$i++;
}
?>
</body>
</html>
Output:
UNIT – I By P.V.Ravikanth, 8019594355
21
OPEN SOURCE SOFTWARE
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The do...while Statement
The do...while statement will always execute the block of code once, it will then check the condition, and repeat the
loop while the condition is true.
Syntax
do
{
code to be executed;
}
while (condition);
Example
The example below first sets a variable i to 1 ($i=1;).
Then, it starts the do...while loop. The loop will increment the variable i with 1, and then write some output. Then the
condition is checked (is i less than, or equal to 5), and the loop will continue to run as long as i is less than, or equal to
5:
<html>
<body>
<?php
$i=1;
do
{
$i++;
echo "The number is " . $i . "<br>";
}
while ($i<=5);
?>
</body>
</html>
Output:
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
PHP Looping - For Loops
Loops execute a block of code a specified number of times, or while a specified condition is true.
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (init; condition; increment)
{
code to be executed;
}
Parameters:

init: Mostly used to set a counter (but can be any code to be executed once at the beginning of the loop)
UNIT – I By P.V.Ravikanth, 8019594355
22
OPEN SOURCE SOFTWARE

condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FALSE,
the loop ends.

increment: Mostly used to increment a counter (but can be any code to be executed at the end of the iteration)
Note: The init and increment parameters above can be empty or have multiple expressions (separated by commas).
Example
The example below defines a loop that starts with i=1. The loop will continue to run as long as the variable i is less
than, or equal to 5. The variable i will increase by 1 each time the loop runs:
<html>
<body>
<?php
for ($i=1; $i<=5; $i++)
{
echo "The number is " . $i . "<br>";
}
?>
</body>
</html>
Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
The foreach Loop
The foreach loop is used to loop through arrays.
Syntax
foreach ($array as $value)
{
code to be executed;
}
For every loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved
by one) - so on the next loop iteration, you'll be looking at the next array value.
Example
The following example demonstrates a loop that will print the values of the given array:
<html>
<body>
<?php
$x=array("one","two","three");
foreach ($x as $value)
{
echo $value . "<br>";
}
?>
</body>
</html>
Output:
UNIT – I By P.V.Ravikanth, 8019594355
23
OPEN SOURCE SOFTWARE
one
two
three
PHP Functions
The real power of PHP comes from its functions.
In PHP, there are more than 700 built-in functions.
PHP Built-in Functions
For a complete reference and examples of the built-in functions, please visit our PHP Reference.
PHP Functions
In this chapter we will show you how to create your own functions.
To keep the script from being executed when the page loads, you can put it into a function.
A function will be executed by a call to the function.
You may call a function from anywhere within a page.
Create a PHP Function
A function will be executed by a call to the function.
Syntax
function functionName()
{
code to be executed;
}
PHP function guidelines:

Give the function a name that reflects what the function does

The function name can start with a letter or underscore (not a number)
Example
A simple function that writes my name when it is called:
<html>
<body>
<?php
function writeName()
{
echo "Kai Jim Refsnes";
}
echo "My name is ";
writeName();
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes
PHP Functions - Adding parameters
To add more functionality to a function, we can add parameters. A parameter is just like a variable.
Parameters are specified after the function name, inside the parentheses.
UNIT – I By P.V.Ravikanth, 8019594355
24
OPEN SOURCE SOFTWARE
Example 1
The following example will write different first names, but equal last name:
<html>
<body>
<?php
function writeName($fname)
{
echo $fname . " Refsnes.<br>";
}
echo "My name is ";
writeName("Kai Jim");
echo "My sister's name is ";
writeName("Hege");
echo "My brother's name is ";
writeName("Stale");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes.
My brother's name is Stale Refsnes.
Example 2
The following function has two parameters:
<html>
<body>
<?php
function writeName($fname,$punctuation)
{
echo $fname . " Refsnes" . $punctuation . "<br>";
}
echo "My name is ";
writeName("Kai Jim",".");
echo "My sister's name is ";
writeName("Hege","!");
echo "My brother's name is ";
writeName("Ståle","?");
?>
</body>
</html>
Output:
My name is Kai Jim Refsnes.
My sister's name is Hege Refsnes!
My brother's name is Ståle Refsnes?
PHP Functions - Return values
To let a function return a value, use the return statement.
UNIT – I By P.V.Ravikanth, 8019594355
25
OPEN SOURCE SOFTWARE
Example
<html>
<body>
<?php
function add($x,$y)
{
$total=$x+$y;
return $total;
}
echo "1 + 16 = " . add(1,16);
?>
</body>
</html>
Output:
1 + 16 = 17
PHP Forms and User Input
The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input.
PHP Form Handling
The most important thing to notice when dealing with HTML forms and PHP is that any form element in an HTML page
will automatically be available to your PHP scripts.
Example
The example below contains an HTML form with two input fields and a submit button:
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
When a user fills out the form above and clicks on the submit button, the form data is sent to a PHP file, called
"welcome.php":
"welcome.php" looks like this:
<html>
<body>
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>
Output could be something like this:
Welcome John!
You are 28 years old.
The PHP $_GET and $_POST variables will be explained in the next chapters.
UNIT – I By P.V.Ravikanth, 8019594355
26
OPEN SOURCE SOFTWARE
Form Validation
User input should be validated on the browser whenever possible (by client scripts). Browser validation is faster and
reduces the server load.
You should consider server validation if the user input will be inserted into a database. A good way to validate a form
on the server is to post the form to itself, instead of jumping to a different page. The user will then get the error
messages on the same page as the form. This makes it easier to discover the error.
PHP $_GET Variable
In PHP, the predefined $_GET variable is used to collect values in a form with method="get".
The $_GET Variable
The predefined $_GET variable is used to collect values in a form with method="get"
Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser's address
bar) and has limits on the amount of information to send.
Example
<form action="welcome.php" method="get">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
When the user clicks the "Submit" button, the URL sent to the server could look something like this:
http://www.w3schools.com/welcome.php?fname=Peter&age=37
The "welcome.php" file can now use the $_GET variable to collect form data (the names of the form fields will
automatically be the keys in the $_GET array):
Welcome <?php echo $_GET["fname"]; ?>.<br>
You are <?php echo $_GET["age"]; ?> years old!
When to use method="get"?
When using method="get" in HTML forms, all variable names and values are displayed in the URL.
Note: This method should not be used when sending passwords or other sensitive information!
However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in
some cases.
Note: The get method is not suitable for very large variable values. It should not be used with values exceeding 2000
characters.
PHP $_POST Function
In PHP, the predefined $_POST variable is used to collect values in a form with method="post".
The $_POST Variable
The predefined $_POST variable is used to collect values from a form sent with method="post".
Information sent from a form with the POST method is invisible to others and has no limits on the amount of
information to send.
Note: However, there is an 8 MB max size for the POST method, by default (can be changed by setting the
post_max_size in the php.ini file).
Example
<form action="welcome.php" method="post">
Name: <input type="text" name="fname">
Age: <input type="text" name="age">
<input type="submit">
</form>
When the user clicks the "Submit" button, the URL will look like this:
UNIT – I By P.V.Ravikanth, 8019594355
27
OPEN SOURCE SOFTWARE
http://www.w3schools.com/welcome.php
The "welcome.php" file can now use the $_POST variable to collect form data (the names of the form fields will
automatically be the keys in the $_POST array):
Welcome <?php echo $_POST["fname"]; ?>!<br>
You are <?php echo $_POST["age"]; ?> years old.
When to use method="post"?
Information sent from a form with the POST method is invisible to others and has no limits on the amount of
information to send.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
The PHP $_REQUEST Variable
The predefined $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE.
The $_REQUEST variable can be used to collect form data sent with both the GET and POST methods.
Example
Welcome <?php echo $_REQUEST["fname"]; ?>!<br>
You are <?php echo $_REQUEST["age"]; ?> years old.
PHP Filesystem Functions
PHP Filesystem Introduction
The filesystem functions allow you to access and manipulate the filesystem.
Installation
The filesystem functions are part of the PHP core. There is no installation needed to use these functions.
Runtime Configuration
The behavior of the filesystem functions is affected by settings in php.ini.
Filesystem configuration options:
Name
Default
Description
Changeable
allow_url_fopen
"1"
PHP_INI_SYSTEM
user_agent
NULL
default_socket_timeout
"60"
from
""
Allows fopen()-type functions to work with URLs (available
since PHP 4.0.4)
Defines the user agent for PHP to send (available since PHP
4.3)
Sets the default timeout, in seconds, for socket based
streams (available since PHP 4.3)
Defines the anonymous FTP password (your email address)
auto_detect_line_endings
"0"
Unix / Windows Compatibility
PHP_INI_ALL
PHP_INI_ALL
PHP_INI_ALL
When set to "1", PHP will examine the data read by fgets() PHP_INI_ALL
and file() to see if it is using Unix, MS-Dos or Mac line-ending
characters (available since PHP 4.3)
When specifying a path on Unix platforms, the forward slash (/) is used as directory separator. However, on Windows
platforms, both forward slash (/) and backslash (\) can be used.
PHP Filesystem Functions
PHP: indicates the earliest version of PHP that supports the function.
Function
Description
PHP
basename()
Returns the filename component of a path
3
chgrp()
Changes the file group
3
chmod()
Changes the file mode
3
chown()
Changes the file owner
3
UNIT – I By P.V.Ravikanth, 8019594355
28
OPEN SOURCE SOFTWARE
clearstatcache()
Clears the file status cache
3
copy()
Copies a file
3
delete()
See unlink() or unset()
dirname()
Returns the directory name component of a path
3
disk_free_space()
Returns the free space of a directory
4
disk_total_space()
Returns the total size of a directory
4
diskfreespace()
Alias of disk_free_space()
3
fclose()
Closes an open file
3
feof()
Tests for end-of-file on an open file
3
fflush()
Flushes buffered output to an open file
4
fgetc()
Returns a character from an open file
3
fgetcsv()
Parses a line from an open file, checking for CSV fields
3
fgets()
Returns a line from an open file
3
fgetss()
Returns a line, with HTML and PHP tags removed, from an open file
3
file()
Reads a file into an array
3
file_exists()
Checks whether or not a file or directory exists
3
file_get_contents()
Reads a file into a string
4
file_put_contents
Writes a string to a file
5
fileatime()
Returns the last access time of a file
3
filectime()
Returns the last change time of a file
3
filegroup()
Returns the group ID of a file
3
fileinode()
Returns the inode number of a file
3
filemtime()
Returns the last modification time of a file
3
fileowner()
Returns the user ID (owner) of a file
3
fileperms()
Returns the permissions of a file
3
filesize()
Returns the file size
3
filetype()
Returns the file type
3
flock()
Locks or releases a file
3
fnmatch()
Matches a filename or string against a specified pattern
4
fopen()
Opens a file or URL
3
fpassthru()
Reads from an open file, until EOF, and writes the result to the output buffer 3
fputcsv()
Formats a line as CSV and writes it to an open file
5
fputs()
Alias of fwrite()
3
fread()
Reads from an open file
3
fscanf()
Parses input from an open file according to a specified format
4
UNIT – I By P.V.Ravikanth, 8019594355
29
OPEN SOURCE SOFTWARE
fseek()
Seeks in an open file
3
fstat()
Returns information about an open file
4
ftell()
Returns the current position in an open file
3
ftruncate()
Truncates an open file to a specified length
4
fwrite()
Writes to an open file
3
glob()
Returns an array of filenames / directories matching a specified pattern
4
is_dir()
Checks whether a file is a directory
3
is_executable()
Checks whether a file is executable
3
is_file()
Checks whether a file is a regular file
3
is_link()
Checks whether a file is a link
3
is_readable()
Checks whether a file is readable
3
is_uploaded_file()
Checks whether a file was uploaded via HTTP POST
3
is_writable()
Checks whether a file is writeable
4
is_writeable()
Alias of is_writable()
3
link()
Creates a hard link
3
linkinfo()
Returns information about a hard link
3
lstat()
Returns information about a file or symbolic link
3
mkdir()
Creates a directory
3
move_uploaded_file()
Moves an uploaded file to a new location
4
parse_ini_file()
Parses a configuration file
4
pathinfo()
Returns information about a file path
4
pclose()
Closes a pipe opened by popen()
3
popen()
Opens a pipe
3
readfile()
Reads a file and writes it to the output buffer
3
readlink()
Returns the target of a symbolic link
3
realpath()
Returns the absolute pathname
4
rename()
Renames a file or directory
3
rewind()
Rewinds a file pointer
3
rmdir()
Removes an empty directory
3
set_file_buffer()
Sets the buffer size of an open file
3
stat()
Returns information about a file
3
symlink()
Creates a symbolic link
3
tempnam()
Creates a unique temporary file
3
tmpfile()
Creates a unique temporary file
3
touch()
Sets access and modification time of a file
3
UNIT – I By P.V.Ravikanth, 8019594355
30
OPEN SOURCE SOFTWARE
umask()
Changes file permissions for files
3
unlink()
Deletes a file
3
PHP Filesystem Constants
PHP: indicates the earliest version of PHP that supports the constant.
Constant
Description
PHP
GLOB_BRACE
GLOB_ONLYDIR
GLOB_MARK
GLOB_NOSORT
GLOB_NOCHECK
GLOB_NOESCAPE
PATHINFO_DIRNAME
PATHINFO_BASENAME
PATHINFO_EXTENSION
FILE_USE_INCLUDE_PATH
FILE_APPEND
FILE_IGNORE_NEW_LINES
FILE_SKIP_EMPTY_LINES
PHP Filter Functions
PHP Filter Introduction
This PHP filters is used to validate and filter data coming from insecure sources, like user input.
Installation
The filter functions are part of the PHP core. There is no installation needed to use these functions.
PHP Filter Functions
PHP: indicates the earliest version of PHP that supports the function.
Function
Description
PHP
filter_has_var()
Checks if a variable of a specified input type exist
5
filter_id()
Returns the ID number of a specified filter
5
filter_input()
Get input from outside the script and filter it
5
filter_input_array()
Get multiple inputs from outside the script and filters them
5
filter_list()
Returns an array of all supported filters
5
filter_var_array()
Get multiple variables and filter them
5
UNIT – I By P.V.Ravikanth, 8019594355
31
OPEN SOURCE SOFTWARE
filter_var()
Get a variable and filter it
5
PHP Filters
ID Name
Description
FILTER_CALLBACK
Call a user-defined function to filter data
FILTER_SANITIZE_STRING
Strip tags, optionally strip or encode special characters
FILTER_SANITIZE_STRIPPED
Alias of "string" filter
FILTER_SANITIZE_ENCODED
URL-encode string, optionally strip or encode special characters
FILTER_SANITIZE_SPECIAL_CHARS
HTML-escape '"<>& and characters with ASCII value less than 32
FILTER_SANITIZE_EMAIL
Remove all characters, except letters, digits and !#$%&'*+-/=?^_`{|}~@.[]
FILTER_SANITIZE_URL
FILTER_SANITIZE_NUMBER_INT
Remove
all
characters,
except
letters,
_.+!*'(),{}|\\^~[]`<>#%";/?:@&=
Remove all characters, except digits and +-
FILTER_SANITIZE_NUMBER_FLOAT
Remove all characters, except digits, +- and optionally .,eE
FILTER_SANITIZE_MAGIC_QUOTES
Apply addslashes()
FILTER_UNSAFE_RAW
Do nothing, optionally strip or encode special characters
FILTER_VALIDATE_INT
Validate value as integer, optionally from the specified range
FILTER_VALIDATE_BOOLEAN
FILTER_VALIDATE_FLOAT
Return TRUE for "1", "true", "on" and "yes", FALSE for "0", "false", "off",
"no", and "", NULL otherwise
Validate value as float
FILTER_VALIDATE_REGEXP
Validate value against regexp, a Perl-compatible regular expression
FILTER_VALIDATE_URL
Validate value as URL, optionally with required components
FILTER_VALIDATE_EMAIL
Validate value as e-mail
FILTER_VALIDATE_IP
Validate value as IP address, optionally only IPv4 or IPv6 or not from
private or reserved ranges
digits
and
$-
PHP FTP Introduction
The FTP functions give client access to file servers through the File Transfer Protocol (FTP).
The FTP functions are used to open, login and close connections, as well as upload, download, rename, delete, and
get information on files from file servers. Not all of the FTP functions will work with every server or return the same
results. The FTP functions became available with PHP 3.
These functions are meant for detailed access to an FTP server. If you only wish to read from or write to a file on an
FTP server, consider using the ftp:// wrapper with the Filesystem functions.
Installation
The windows version of PHP has built-in support for the FTP extension. So, the FTP functions will work automatically.
However, if you are running the Linux version of PHP, you will have to compile PHP with --enable-ftp (PHP 4+) or -with-ftp (PHP 3) to get the FTP functions to work.
PHP FTP Functions
PHP: indicates the earliest version of PHP that supports the function.
Function
Description
PHP
ftp_alloc()
Allocates space for a file to be uploaded to the FTP server
5
ftp_cdup()
Changes the current directory to the parent directory on the FTP server
3
UNIT – I By P.V.Ravikanth, 8019594355
32
OPEN SOURCE SOFTWARE
ftp_chdir()
Changes the current directory on the FTP server
3
ftp_chmod()
Sets permissions on a file via FTP
5
ftp_close()
Closes an FTP connection
4
ftp_connect()
Opens an FTP connection
3
ftp_delete()
Deletes a file on the FTP server
3
ftp_exec()
Executes a program/command on the FTP server
4
ftp_fget()
Downloads a file from the FTP server and saves it to an open file
3
ftp_fput()
Uploads from an open file and saves it to a file on the FTP server
3
ftp_get_option()
Returns runtime behaviors of the FTP connection
4
ftp_get()
Downloads a file from the FTP server
3
ftp_login()
Logs on to an FTP connection
3
ftp_mdtm()
Returns the last modified time of a specified file
3
ftp_mkdir()
Creates a new directory on the FTP server
3
ftp_nb_continue()
Continues retrieving/sending a file (non-blocking)
4
ftp_nb_fget()
Downloads a file from the FTP server and saves it to an open file (non-blocking) 4
ftp_nb_fput()
Uploads from an open file and saves it to a file on the FTP server (non-blocking) 4
ftp_nb_get()
Downloads a file from the FTP server (non-blocking)
4
ftp_nb_put()
Uploads a file to the FTP server (non-blocking)
4
ftp_nlist()
Lists the files in a specified directory on the FTP server
3
ftp_pasv()
Turns passive mode on or off
3
ftp_put()
Uploads a file to the FTP server
3
ftp_pwd()
Returns the current directory name
3
ftp_quit()
Alias of ftp_close()
3
ftp_raw()
Sends a raw command to the FTP server
5
ftp_rawlist()
Returns a detailed list of files in the specified directory
3
ftp_rename()
Renames a file or directory on the FTP server
3
ftp_rmdir()
Removes a directory on the FTP server
3
ftp_set_option()
Sets runtime options for the FTP connection
4
UNIT – I By P.V.Ravikanth, 8019594355
33
OPEN SOURCE SOFTWARE
ftp_site()
Sends a SITE command to the server
3
ftp_size()
Returns the size of the specified file
3
ftp_ssl_connect()
Opens a secure SSL-FTP connection
4
ftp_systype()
Returns the system type identifier of the FTP server
3
PHP FTP Constants
PHP: indicates the earliest version of PHP that supports the constant.
Constant
Description
PHP
FTP_ASCII
3
FTP_TEXT
3
FTP_BINARY
3
FTP_IMAGE
3
FTP_TIMEOUT_SEC
3
FTP_AUTOSEEK
4
FTP_AUTORESUME
Determine resume position and start position for get and put requests automatically
4
FTP_FAILED
Asynchronous transfer has failed
4
FTP_FINISHED
Asynchronous transfer has finished
4
FTP_MOREDATA
Asynchronous transfer is still active
4
PHP 5 String Functions
The PHP string functions are part of the PHP core. No installation is required to use these functions.
Function
Description
addcslashes()
Returns a string with backslashes in front of the specified characters
addslashes()
Returns a string with backslashes in front of predefined characters
bin2hex()
Converts a string of ASCII characters to hexadecimal values
chop()
Removes whitespace or other characters from the right end of a string
chr()
Returns a character from a specified ASCII value
chunk_split()
Splits a string into a series of smaller parts
convert_cyr_string()
Converts a string from one Cyrillic character-set to another
convert_uudecode()
Decodes a uuencoded string
convert_uuencode()
Encodes a string using the uuencode algorithm
count_chars()
Returns information about characters used in a string
crc32()
Calculates a 32-bit CRC for a string
crypt()
One-way string encryption (hashing)
echo()
Outputs one or more strings
explode()
Breaks a string into an array
UNIT – I By P.V.Ravikanth, 8019594355
34
OPEN SOURCE SOFTWARE
fprintf()
Writes a formatted string to a specified output stream
get_html_translation_table()
Returns the translation table used by htmlspecialchars() and htmlentities()
hebrev()
Converts Hebrew text to visual text
hebrevc()
Converts Hebrew text to visual text and new lines (\n) into <br>
hex2bin()
Converts a string of hexadecimal values to ASCII characters
html_entity_decode()
Converts HTML entities to characters
htmlentities()
Converts characters to HTML entities
htmlspecialchars_decode()
Converts some predefined HTML entities to characters
htmlspecialchars()
Converts some predefined characters to HTML entities
implode()
Returns a string from the elements of an array
join()
Alias of implode()
lcfirst()
Converts the first character of a string to lowercase
levenshtein()
Returns the Levenshtein distance between two strings
localeconv()
Returns locale numeric and monetary formatting information
ltrim()
Removes whitespace or other characters from the left side of a string
md5()
Calculates the MD5 hash of a string
md5_file()
Calculates the MD5 hash of a file
metaphone()
Calculates the metaphone key of a string
money_format()
Returns a string formatted as a currency string
nl_langinfo()
Returns specific local information
nl2br()
Inserts HTML line breaks in front of each newline in a string
number_format()
Formats a number with grouped thousands
ord()
Returns the ASCII value of the first character of a string
parse_str()
Parses a query string into variables
print()
Outputs one or more strings
printf()
Outputs a formatted string
quoted_printable_decode()
Converts a quoted-printable string to an 8-bit string
quoted_printable_encode()
Converts an 8-bit string to a quoted printable string
quotemeta()
Quotes meta characters
rtrim()
Removes whitespace or other characters from the right side of a string
setlocale()
Sets locale information
sha1()
Calculates the SHA-1 hash of a string
sha1_file()
Calculates the SHA-1 hash of a file
similar_text()
Calculates the similarity between two strings
soundex()
Calculates the soundex key of a string
UNIT – I By P.V.Ravikanth, 8019594355
35
OPEN SOURCE SOFTWARE
sprintf()
Writes a formatted string to a variable
sscanf()
Parses input from a string according to a format
str_getcsv()
Parses a CSV string into an array
str_ireplace()
Replaces some characters in a string (case-insensitive)
str_pad()
Pads a string to a new length
str_repeat()
Repeats a string a specified number of times
str_replace()
Replaces some characters in a string (case-sensitive)
str_rot13()
Performs the ROT13 encoding on a string
str_shuffle()
Randomly shuffles all characters in a string
str_split()
Splits a string into an array
str_word_count()
Count the number of words in a string
strcasecmp()
Compares two strings (case-insensitive)
strchr()
Finds the first occurrence of a string inside another string (alias of strstr())
strcmp()
Compares two strings (case-sensitive)
strcoll()
Locale based string comparison
strcspn()
strip_tags()
Returns the number of characters found in a string before any part of some specified characters are
found
Strips HTML and PHP tags from a string
stripcslashes()
Unquotes a string quoted with addcslashes()
stripslashes()
Unquotes a string quoted with addslashes()
stripos()
Returns the position of the first occurrence of a string inside another string (case-insensitive)
stristr()
Finds the first occurrence of a string inside another string (case-insensitive)
strlen()
Returns the length of a string
strnatcasecmp()
Compares two strings using a "natural order" algorithm (case-insensitive)
strnatcmp()
Compares two strings using a "natural order" algorithm (case-sensitive)
strncasecmp()
String comparison of the first n characters (case-insensitive)
strncmp()
String comparison of the first n characters (case-sensitive)
strpbrk()
Searches a string for any of a set of characters
strpos()
Returns the position of the first occurrence of a string inside another string (case-sensitive)
strrchr()
Finds the last occurrence of a string inside another string
strrev()
Reverses a string
strripos()
Finds the position of the last occurrence of a string inside another string (case-insensitive)
strrpos()
Finds the position of the last occurrence of a string inside another string (case-sensitive)
strspn()
strstr()
Returns the number of characters found in a string that contains only characters from a specified
charlist
Finds the first occurrence of a string inside another string (case-sensitive)
strtok()
Splits a string into smaller strings
UNIT – I By P.V.Ravikanth, 8019594355
36
OPEN SOURCE SOFTWARE
strtolower()
Converts a string to lowercase letters
strtoupper()
Converts a string to uppercase letters
strtr()
Translates certain characters in a string
substr()
Returns a part of a string
substr_compare()
Compares two strings from a specified start position (binary safe and optionally case-sensitive)
substr_count()
Counts the number of times a substring occurs in a string
substr_replace()
Replaces a part of a string with another string
trim()
Removes whitespace or other characters from both sides of a string
ucfirst()
Converts the first character of a string to uppercase
ucwords()
Converts the first character of each word in a string to uppercase
vfprintf()
Writes a formatted string to a specified output stream
vprintf()
Outputs a formatted string
vsprintf()
Writes a formatted string to a variable
wordwrap()
Wraps a string to a given number of characters
PHP -Regular Expressions
Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the foundation for
pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can replace one string by
another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to a certain type of
regular expression. You can use any of them based on your comfort.

POSIX Regular Expressions

PERL Style Regular Expressions
POSIX Regular Expressions:
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression: various
elements (operators) are combined to form more complex expressions.
The simplest regular expression is one that matches a single character, such as g, inside strings such as g, haggle, or
bag.
Lets give explaination for few concepts being used in POSIX regular expression. After that we will introduce you wih
regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to find a range
of characters.
Expression
Description
[0-9]
It matches any decimal digit from 0 through 9.
[a-z]
It matches any character from lowercase a through lowercase z.
[A-Z]
It matches any character from uppercase A through uppercase Z.
[a-Z]
It matches any character from lowercase a through uppercase Z.
UNIT – I By P.V.Ravikanth, 8019594355
37
OPEN SOURCE SOFTWARE
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit ranging from 0
through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Quantifiers:
The frequency or position of bracketed character sequences and single characters can be denoted by a special
character. Each pecial character having a specific connotation. The +, *, ?, {int. range}, and $ flags all follow a
character sequence.
Expression
Description
p+
It matches any string containing at least one p.
p*
It matches any string containing zero or more p's.
p?
It matches any string containing zero or more p's. This is just an alternative way to use p*.
p{N}
It matches any string containing a sequence of N p's
p{2,3}
It matches any string containing a sequence of two or three p's.
p{2, }
It matches any string containing a sequence of at least two p's.
p$
It matches any string with p at the end of it.
^p
It matches any string with p at the beginning of it.
Examples:
Following examples will clear your concepts about matching chracters.
Expression
Description
[^a-zA-Z]
It matches any string not containing any of the characters ranging from a through z and A through Z.
p.p
It matches any string containing p, followed by any character, in turn followed by another p.
^.{2}$
It matches any string containing exactly two characters.
<b>(.*)</b>
It matches any string enclosed within <b> and </b>.
p(hp)*
It matches any string containing a p followed by zero or more instances of the sequence hp.
Predefined Character Ranges
For your programming convenience several predefined character ranges, also known as character classes, are
available. Character classes specify an entire range of characters, for example, the alphabet or an integer set:
Expression
Description
[[:alpha:]]
It matches any string containing alphabetic characters aA through zZ.
[[:digit:]]
It matches any string containing numerical digits 0 through 9.
[[:alnum:]]
It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
[[:space:]]
It matches any string containing a space.
PHP's Regexp POSIX Functions
PHP currently offers seven functions for searching strings using POSIX-style regular expressions:
Function
Description
UNIT – I By P.V.Ravikanth, 8019594355
38
OPEN SOURCE SOFTWARE
ereg()
The ereg() function searches a string specified by string for a string specified by pattern, returning true if the pattern is found, and
false otherwise.
ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces pattern with replacement if found.
eregi()
The eregi() function searches throughout a string specified by pattern for a string specified by string. The search is not case
sensitive.
eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the search for pattern in string is not case sensitive.
split()
The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in
string.
spliti()
The spliti() function operates exactly in the same manner as its sibling split(), except that it is not case sensitive.
sql_regcase()
The sql_regcase() function can be thought of as a utility function, converting each character in the input parameter string into a
bracketed expression containing two characters.
PERL Style Regular Expressions:
Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used almost
interchangeably with the Perl-style regular expression functions. In fact, you can use any of the quantifiers introduced
in the previous POSIX section.
Lets give explaination for few concepts being used in PERL regular expressions. After that we will introduce you wih
regular expression related functions.
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the combination a
special meaning.
For instance, you can search for large money sums using the '\d' metacharacter: /([\d]+)000/, Here \d will search for
any string of numerical character.
Following is the list of metacharacters which can be used in PERL Style Regular Expressions.
Character
Description
.
a single character
\s
a whitespace character (space, tab, newline)
\S
non-whitespace character
\d
a digit (0-9)
\D
a non-digit
\w
a word character (a-z, A-Z, 0-9, _)
\W
a non-word character
[aeiou]
matches a single character in the given set
[^aeiou]
matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers
Several modifiers are available that can make your work with regexps much easier, like case sensitivity, searching in
multiple lines etc.
Modifier
Description
i
Makes the match case insensitive
m
Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
UNIT – I By P.V.Ravikanth, 8019594355
39
OPEN SOURCE SOFTWARE
o
Evaluates the expression only once
s
Allows use of . to match a newline character
x
Allows you to use white space in the expression for clarity
g
Globally finds all matches
cg
Allows a search to continue even after a global match fails
PHP's Regexp PERL Compatible Functions
PHP offers following functions for searching strings using Perl-compatible regular expressions:
Function
Description
preg_match()
The preg_match() function searches string for pattern, returning true if pattern exists, and false otherwise.
preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular expressions can be used in the pattern and
replacement input parameters.
preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for
pattern.
preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements matching the regexp pattern.
preg_ quote()
Quote regular expression characters
Important Questions:1. Write about open source programming languages?
2. How to PHP support for web environment?
3. What about following words in PHP language?
a)
Variables
e) Statements
b) Constants
f)
Functions
c) data types
g) Arrays
d) operators
4. PHP Language is a Object Oriented Programming language or not? Explain it?
5. Explain about String Manipulation and regular expression in PHP?
6. What a short note on File handling and data storage in PHP?
Notes:-
UNIT – I By P.V.Ravikanth, 8019594355
40
Download