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

Pallavi Engineering College PHP Introduction

Unit-1

History of PHP, Apache Web Server,


MySQL and Open Source
Open Source
• In general, open source refers to any program whose source code is made available for use or modification.
Open source software is usually developed as a public collaboration and made freely available. It means can
be used without purchasing any license.
• Open Source is a certification mark owned by the Open Source Initiative (OSI). Developers of software that is
intended to be freely shared and possibly improved and redistributed by others can use the Open Source
trademark if their distribution terms conform to the OSI's Open Source Definition. To summarize, the
Definition model of distribution terms require that:
 The software being distributed must be redistributed to anyone else without any
restriction.
 The source code must be made available (so that the receiving party will be able to improve or
modify it).
• Example of Open Source: Linux, Apache, MySQL, PHP.

PHP
• PHP is a general‐purpose server‐side scripting language originally designed for web development to produce
dynamic websites.
• PHP scripts execute on web server and serve WebPages to user on request.
• PHP was originally created by Rasmus Lerdorf in 1994. Programmer Rasmus Lerdorf initially created a set of
C scripts he called "Personal Home Page Tools" to maintain his personal homepage. The scripts performed
tasks such as displaying his résumé and recording his web‐page traffic.
• These were released and extended to include a package called the Form Interpreter (PHP/FI). While PHP
originally stood for "Personal Home Page", it is now said to stand for "PHP: Hypertext Preprocessor", a
recursive acronym.
• PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor
module, which generates the web page document. It also has evolved to include a command‐line interface
capability and can be used in standalone graphical applications.PHP can be deployed on most web servers and
as a standalone interpreter, on almost every operating system and platform free of charge.
• In 1997 Zeev Suraski and Andi Gutmans along with Rasmus rewrite PHP and released PHP version 3.0 in
June 1998.After this release PHP becomes so much popular.
• The PHP version 4.0 was launched in May 2000.This version includes session handling, output buffering, a
richer cire language and support for wide variety of web server platforms.
• The PHP 5.0 version released in 2004 with object oriented programming concept.

Apache
1 IV ECE PHP Programming
Pallavi Engineering College PHP Introduction
Web Server
• A Web Server is computer and the program installed on it. Web Server interacts with the client through the
browser. It delivers the web pages to the client and to an application by using the web browser and HTTP
protocol respectively.

2 IV ECE PHP Programming


Pallavi Engineering College PHP Introduction
• We can also define the web server as the package of larger number of programs installed on a computer
connected to internet or intranet for downloading the requested files using File Transfer Protocol, serving e‐
mail and building and publishing web pages.
• A web server works on client server model. A computer connected to internet or intranet must have a server
program.
• A computer connected to the internet for providing the services to a small company or a department store may
contain the HTTP server to access and store WebPages and files, SMTP server to support mail services, FTP
server for files downloading and NNTP server for newsgroup.
• The computer containing all the above servers is called the web server.

Apache Web Server


• The Apache web Server, commonly referred to as Apache is web server software notable for playing a key
role in the initial growth of the World Wide Web.
• The first version of Apache, based on the NCSA httpd Web server, was developed in 1995. The Apache
server has been developed by an open source community ‐ Apache Software Foundation, whose members are
constantly adding new useful functionalities, with the sole purpose of providing a secure and extensible server
platform that ensures HTTP service delivery in accordance with the current HTTP standards.
• The original version of Apache was written for UNIX, but there are now versions that run under OS/2,
Windows and other platforms.
• The Apache Server provides full range of Web Server features, including CGI, SSL and virtual domains.
Apache also supports plug‐in modules for extensibility.
• It was called Apache because it was developed from existing NCSA code plus various patches, hence the
name a patchy server, or Apache server.
• Apache is open source free software distributed by the Apache Software Foundation.
• Apache is reliable, free and relatively easy to configure.

MySQL
• MySQL is a relational database management system (RDBMS) that runs as a server providing multi‐user
access to a number of databases.
• It is named after developer Michael Widenius' daughter, My. The SQL phrase stands for Structured Query
Language.
• The data in MySQL is stored in database objects called tables. A table is a collection of related data entries
and it consists of columns and rows.
• The MySQL development project has made its source code available under the terms of the License. The
license can require improved versions of the software to carry a different name or version from the original
software.
• First released in January,1998, MySQL was owned and sponsored by the Swedish company MySQL AB, now
owned by Oracle Corporation.
• MySQL is fully multithreaded using kernel threads, and provides application programming interfaces (APIs)
for many programming languages, including C,C++, Java, Perl, PHP, Python.

3 IV ECE PHP Programming


PHP Programming _IV_ECE

• MySQL is used in a wide range of applications, including data warehousing, e‐commerce, Web
databases, logging applications and distributed applications.

Relationship between Apache,


MySQL and PHP (AMP Module)
• AMP stands for Apache MySQL PHP

PHP
• PHP is a server side scripting that was designed for creating dynamic websites. It slots into your
Apache web server and processes instructions contained in a web page before that page is sent
through to your web browser.
• PHP is a powerful scripting language that can be run in the command line of any computer with PHP
installed. However, PHP alone isn't enough in order to build dynamic web sites.

Apache
• To use PHP on a web site, you need a server that can process PHP scripts. Apache is a free web
Server that, once installed on a computer, allows developers to test PHP scripts locally; this makes it
an invaluable piece of your local development environment.
• Like all web servers, Apache accepts an HTTP request and serves an HTTP response.

MySQL
• Additionally, dynamic websites are dependent on stored information that can be modified quickly
and easily; this is the main difference between a dynamic site and a static HTML site. However, PHP
doesn’t provide a simple, efficient way to store data. This is where a relational database management
system like MySQL comes into play. PHP provides native support for it and the database is free,
open‐source project.
• MySQL is a relational database management system (DBMS). Essentially, this means that MySQL
allows users to store information in a table‐based structure, using rows and columns to organize
different pieces of data.
• The process of serving a page to the client is explained below:
 Client requests for the web page by entering the URL in the browser using HTTP protocol.
 Upon receiving the request from the user web server trying to locate the requested web
page on the server.
 If the requested page by user does not exist on the server then it will send error
message displaying
 Page cannot found. But if page requested by user exists on the server then it will
process the requested page.
 If the page contains any server side script then it will execute the script.
 After execution of script it will send the page in the form of HTML to the client.
 The client browser processes the page that is returned from the server and displays it.

4
PHP Introduction
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create dynamic
content that interacts with databases. PHP is basically used for developing web based software applications.

Pallavi Engineering College


PHP Programming _IV_ECE

 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".



PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content,
databases, session tracking, even build entire e-commerce sites.
Common uses of PHP
 PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
 PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return
data to the user.
 You add, delete, modify elements within your database thru PHP.
 Access cookies variables and set cookies.
 Using PHP, you can restrict users to access some pages of your website.
 It can encrypt data.
Declaring Variables
In PHP, a variable starts with the $ sign, followed by the name of the variable:
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
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 ($age and $AGE are two different variables).
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 other languages such as C,
C++, and Java, the programmer must declare the name and type of the variable before using it.
PHP Variables Scope

In PHP, variables can be declared anywhere in the script.


The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three
different variable scopes:
 local
 global
 static 5
Global And Local Scope
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function:
<?php

Pallavi Engineering College


PHP Programming _IV_ECE

$x = 5; // global scope

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

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


?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function:
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();

// using x outside the function will generate an error echo


"<p>Variable x outside function is: $x</p>";
?>
PHP Data Types
Variables can store data of different types, and different data types can do different things. PHP
supports the following data types:
 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource
PHP String
A string is a sequence of characters, like "Hello world!".
A string can be any text inside quotes. You can use single or double quotes:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x; echo
"<br>"; echo 6
$y;
?>
PHP Integer

Pallavi Engineering College


PHP Programming _IV_ECE

An integer is a whole number (without decimals). It is a number between -2,147,483,648 and


+2,147,483,647.
Rules for integers:
 An integer must have at least one digit (0-9)
 An integer cannot contain comma or blanks
 An integer must not have a decimal point
 An integer can be either positive or negative
 Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based - prefixed
with 0x) or octal (8-based - prefixed with 0)
In the following example $x is an integer. The PHP var_dump() function returns the data type and value:
<?php
$x = 5985;
var_dump($x);
?>
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true;
$y = false;
PHP Array
An array stores multiple values in one single variable.
In the following example $cars is an array. The PHP var_dump() function returns the data type and value:
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP NULL Value
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Array

An array is a special variable, which can hold more than one value at a time.
7
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";
Pallavi Engineering College
PHP Programming _IV_ECE

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:
In PHP, there are three types of arrays:
 Indexed arrays - Arrays with a 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), like this:
$cars = array("Volvo", "BMW", "Toyota");
The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text
containing the array values:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
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");
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter
is " . $age['Peter'] . " years old.";
?>
Strings
A string is a sequence of characters, like "Hello world!".
Get The Length of a String
The PHP strlen() function returns the length of a string.
The example below returns the length of the string "Hello world!":
<?php
echo strlen("Hello world!"); // outputs 12
?>
Count The Number of Words in a String
The PHP str_word_count() function counts the number of words in a string:
<?php 8
echo str_word_count("Hello world!"); // outputs 2
?>
The output of the code above will be: 2.
Pallavi Engineering College
PHP Programming _IV_ECE

Reverse a String
The PHP strrev() function reverses a string:
<?php
echo strrev("Hello world!"); // outputs !dlrowolleH
?>
String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator −
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce the following result – Hello
World 1234

Using the strpos() function


The strpos() function is used to search for a string or character within a string.
If a match is found in the string, this function will return the position of the first match. If no match is found, it will
return FALSE.
Let's see if we can find the string "world" in our string −
<?php
echostrpos("Hello world!","world");
?>
This will produce the following result −6
(2) operators:An operator is a symbol that specifies a particular action in an expression.operators are classified
into different types
(a) Arithmetic operators
(b)Assignment operators
(c)string operators
(d)Increment and decrement operators
(e)Logical operators
(f)Equality operators
(g)Comparision operators
(h)Bitwise operators
a) Arithmetic operators :The arthimetic operators are

operators Label Example


+ addition $a+$b
- subtraction $a-$b

* Multiplication $a*$b
/ Division $a/$b
% modulus $a%$b 9
b) Assignment operators: Assignment operators mainly used for to assign a data value to a variable. The simplest
form of assignment operator just assigns some value.
Operator Label Example

Pallavi Engineering College


PHP Programming _IV_ECE

= Assignmen $a=5
t
+= Addition-assignment $a+=5
*= multiplication-assignment $a*=5
/= division-assignment $a/=5
.= concatenation-assignment $a.=5
(c) String operators:php’s string operators provide two operators that two operatorsusefull for
concatenation the two strings.
Operator label example output
.concatenation $a= “abc”. “def”; abcdef
.= concatenation-assighment $a.= “ghijkl” ghijkl
(d) increment and decrement operators:
Increment(++) and decrement operators increment by 1 and decrement by 1 from the current value of a variable
Operatorlabelexampleoutput
++ increment ++$a, $a++ increment $a by 1
-- Decrement --$a, $a-- decrement $a by 1
(e) logical operators:
Logical operators make it possible to direct the flow of a program and used frequently with control
structures such as the if conditional and while and loops.
Operatorslabelexampleoutput
&& AND $a&&$b true if both $a and $b are true AND
AND $a AND $b true if both $a and $b are true
|| OR $a || $b true if either $a or $b is true OR
OR $a OR $b true if both $a and $b are true
! NOT !$a true if $a is not true
NOT NOTNOT $a true if $a is not true
XOR exclusive $a XOR $b true if only $a (or) only $b is true
(f) equality operators:
Equality operators are used to compare two values, testing for equivalence
Operatorslabelexample
<less than $a<$b

> Greater than $a>$b


<= less than or equal to $a<=$b
>= greator than or equal to $a=>$b
(g) bitwise operators:
Bitwise operators are used for variations on some of the logical operators
Operatorslabelexampleoutput
& AND $a&$b and together each bit contained in $a and $b
| OR $a|$b or together each bit contained in $a and $b
10
^ XOR $a^$b exclusive-or together each bit
contained in $a and $b
~ NOT ~$b negate each bit in $b
<<shift left $a<<$b $a will receive the value of $b

Pallavi Engineering College


PHP Programming _IV_ECE

shifted left two values.


>> shift right $a>>$b $a will receive the value of $b
shifted right two values.
(3) expressions and statements:-
Expressions:-an expression is a phrase representing a particular action in a program.all expressions consists
of a least one operand ana one (or) more operations
Ex:-
$a=5; //assign inter value 5 to the variable $a
$a=”5”; //assign string value “5” to the variable $a
$a=”abit”; //assign “abit” to the variable $a
Here operends are the input expressions
Ex:-$a++; //$a is the operand
$sum=$val1+val2; //$sum,$val1,$val2 are operends
Statements:-php supports different types of statements like (1)if
statement
(2)else statement
(3)switch statement
(4)while statement
(5)do…while statement
(6)for statement
(7)for each statement (8)break
and goto statement
(9)continue statement
(1) if statement:-
Syntax:-if (expression)
{
Statement
}
->An example,supposeuou want a cougratutory message displayed if the user
guesses apredefimindservet number
<?php
$sescretnumber=143;
If($_POST[‘guess’]==$secretnumber)
{
Echo “<p>congratulation!</p>”;
}
(2) else statement: if the condition si true statement followed if will be execute other else statement will execute
<?php
$sescretnumber=143;
If($_POST[‘guess’]==$secretnumber)
{
Echo “<p>congratulation!</p>”;
}
Else 11
{
Echon “<p>sorry!</p>”;
}
Pallavi Engineering College
PHP Programming _IV_ECE

?>
(4) switch statement:- switch statement can compare “ = “ operations only ex:-
<?php
$x=1;
Switch($x)
{
case 1:
Echo “number1”;
Break;
Case 2:echo “number2”;
Break;
Case 3:
Echo “number3”;
Break;
Default:
Echo “no number b/w 1 and 3”;
}
?>
(5) while statement:- while loop check the condition then only excute the statement when the condition is true.
Syntax:-
While(expression)
{
Statements
}
Ex:-<?php
$count=1;
While($count <5)
{
Printf(“%d sqared=%d <br>”,$count,pow($count,2));
$count++;
}
?>
o/p : 1 squared=1 2
squared=4
3 squared=9
4 squared=16
(6) do while:
It will execute the statement atleast once even condition false(or)true.
Syntax:
<?php
$count=11;
Do
{ 12
Printf(“%d squared=%d<br/>”,$count,pow($count,2));
}
While($count<10);
Pallavi Engineering College
PHP Programming _IV_ECE

?>
(7) for statement: By using this loop we can run number of iteration.
Syntax: for(exp1;exp2;exp3)
{
Statements;
}
There are afew rules to keep in mind when using php’s for loops.
The first expression,exp1,is evaluated by default at the first iteration of the loop
The second expression,exp2 is evaluated at the beginning of each iteration.this expression determines wherher
looping will continue.
The third expression,exp3,is evaluated at conclusion of even loop.

Ex:
<?php
For($kilometers=1;$kilometers<=3;$kilometers++)
{
printf(“%kilometers=%f miles<br/>”,$kilometers,$kilometers*0.62140);
}
?>
o/p:
1 kilometers= 0.6214 miles
2 kilometers=1.2428 miles
3 kilometers =1.8642 miles .
(a)Break and goto statement:-
Break statement:- break statement is end execution of a do while,for,foreach,switch,while block.
Goto statement:- In php goto statement,”BREAK” features was extend to support labels.
This means we can suddenly jump to a specific location outside of a looping or conditional construct.
(10) continue statement:-
Continue statement execute the current loop iteration to the end.

(4) string:- string variable can hold collection of characters . in php we can assign values into the string
variables ‘3’ ways.
-> using single quotation
-> using double quotation
->heradoc style.
->inphp offers approximately 100 function collectively.
->we introduce each function but we have to implement some of the functions of a string.
(1) determining string length
(2) comparing two strings
13
(3) manipulating string case
(4) alternatives for regular expression functions
(5) converting string to and form HTML
(6) padding and stripping a string
Pallavi Engineering College
PHP Programming _IV_ECE

(7) counting characters and works


(1) determining string length:- here we are using strlen() function and this function returns the length of the
string.
Ex:-intstrlen(string str)
(2) comparing two string:- in php provides four functions for performing this task.
1. strcmp ()
2.strcasecmp ()
3.strlen()
4.strcmp()
(1) strcmp():- the strcmp() function performs a binary numbers and compare two strings.
Syntax:-(case-sensitive)
Intstrcmp(string str1,string str2)
0, if str1 and str2 are equal.(s1==s2)
-1, if str1 is less than str2(s1<s2)
1, if str2 is less than str1(s2<s1)
Ex:-<?php
$pwd=”abitcse”;
$pwd2=”abitcse2”;
if
Ex:-<?php
$pwd=”abc123”;
If(strcspn($pwd,”1234567890”)==0) Echo”pwd
can’t consists solely of numbers! }
?>
(2) strspn:- calculating the similarities between two strings.

Syntax: int strspn(string str1,string str2[, int start[, int length]]) Ex:-
<?php
$pwd=”abc123”;
If(strspn($pwd,”1234567890”)==strlen($pwd))
Echo”thepwd cannot consist solely of numbers!”;
?>

(3) mani

Ex:-<?php
$pwd=”abitcse”;
$pwd2=”abitcse2”;
If(strcmp($pwd,$pwd2)!=0)
{
Echo”pwd do not match’;
}
Else
{ 14
Echo”pwd match”;
}
?>
Pallavi Engineering College
PHP Programming _IV_ECE

(2) strcasecmp():- (case-insensitive0


The strcasecmp() function operates exactly like strcmp().
Syntax: intstrcasecmp(string str1,string str2) Ex:-
<?php
$gmail1= ”abit @gmail .com ”;
$gmail2= ” ABIT@ gmail.com ”;
If(!strcasecmp($gmail1,gmail20)
Echo” the gmail addresses are identical! ”;
?>

(3) strspn():- calculating the simirality between two strings.


Syntax;-intstrspn(string str1,string str2 [, int start [, int length]]] Ex:-<?php
$pwd=”abc123”;
If(strspn($pwd,”1234567890”)==strlen($pwd))
Echo “ thepwd cannot consist solely of numbers! “;
?>

(4) strcspn():- calculating difference between two strings.


Syntax:-intstrcspn(string str1,string str2 [, int start [, int length]]) Ex:-<?php
$pwd= “ abc123 “; If(strcspn($pwd,
“1234567890 “)==0)
{
Echo “ pwd can’t consist solely of numbers! “;
}
?>

(3) manipulating string case:-


In this we have to mainely concentrated on four function.

1. Strtolower()
2. Strtoupper()
3. Ucfirst()
4. Ucwords()
(1) Strtolower:- ( converting a string to all lowercase ) Ex:-
<?php
$name= “ bangaram “; Echo str
to lower($name);
?
(2) Strtoupper():- ( converting a string to all uppercase) Ex:-
<?php
$name= “ JAMALBASHA “;
Echo strtoupper
?>

(3) Ucfirst():- ( capitalizing the first letter of a string ) Ex:-


<?php 15
$name=” abit college “;
Echo strucfirst ($name);
?>
Pallavi Engineering College
PHP Programming _IV_ECE

(4) Ucwords():- ( capitalizing the first letter of each words of a string ). Ex;-<?php
$name “ abitengg college “; Echo
ucwords($name)
?>
(4) Alternatives for regular expression function:- in this we have to describe different types of functions. There
are
(a) strtok() (e) strrpos() (i) substr_count()
(b) explodc() (f) str_replace() (j) substr_replace()
(c) implodc() (g) strstr()
(d) strops() (h) substr()
(a) strtok():- this function parses the string based on a predefind list of characters.
Syntax:- string strtok(string str,string tokens)
Ex:-<?php
$into= “ abit: abit@gmail.com\siddavatam,kdp “;
$tokens= “ :\ , ”;
$tokenized= strtok($into,$tokens);
While( $tokenized)
{
Echo “ elements = $tokenized<br>”;
$tokenized=strtok($tokens);
}
?>
(b) explode():-this function devides the string str into an array of substrings,in this we have to mainly
concentrated areas are size of ( ) and stip-tags( ) to determine the total number of words. Ex: <? Php
$summary==<<<summery
Php is a server side scripting language.
Summary;
$words=size of(explode(‘ ‘,strip-tags($summary))); Echo”
total words in summary;$words”;
?>
(c) implode( ):-we concatenate array elements to form a single delimited string using the implode( )
function.
Ex: <? Php
$cites=array(“kdp”,”antpr”,”tirupathi”.); Echo
implode(“\”,$cities);
?>
o/pkdp\antpr\tirupathi
(d) strops(): in this function finds the position of the first case_sensitiveoccurance of a substring in a string.
(e) strrpos():- in this function finds the last occurance of a string returning it’s numerical position.
(f) str_replace():-this function case sensitively replaces all instance of a string with another. Ex:-<?php
$gmail= “abit@gmail.com “;
$gmail=str_replace(“@”, ”(is)”, $gmail); Echo
“college mail is $gmail; 16
?>
(g) strstr():- this function returns the remainder of a string beginning with the first occurance of a predefined
string.
Ex:-<?php

Pallavi Engineering College


PHP Programming _IV_ECE

$gmail= “ abit@gmail.com “;
Echo ltrim (strstr ($gmail, “@”), “@”);
?>
(h) substr():- this function returns the part of a string located between a predefined string offset and length
positions.
Ex:-<?php
$car= “ 1994 ford “; Echo
substr( $car,5);
?>
Ex2:- <?php
$car= “ 1944 ford “; Echo
substr( $car,0,4);
?>
(i) substr-count() :thisfunctionreturns the no.of times one string excuss another
Ex:<?php
$intu=array(“php”, “XAMPP”);
$talk=<<<talk
PHP is a scriptin language and php is server side
Programming language.XAMPP is a web server Talk:
Foreach($info as $it)
{
Echo “the word $it appears”.substr_count($talk,$it). “time(s)<br>/>”;
}
?>
(j) substr-replace():replace the portion of a string with another string
Ex:<?php
$name=”Abitcollege”;
Echo substr_replace($name, “engg”,0,4);
?>
(5) converting string to HTML form:- in this we are using different types of converting function .there
are
-> Converting newline characters to HTML break tags. Ex:-<?php
$info=”aaaaaaaaaaaaaaaaaaaaaaa
Bbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc
ddddddddddddddddddd”;
echo n12br($into);
?>
Here we are not use <br> statement.
->using special HTML characters for other purpose. In this we using htmlspecialchars() function.
->& ->&amp;
-> “ ->&quoit;
17

-> ‘ ->&#039;
->< ->&1t;

Pallavi Engineering College


PHP Programming _IV_ECE

->> ->&gt;
Ex:-<?php
$input= “<php is “scripting” language>”; Echo
html\specialchars($input);
?>
(6) padding and stripping a string:- php provides no. of functions there are
(a) ltrim()
(b) rtrim()
(c) trim()
(d) str_pad()
(a) ltrim():- this function removes various characters from the beginning of a string including white space,
horizontal tab(\t), newline(\n), carriage return(\v), null(\o).
String ltrim(string str [, string [, string charlist])

(b) rtrim():- this function removes various characters from the end of the string and except designated
characters.
String rtrim(string str [, string charlist])

(c) trim():-both l trim and r trim


(d) str_pad():- this function pads a string with a specified number of characters. Ex:-<?php
Echo str_pad( “salad”,10). “is good.”;
?>output:- salad is good
(7) counting characters and words:- it’s mainely used for to determine the total number of characters or
words in a given string. Php provides two functions. there are count_chars() and str_word_count.
(5) arrays and functions:- array is a collection of heterogeneous(different elements) data types in php. Because
php is a loosely typed language.
Ex:-<?php
$arr=array(10,20,30);
Print_r($str);
?>output:- [0]=10,[1]=20,[2]=30
Ex2:- <?php
$arr=array(100->10, 101->20, ->102=>30);
Print_r($arr);
?>output:-[100]=10, [101]=20, [102]=30
Ex3:- <?php
$arr=array(100=>10,20,30, 106=>30);
Print_r($arr);
?>output:- [100]=10,[101]=20,[102]=30,[106]=30
Ex:-<?php
$arr=array(100=>10, ‘city’=> ’hyd’, 105=>30, 50=>40,70); Print_r($arr);
?>output:-[100]=40,[city]=hyd,[105]=30,[50]=40,[106]=70
Array functions:- 18
Count:- it returns total no. of elements Ex:-
<?php
$arr=array(10,20,30);

Pallavi Engineering College


PHP Programming _IV_ECE

Echo count($arr);
?>output:- 3
Sort :- it returns the elements of an array in assending order. Ex:-<?php
$arr=array(60,20,30);
Sort($arr);
Print_r($arr);
?>output:- 20,30,60
rsort :- it returns the elements of an array in descending order. Ex:-<?php
$arr=array(101,104,102);
rsort_r($arr);
print_r($arr);
?> output:-104,102,101
asort:- it returns the original keys with assending order. Ex:-<?php
$arr=array(104=>40, 101=>20, 108=>50, 102=>80);
assort($arr);
print_r($arr);
?> output:- 101=20,104=40,108=50,102=80
arsort:-it returns the original key values with descending order. Ex:-<?php
$arr=array(104=>40, 101=>20, 108=>50, 102=>80);
arsort($arr);
Print_r($arr);
?>ouput:-[102]=80,[108]=50,[104]=40,[101=20
ksort:-it returns the array in assending order with based on the“keys”. Ex:-<?php
$arr=array(104=>40,101=>20,108=>50,102=>80);
Ksort($arr);
Print_r($arr);
?> output:-[101]=20,[102]=80,[104]=40,[108]=50
krsort:- it returns the array in dessending order with based on “keys”. Ex:-<?php
$arr=array(104=>40,101=>20,108=>50,102=>80);
Krsort($arr);
Print_r($arr);
?> output:-[108]=50,[104]=40,[102]=80,[101]=20
array push():- this function adds an elements into the end of an array and returns the total no. of
elements in that array.
Ex:-<?php
$arr=array(10,20,30); Echo
array_push($arr,40);
Print_r($arr);
?> output:-
array_pop():- remove the last element & return the value of that element. Ex:-<?php
$arr=array(10,20,30);
Echo array_pop($arr);
Print_r($arr);
?> output:-
19
array_shift():-it removes the first element of an array and returns the value of that element.
Ex:-<?php
$arr=array(10,20,30); Echo
array_shift($arr);
Pallavi Engineering College
PHP Programming _IV_ECE

Print_r($arr);
?> output:-
array_unshift():- add an element at the beginning of an array and return size of an array.
Ex:-<?php
$arr=array(10,20,30);
Echo array_unshift($arr);
Print_r($arr);
?> output:-
array_change_key_case():- it converts all keys of an array into lower case. Ex:-<?php
$arr=array(‘ABC’=>10,20,30);
Print_r(array_change_key_case($arr));
?> output:-
array_chunk():- splits an array into chunk of an array. Ex:-<?php
$arr=array(10,20,30,40,50,60);
Print_r(array_chunk($arr,2));
?> output:-
array_combine():- creats an array by using one array one array for keys and another for it’s value.
Ex:-<?php
$arr=array( ‘abc’=>10,20,30,40,50);
$arr1=array(100,200,300,400,500);
Print_r(array_combine($arr,$arr1));
?> output:-
array_keys:- it returns new array with keys as value of another array. Ex:-<?php
$arr=array(‘abc’=>10,20,30,40);
Print_r(array_keys($arr));
?> output:-
array_count_values():- returns an array with no of occurance for each value. Ex:-<?php
$arr=array(‘ABC’=>10,20,30,40,50,10);
Printf_r(array_count_values($arr));
?>
array_values():=return array with the values of an array
ex:- <?php
$arr=array(‘ABC’=10,20,30,40,50,60);
Printf_r(array_values($arr));
?>
array_flip():-exchanges all keys with their associated values in array ex:-<?php
$arr=array(‘ABC’->10,20,30,40);
//$arr=array(10,200,400);
Printf_r(array-flip($arr));
?>
array_interest():-compaves array values and returns the matches ex:-<?php
$arr=array(10,20,30,40);
20
$arr=array(100,200,300,400,10);
Printf_r(array_interest($arr)); //($arr,$arr1)
?>

Pallavi Engineering College


PHP Programming _IV_ECE

array_interest_assoc():-compaves array key and values and returns the matches ex:-<?php
$arr=array(10,20,30,40);
$arr1=array(100,200,300,400,0=>10);
Printf_r(array_interest_assoc($arr,$arr1));
?>
array_merge():-merges one or more arrays into one array
ex:-<?php
$arr=array(‘ABC’=>10,20,30,40);
$arr=array(100,200,300);
Printf_r(array-merge($arr,$arr1));
?>
array_product():-returns the product of all array element values ex:-<?php
$arr=array(‘ABC’=>10,20,30,40);
Echo print_r(array_product($arr));
?>
array_sum():-returns the sum of all elements of an array ex:-<?php
$arr=array(10,20,30,40);
Echo print_r(array_sum($arr));
?>
array_reverse():-it revers the elements of an array ex:-<?php
$arr=array(10,20,30,40);
Print_r(array_reverse($arr));
?>
array_unique():-removes the duplicate values and returns the values of an array ex:-<?php
$arr=(‘ABC’=>10,20,30,40);
Print_r(array_unique($arr));
?>
shuffle():-shuffle the elements of an array ex:-
<?php
$arr=array(‘ABC’=>10,20,30,40);
Shuffle($arr);
Print_r($arr);
?>
extract():-divides the elements of an array as individual variables ex:-<?php
$arr=array(‘ABC’=>10,20,30,40);
Extract($arr);
Echo $ABC;
?>
list():-assign variables as it they were an array means that,we can assign the values of an array into
variables
21

Pallavi Engineering College


PHP Programming _IV_ECE

Ex:-<?php
List($x,$y,$z)=array(10,20,30);
Echo $x;
Echo $y;
Echo $z;

PHP User Defined Functions


Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used
repeatedly in a program. A function will not execute
immediately when a page loads.
A function will be executed by a call to the function.

Create a User Defined Function in PHP


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

Syntax
function functionName() {
code to be executed;
}

In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code and the closing curly brace (
} ) indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name:

Example
<?php
function writeMsg() {
echo "Hello world!";
}

writeMsg(); // call the function


?>

PHP Function Arguments


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

Arguments are specified after the function name, inside the parentheses. You can add 22
as many arguments as you want, just seperate them with a comma.

The following example has a function with one argument ($fname). When the

Pallavi Engineering College


PHP Programming _IV_ECE

familyName() function is called, we also pass along a name (e.g. Jani), and the name
is used inside the function, which outputs several different first names, but an equal
last name:

Example
<?php
function familyName($fname)
{
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>

Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}

familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>

PHP Default Argument Value


The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:

Example
<?php
function
setHeight($minheight =
50) { echo "The height is
23
: $minheight <br>";
}

setHeight(350);
Pallavi Engineering College
PHP Programming _IV_ECE

setHeight(); // will use the


default value of 50
setHeight(135);
setHeight(80);
?>

PHP Functions - Returning values


To let a function return a value, use the return statement:
<?php
function sum($x, $y) {
$z=$x+$y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7,
13) . "<br>"; echo "2 + 4
= " . sum(2, 4);
?>

24

Pallavi Engineering College


PHP Programming _IV_ECE

Unit-2

Variable functions

PHP supports the concept of variable functions. This means that if a variable name has parentheses
appended to it, PHP will look for a function with the same name as whatever the variable evaluates to,
and will attempt to execute it. Among other things, this can be used to implement callbacks, function
tables, and so forth.

Variable functions won't work with language constructs such


as echo, print, unset(), isset(), empty(), include, require and the like. Utilize wrapper functions to make
use of any of these constructs as variable functions.

Example #1 Variable function example

<?php
function foo() {
echo "In foo()<br />\n";
}

function bar($arg = '')


{
echo "In bar(); argument was '$arg'.<br />\n";
}

// This is a wrapper function around echo


function echoit($string)
{
echo $string;
}

$func = 'foo';
$func(); // This calls foo()

$func = 'bar';
$func('test'); // This calls bar()

$func = 'echoit';
$func('test'); // This calls echoit()
?>

User-defined functions ¶
25
A function may be defined using syntax such as the following:

Example #1 Pseudo code to demonstrate function uses


Pallavi Engineering College
PHP Programming _IV_ECE

<?php
function foo($arg_1, $arg_2, /* ..., */ $arg_n)
{
echo "Example function.\n";
return $retval;
}
?>

Any valid PHP code may appear inside a function, even other functions and class definitions.

Function names follow the same rules as other labels in PHP. A valid function name starts with a letter
or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it
would be expressed thus: ^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$.

Tip
See also the Userland Naming Guide.

Functions need not be defined before they are referenced, except when a function is conditionally
defined as shown in the two examples below.

When a function is defined in a conditional manner such as the two examples shown. Its definition
must be processed prior to being called.

Example #2 Conditional functions

<?php

$makefoo = true;

/* We can't call foo() from here


since it doesn't exist yet,
but we can call bar() */

bar();

if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.\n";
}
}

/* Now we can safely call foo()


since $makefoo evaluated to true */

if ($makefoo) foo();
26
function bar()
{
echo "I exist immediately upon program start.\n";
Pallavi Engineering College
PHP Programming _IV_ECE

?>

Example #3 Functions within functions

<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.\n";
}
}

/* We can't call bar() yet


since it doesn't exist. */

foo();

/* Now we can call bar(),


foo()'s processing has
made it accessible. */

bar();

?>

All functions and classes in PHP have the global scope - they can be called outside a function even if
they were defined inside and vice versa.

PHP does not support function overloading, nor is it possible to undefine or redefine previously-
declared functions.

Note: Function names are case-insensitive, though it is usually good form to call functions as they
appear in their declaration.

Both variable number of arguments and default arguments are supported in functions. See also the
function references for func_num_args(), func_get_arg(), and func_get_args() for more information.

It is possible to call recursive functions in PHP.

Example #4 Recursive functions

<?php
function recursion($a)
27
{
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
Pallavi Engineering College
PHP Programming _IV_ECE

}
}
?>
Function arguments ¶

Information may be passed to functions via the argument list, which is a comma-delimited list of
expressions. The arguments are evaluated from left to right.

PHP supports passing arguments by value (the default), passing by reference, and default argument
values. Variable-length argument lists are also supported.

Example #1 Passing arrays to functions

<?php
function takes_array($input)
{
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
?>
Passing arguments by reference ¶

By default, function arguments are passed by value (so that if the value of the argument within the
function is changed, it does not get changed outside of the function). To allow a function to modify its
arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the
argument name in the function definition:

Example #2 Passing function parameters by reference

<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str; // outputs 'This is a string, and something extra.'
?>
Default argument values ¶

A function may define C++-style default values for scalar arguments as follows:

Example #3 Use of default parameters in functions

<?php
function makecoffee($type = "cappuccino") 28
{
return "Making a cup of $type.\n";
}

Pallavi Engineering College


PHP Programming _IV_ECE

echo makecoffee();
echo makecoffee(null);
echo makecoffee("espresso");
?>

The above example will output:

Making a cup of cappuccino.


Making a cup of .
Making a cup of espresso.

PHP also allows the use of arrays and the special type NULL as default values, for example:

Example #4 Using non-scalar types as default values

<?php
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL
)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
?>

The default value must be a constant expression, not (for example) a variable, a class member or a
function call.

Note that when using default arguments, any defaults should be on the right side of any non-default
arguments; otherwise, things will not work as expected. Consider the following code snippet:

Example #5 Incorrect usage of default function arguments

<?php
function makeyogurt($type = "acidophilus", $flavour)
{
return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry"); // won't work as expected


?>

The above example will output:

Warning: Missing argument 2 in call to makeyogurt() in


/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41 29
Making a bowl of raspberry .

Now, compare the above with this:

Pallavi Engineering College


PHP Programming _IV_ECE

Example #6 Correct usage of default function arguments

<?php
function makeyogurt($flavour, $type = "acidophilus")
{
return "Making a bowl of $type $flavour.\n";
}

echo makeyogurt("raspberry"); // works as expected


?>

The above example will output:

Making a bowl of acidophilus raspberry.


PHP functions are similar to other programming languages. A function is a piece of code which takes
one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but
PHP gives you option to create your own functions as well.
There are two parts which should be clear to you −

 Creating a PHP Function


 Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more than 1000 of
built-in library functions created for different area and you just need to call them according to your
requirement.
Please refer to PHP Function Reference for a complete set of useful functions.

Creating PHP Function

Its very easy to create your own PHP function. Suppose you want to create a PHP function which will
simply write a simple message on your browser when you will call it. Following example creates a
function called writeMessage() and then calls it just after creating it.
Note that while creating a function its name should start with keyword function and all the PHP code
should be put inside { and } braces as shown in the following example below −
Live Demo
<html>

<head>
<title>Writing PHP Function</title>
</head>

<body>
30
<?php
/* Defining a PHP Function */
function writeMessage() {

Pallavi Engineering College


PHP Programming _IV_ECE

echo "You are really a nice person, Have a nice time!";


}

/* Calling a PHP Function */


writeMessage();
?>

</body>
</html>
This will display following result −
You are really a nice person, Have a nice time!

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass as many as parameters
your like. These parameters work like variables inside your function. Following example takes two
integer parameters and add them together and then print them.
Live Demo
<html>

<head>
<title>Writing PHP Function with Parameters</title>
</head>

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

</body>
</html>
This will display following result −
Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a reference to the variable
is manipulated by the function rather than a copy of the variable's value. 31

Any changes made to an argument in these cases will change the value of the original variable. You
can pass an argument by reference by adding an ampersand to the variable name in either the function
call or the function definition.
Pallavi Engineering College
PHP Programming _IV_ECE

Following example depicts both the cases.


Live Demo
<html>

<head>
<title>Passing Argument by Reference</title>
</head>

<body>

<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

</body>
</html>
This will display following result −
Original Value is 10
Original Value is 16

PHP Functions returning value

A function can return a value using the return statement in conjunction with a value or object. return
stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to
the calling program. Note that return keyword is used to return a value from a function.
Live Demo
<html> 32

<head>
<title>Writing PHP Function which returns value</title>
</head>
Pallavi Engineering College
PHP Programming _IV_ECE

<body>

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function : $return_value";


?>

</body>
</html>
This will display following result −
Returned value from the function : 30

Setting Default Values for Function Parameters

You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
Live Demo
<html>

<head>
<title>Writing PHP Function which returns value</title>
</head>

<body>

<?php
function printMe($param = NULL) {
print $param;
}

printMe("This is test");
printMe();
?>

</body>
</html>
This will produce following result −
33
This is test

Dynamic Function Calls

Pallavi Engineering College


PHP Programming _IV_ECE

It is possible to assign function names as strings to variables and then treat these variables exactly as
you would the function name itself. Following example depicts this behaviour.
Live Demo
<html>

<head>
<title>Dynamic Function Calls</title>
</head>

<body>

<?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>

</body>
</html>

PHP String Functions


PHP provides nearly one hundred functions that can manipulate strings in various ways. Some (but not
all!) of the functions that can be performed on strings are:

Compare Two Strings


Find a String In Another String
Find Out How Many Instances of A String Occur In Another String
Return Part of a String
Replace Part of a String
Trim Whitespace From The Ends of a String
Make An Entire String Lowercase or Uppercase
Convert All Applicable Characters In a String to HTML Entities, or Vice Versa
Strip HTML & PHP Tags From Inside of a String

The simplest string functions are those that only require a single parameter. This parameter is the string
itself, which is accepted either as a variable or as a single or double-quoted string. The strlen()
function, for example, will return the length of the string that it is given.

<?php
$string = "What is the definition of a caterpillar?";
echo strlen($string); // Result Will Be 40

echo strlen("A worm in a fur coat!"); // Result Will Be 21 34

$string_length = strlen($string);
// The Length of $string (40) Is Now Stored In $string_length

Pallavi Engineering College


PHP Programming _IV_ECE

?>

As you can see, the results of these functions can be echoed, stored in a variable, etc.

Most functions accept multiple parameters. The strpos() function, for example, searches for
occurrences of a string inside of another string, and requires two parameters in order to function.
Multiple parameter are separated by commas.

<?php
$str = "There were four cats in a boat, one jumped out. How many were left?";
echo strpos($str, "cat"); // Result Will Be 16
?>

The strpos() function will return a number indicating the position of the first match that it encounters.
If you begin to do the counting yourself, you will see that the "c" for "cat" is the 17th character... so
why did the function say 16? This is because most PHP functions begin counting with 0, so the
position of the string's first character is 0, the second character is 1, etc.

(By the way, there were no cats left in the boat, because they were all copy cats.)

Below is a list of fifty useful string functions, along with a brief description and required parameters.

Function(Parameters) Description

echo(string) Outputs Strings

print(string) Outputs a String

printf(string) Outputs a Formatted String

ltrim(string) Strips Whitespace From the Left Side of a String

rtrim(string) Strips Whitespace From the Right Side of a String

trim(string) Strips Whitespace From Both Sides of a String

lcfirst(string) Makes a String's First Character Lowercase

ucfirst(string) Makes a String's First Character Uppercase

strtolower(string) Converts a String to Lowercase Letters

strtoupper(string) Converts a String to Uppercase Letters

str_word_count(string) Count the Number of Words In a String

ucwords(string) Makes the First Character of Each Word In a String Uppercase

wordwrap(string, width, break) Wraps a String to a Given Number of Characters (Default Width: 35
75) (Default Break: \n)

count_chars(string) Returns How Many Times an ASCII Character Occurs Within a

Pallavi Engineering College


PHP Programming _IV_ECE

String & Returns the Information

substr_count(string, substring) Counts the Number of Times a Substring Occurs In a String

str_pad(string, length, pad_string) Pads a String to a New Length

strlen(string) Returns the Length of a String

substr(string, start) Returns a Part of a String (Start Value of "0" to Begin at First
Character)

strrev(string) Reverses a String

str_shuffle(string) Randomly Shuffles All Characters In a String

str_repeat(string, repeat) Repeats a String a Specified Number of Times ("Repeat" Is


Number of Times to Repeat)

strpbrk(string, characters) Searches a String For Any of a Set of Characters

str_replace(find, replace, string) Replaces Some Characters In a String (Case-Sensitive)

substr_replace(string, replacement, Replaces a Part of a String With Another String


start)

stristr(string, search) Finds the First Occurrence of a String Inside Another String
(Case-Insensitive)

strstr(string, search) Finds the First Occurrence of a String Inside Another String
(Case-Sensitive)

strrchr(string, char) Finds the Last Occurrence of a String Inside Another String

stripos(string, find) Returns the Position of the First Occurrence of a String Inside
Another String (Case-Insensitive)

strpos(string, find) Returns the Position of the First Occurrence of a String Inside
Another String (Case-Sensitive)

strripos(string, find) Returns the Position of the Last Occurrence of a String Inside
Another String (Case-Insensitive)

strrpos(string, find) Returns the Position of the Last Occurrence of a String Inside
Another String (Case-Sensitive)

strcasecmp(string1, string2) Compares Two Strings (Case-Insensitive)

strcmp(string1, string2) Compares Two Strings (Case-Sensitive)

strtok(string, split) Splits a String Into Smaller Strings 36

chunk_split(string, length) Splits a String Into a Series of Smaller Parts (Default Length Is
76)

Pallavi Engineering College


PHP Programming _IV_ECE

str_split(string, length) Splits a String Into an Array

explode(separator, string) Breaks a String Into an Array

implode(separator, array) Returns a String From the Elements of an Array

str_getcsv(string, delimiter, Parses a CSV String Into an Array


enclosure)

addcslashes(string) Returns a String With Backslashes In Front of Single Quotes,


Double Quotes & Backslashes

stripcslashes(string) Unquotes a String Quoted With addcslashes()

addslashes(string,characters) Returns a String With Backslashes in Front of Predefined


Characters

stripslashes(string) Unquotes a String Quoted With addslashes()

nl2br(string) Inserts HTML Line Breaks In Front of Each Newline In a String

strip_tags(string) Strips HTML & PHP Tags From a String

html_entity_decode(string) Converts HTML Entities to Characters

htmlentities(string) Converts Characters to HTML Entities

htmlspecialchars_decode(string) Converts Some Predefined HTML Entities to Characters

htmlspecialchars(string) Converts Some Predefined Characters to HTML Entities

get_html_translation_table() Returns the Translation Table Used by htmlspecialchars() &


htmlentities()

A complete list of the string functions available can be found in the official PHP manual. Each
function includes examples that will help you understand how to use it.

Math Functions:

PHP provides nearly fifty functions that can perform various mathematical functions. Combined with
mathematical operators, they can make your homework a lot easier!

The simplest math functions are those that only require a single parameter. This parameter is usually a
number, which is accepted either as a variable or a string. The ceil() function, for example, will return
a number rounded up to the nearest full number.

<?php
$num = 55;
echo ceil($num); 37
// Result Will Be: 55

$result = ceil(295.34);
echo $result;
Pallavi Engineering College
PHP Programming _IV_ECE

// Result Will Be: 296


?>

As you can see, the results of these functions can be echoed, stored in a variable, etc.

Some math functions accept multiple parameters. The rand() function, for example, generates a
random number in between the two numbers that it is given. Multiple parameter are separated by
commas.

<?php
echo rand(0, 500);
// Result Is: 433
?>

If you refresh the page, you will see the above result change each time to a random number between 0
and 500.

Below is a list of almost twenty useful math functions, along with a brief description and required
parameters.

Function(Parameters) Description

rand(min_number, Returns a Random Integer


max_number)

ceil(number) Returns the Value of a Number Rounded Upwards to the Nearest


Integer

floor(number) Returns the Value of a Number Rounded Downwards to the Nearest


Integer

abs(number) Returns the Absolute Value of a Number

base_convert(number) Converts a Number From One Base to Another

bindec(binary_number) Converts a Binary Number to a Decimal Number

decbin(decimal_number) Converts a Decimal Number to a Binary Number

dechex(decimal_number) Converts a Decimal Number to a Hexadecimal Number

decoct(decimal_number) Converts a Decimal Number to an Octal Number

fmod(number, divisor) Returns the Remainder (Modulo) of the Division of the Arguments

hexdec(hex_number) Converts a Hexadecimal Number to a Decimal Number

is_finite(number) Returns True if a Value is a Finite Number


38
is_infinite(number) Returns True if a Value is an Infinite Number

is_nan(value_to_check) Returns True if a Value is Not a Number

Pallavi Engineering College


PHP Programming _IV_ECE

max(number1, number2) Returns the Number With the Highest Value of Two Specified
Numbers

min(number1, number2) Returns the Number With the Lowest Value of Two Specified
Numbers

pi() Returns the Value of PI

pow(x, y) Returns the Value of "x" to the Power of "y"

round(number, optional) Rounds a Number to the Nearest Integer (Number of Digits After
Decimal Point Optional)

sqrt(number) Returns the Square Root of a Number

A complete list of the math functions available can be found in the official PHP manual. Each function
includes examples that will help you understand how to use it.

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

convert_uudecode() Decodes a uuencoded string

Pallavi Engineering College


PHP Programming _IV_ECE

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 hashing

echo() Outputs one or more strings

explode() Breaks a string into an array

fprintf() Writes a formatted string to a specified output stream

Returns the translation table used by htmlspecialchars() and


get_html_translation_table()
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


40

htmlspecialchars() Converts some predefined characters to HTML entities

Pallavi Engineering College


PHP Programming _IV_ECE

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

41
parse_str() Parses a query string into variables

Pallavi Engineering College


PHP Programming _IV_ECE

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

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

42
str_ireplace() Replaces some characters in a string (case-insensitive)

Pallavi Engineering College


PHP Programming _IV_ECE

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)

Finds the first occurrence of a string inside another string (alias of


strchr()
strstr())

strcmp() Compares two strings (case-sensitive)

strcoll() Compares two strings (locale based string comparison)

Returns the number of characters found in a string before any part of


strcspn()
some specified characters are found

strip_tags() Strips HTML and PHP tags from a string

stripcslashes() Unquotes a string quoted with addcslashes() 43

Pallavi Engineering College


PHP Programming _IV_ECE

stripslashes() Unquotes a string quoted with addslashes()

Returns the position of the first occurrence of a string inside another


stripos()
string (case-insensitive)

Finds the first occurrence of a string inside another string (case-


stristr()
insensitive)

strlen() Returns the length of a string

Compares two strings using a "natural order" algorithm (case-


strnatcasecmp()
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

Returns the position of the first occurrence of a string inside another


strpos()
string (case-sensitive)

strrchr() Finds the last occurrence of a string inside another string

strrev() Reverses a string

Finds the position of the last occurrence of a string inside another string
strripos()
(case-insensitive) 44

Pallavi Engineering College


PHP Programming _IV_ECE

Finds the position of the last occurrence of a string inside another string
strrpos()
(case-sensitive)

Returns the number of characters found in a string that contains only


strspn()
characters from a specified charlist

Finds the first occurrence of a string inside another string (case-


strstr()
sensitive)

strtok() Splits a string into smaller strings

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

Compares two strings from a specified start position (binary safe and
substr_compare()
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


45

ucwords() Converts the first character of each word in a string to uppercase

Pallavi Engineering College


PHP Programming _IV_ECE

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 Array Functions

Function Description

array() Creates an array

array_change_key_case() Changes all keys in an array to lowercase or uppercase

array_chunk() Splits an array into chunks of arrays

array_column() Returns the values from a single column in the input array

Creates an array by using the elements from one "keys" array and one
array_combine()
"values" array

array_count_values() Counts all the values of an array

array_diff() Compare arrays, and returns the differences (compare values only)

array_diff_assoc() Compare arrays, and returns the differences (compare keys and values) 46

Pallavi Engineering College


PHP Programming _IV_ECE

array_diff_key() Compare arrays, and returns the differences (compare keys only)

Compare arrays, and returns the differences (compare keys and values, using
array_diff_uassoc()
a user-defined key comparison function)

Compare arrays, and returns the differences (compare keys only, using a
array_diff_ukey()
user-defined key comparison function)

array_fill() Fills an array with values

array_fill_keys() Fills an array with values, specifying keys

array_filter() Filters the values of an array using a callback function

array_flip() Flips/Exchanges all keys with their associated values in an array

array_intersect() Compare arrays, and returns the matches (compare values only)

array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)

array_intersect_key() Compare arrays, and returns the matches (compare keys only)

Compare arrays, and returns the matches (compare keys and values, using a
array_intersect_uassoc()
user-defined key comparison function)

Compare arrays, and returns the matches (compare keys only, using a user-
array_intersect_ukey()
defined key comparison function)

array_key_exists() Checks if the specified key exists in the array


47

array_keys() Returns all the keys of an array

Pallavi Engineering College


PHP Programming _IV_ECE

Sends each value of an array to a user-made function, which returns new


array_map()
values

array_merge() Merges one or more arrays into one array

array_merge_recursive() Merges one or more arrays into one array recursively

array_multisort() Sorts multiple or multi-dimensional arrays

array_pad() Inserts a specified number of items, with a specified value, to an array

array_pop() Deletes the last element of an array

array_product() Calculates the product of the values in an array

array_push() Inserts one or more elements to the end of an array

array_rand() Returns one or more random keys from an array

array_reduce() Returns an array as a string, using a user-defined function

array_replace() Replaces the values of the first array with the values from following arrays

Replaces the values of the first array with the values from following arrays
array_replace_recursive()
recursively

array_reverse() Returns an array in the reverse order

array_search() Searches an array for a given value and returns the key 48

Pallavi Engineering College


PHP Programming _IV_ECE

Removes the first element from an array, and returns the value of the
array_shift()
removed element

array_slice() Returns selected parts of an array

array_splice() Removes and replaces specified elements of an array

array_sum() Returns the sum of the values in an array

Compare arrays, and returns the differences (compare values only, using a
array_udiff()
user-defined key comparison function)

Compare arrays, and returns the differences (compare keys and values, using
array_udiff_assoc() a built-in function to compare the keys and a user-defined function to
compare the values)

Compare arrays, and returns the differences (compare keys and values, using
array_udiff_uassoc()
two user-defined key comparison functions)

Compare arrays, and returns the matches (compare values only, using a user-
array_uintersect()
defined key comparison function)

Compare arrays, and returns the matches (compare keys and values, using a
array_uintersect_assoc() built-in function to compare the keys and a user-defined function to compare
the values)

Compare arrays, and returns the matches (compare keys and values, using
array_uintersect_uassoc()
two user-defined key comparison functions)

array_unique() Removes duplicate values from an array

49
array_unshift() Adds one or more elements to the beginning of an array

Pallavi Engineering College


PHP Programming _IV_ECE

array_values() Returns all the values of an array

array_walk() Applies a user function to every member of an array

array_walk_recursive() Applies a user function recursively to every member of an array

arsort() Sorts an associative array in descending order, according to the value

asort() Sorts an associative array in ascending order, according to the value

compact() Create array containing variables and their values

count() Returns the number of elements in an array

current() Returns the current element in an array

Deprecated from PHP 7.2. Returns the current key and value pair from an
each()
array

end() Sets the internal pointer of an array to its last element

extract() Imports variables into the current symbol table from an array

in_array() Checks if a specified value exists in an array

key() Fetches a key from an array

krsort() Sorts an associative array in descending order, according to the key


50

ksort() Sorts an associative array in ascending order, according to the key

Pallavi Engineering College


PHP Programming _IV_ECE

list() Assigns variables as if they were an array

natcasesort() Sorts an array using a case insensitive "natural order" algorithm

natsort() Sorts an array using a "natural order" algorithm

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer

range() Creates an array containing a range of elements

reset() Sets the internal pointer of an array to its first element

rsort() Sorts an indexed array in descending order

shuffle() Shuffles an array

sizeof() Alias of count()

sort() Sorts an indexed array in ascending order

uasort() Sorts an array by values using a user-defined comparison function

uksort() Sorts an array by keys using a user-defined comparison function

51
usort() Sorts an array using a user-defined comparison function

Pallavi Engineering College


PHP Programming _IV_ECE

PHP Date/Time Introduction

The date/time functions allow you to get the date and time from the server where your PHP script runs.
You can then use the date/time functions to format the date and time in several ways.

Note: These functions depend on the locale settings of your server. Remember to take daylight saving
time and leap years into consideration when working with these functions.

Installation

The PHP date/time functions are part of the PHP core. No installation is required to use these
functions.

Runtime Configuration

The behavior of these functions is affected by settings in php.ini:

PHP
Name Description Default
Version

date.timezone The default timezone (used by all date/time functions) "" PHP 5.1

The default latitude (used by date_sunrise() and


date.default_latitude "31.7667" PHP 5.0
date_sunset())

The default longitude (used by date_sunrise() and


date.default_longitude "35.2333" PHP 5.0
date_sunset())

The default sunrise zenith (used by date_sunrise() and


date.sunrise_zenith "90.83" PHP 5.0
date_sunset())

52
The default sunset zenith (used by date_sunrise() and
date.sunset_zenith "90.83" PHP 5.0
date_sunset())

Pallavi Engineering College


PHP Programming _IV_ECE

PHP Date/Time Functions

Function Description

checkdate() Validates a Gregorian date

Adds days, months, years, hours, minutes, and seconds to a


date_add()
date

Returns a new DateTime object formatted according to a


date_create_from_format()
specified format

date_create() Returns a new DateTime object

date_date_set() Sets a new date

date_default_timezone_get() Returns the default timezone used by all date/time functions

date_default_timezone_set() Sets the default timezone used by all date/time functions

date_diff() Returns the difference between two dates

date_format() Returns a date formatted according to a specified format

date_get_last_errors() Returns the warnings/errors found in a date string

date_interval_create_from_date_string() Sets up a DateInterval from the relative parts of the string


53

date_interval_format() Formats the interval

Pallavi Engineering College


PHP Programming _IV_ECE

date_isodate_set() Sets the ISO date

date_modify() Modifies the timestamp

date_offset_get() Returns the timezone offset

Returns an associative array with detailed info about a


date_parse_from_format()
specified date, according to a specified format

Returns an associative array with detailed info about a


date_parse()
specified date

Subtracts days, months, years, hours, minutes, and seconds


date_sub()
from a date

Returns an array containing info about sunset/sunrise and


date_sun_info()
twilight begin/end, for a specified day and location

date_sunrise() Returns the sunrise time for a specified day and location

date_sunset() Returns the sunset time for a specified day and location

date_time_set() Sets the time

date_timestamp_get() Returns the Unix timestamp

date_timestamp_set() Sets the date and time based on a Unix timestamp

date_timezone_get() Returns the time zone of the given DateTime object


54

date_timezone_set() Sets the time zone for the DateTime object

Pallavi Engineering College


PHP Programming _IV_ECE

date() Formats a local date and time

Returns date/time information of a timestamp or the current


getdate()
local date/time

gettimeofday() Returns the current time

gmdate() Formats a GMT/UTC date and time

gmmktime() Returns the Unix timestamp for a GMT date

Formats a GMT/UTC date and time according to locale


gmstrftime()
settings

idate() Formats a local time/date as integer

localtime() Returns the local time

microtime() Returns the current Unix timestamp with microseconds

mktime() Returns the Unix timestamp for a date

strftime() Formats a local time and/or date according to locale settings

strptime() Parses a time/date generated with strftime()

strtotime() Parses an English textual datetime into a Unix timestamp

time() Returns the current time as a Unix timestamp 55

Pallavi Engineering College


PHP Programming _IV_ECE

Returns an associative array containing dst, offset, and the


timezone_abbreviations_list()
timezone name

timezone_identifiers_list() Returns an indexed array with all timezone identifiers

timezone_location_get() Returns location information for a specified timezone

timezone_name_from_ abbr() Returns the timezone name from abbreviation

timezone_name_get() Returns the name of the timezone

timezone_offset_get() Returns the timezone offset from GMT

timezone_open() Creates new DateTimeZone object

timezone_transitions_get() Returns all transitions for the timezone

timezone_version_get() Returns the version of the timezonedb

PHP Predefined Date/Time Constants

Constant Description

DATE_ATOM Atom (example: 2019-01-18T14:13:03+00:00)

DATE_COOKIE HTTP Cookies (example: Fri, 18 Jan 2019 14:13:03 UTC)

DATE_ISO8601 ISO-8601 (example: 2019-01-18T14:13:03+0000)

DATE_RFC822 RFC 822 (example: Fri, 18 Jan 2019 14:13:03 +0000) 56

Pallavi Engineering College


PHP Programming _IV_ECE

DATE_RFC850 RFC 850 (example: Friday, 18-Jan-19 14:13:03 UTC)

DATE_RFC1036 RFC 1036 (example: Friday, 18-Jan-19 14:13:03 +0000)

DATE_RFC1123 RFC 1123 (example: Fri, 18 Jan 2019 14:13:03 +0000)

DATE_RFC2822 RFC 2822 (example: Fri, 18 Jan 2019 14:13:03 +0000)

DATE_RFC3339 Same as DATE_ATOM (since PHP 5.1.3)

RFC3339 Extended format (since PHP 7.0.0) (example: 2019-


DATE_RFC3339_EXTENDED
01-18T16:34:01.000+00:00)

DATE_RSS RSS (Fri, 18 Jan 2019 14:13:03 +0000)

World Wide Web Consortium (example: 2019-01-


DATE_W3C
18T14:13:03+00:00)

SUNFUNCS_RET_TIMESTAMP Timestamp (since PHP 5.1.2)

SUNFUNCS_RET_STRING Hours:minutes (example: 09:41) (since PHP 5.1.2)

Hours as a floating point number (example: 9.75) (since PHP


SUNFUNCS_RET_DOUBLE
5.1.2)

PHP Math Functions


❮ PreviousNext❯

57
PHP Math Introduction

The math functions can handle values within the range of integer and float types.

Pallavi Engineering College


PHP Programming _IV_ECE

Installation

The PHP math functions are part of the PHP core. No installation is required to use these functions.

PHP Math Functions

Function Description

abs() Returns the absolute (positive) value of a number

acos() Returns the arc cosine of a number

acosh() Returns the inverse hyperbolic cosine of a number

asin() Returns the arc sine of a number

asinh() Returns the inverse hyperbolic sine of a number

atan() Returns the arc tangent of a number in radians

atan2() Returns the arc tangent of two variables x and y

atanh() Returns the inverse hyperbolic tangent of a number

base_convert() Converts a number from one number base to another

bindec() Converts a binary number to a decimal number

58
ceil() Rounds a number up to the nearest integer

Pallavi Engineering College


PHP Programming _IV_ECE

cos() Returns the cosine of a number

cosh() Returns the hyperbolic cosine of a number

decbin() Converts a decimal number to a binary number

dechex() Converts a decimal number to a hexadecimal number

decoct() Converts a decimal number to an octal number

deg2rad() Converts a degree value to a radian value

exp() Calculates the exponent of e

expm1() Returns exp(x) - 1

floor() Rounds a number down to the nearest integer

fmod() Returns the remainder of x/y

getrandmax() Returns the largest possible value returned by rand()

hexdec() Converts a hexadecimal number to a decimal number

hypot() Calculates the hypotenuse of a right-angle triangle

intdiv() Performs integer division

59
is_finite() Checks whether a value is finite or not

Pallavi Engineering College


PHP Programming _IV_ECE

is_infinite() Checks whether a value is infinite or not

is_nan() Checks whether a value is 'not-a-number'

lcg_value() Returns a pseudo random number in a range between 0 and 1

log() Returns the natural logarithm of a number

log10() Returns the base-10 logarithm of a number

log1p() Returns log(1+number)

Returns the highest value in an array, or the highest value of several


max()
specified values

Returns the lowest value in an array, or the lowest value of several specified
min()
values

mt_getrandmax() Returns the largest possible value returned by mt_rand()

mt_rand() Generates a random integer using Mersenne Twister algorithm

mt_srand() Seeds the Mersenne Twister random number generator

octdec() Converts an octal number to a decimal number

pi() Returns the value of PI

pow() Returns x raised to the power of y 60

Pallavi Engineering College


PHP Programming _IV_ECE

rad2deg() Converts a radian value to a degree value

rand() Generates a random integer

round() Rounds a floating-point number

sin() Returns the sine of a number

sinh() Returns the hyperbolic sine of a number

sqrt() Returns the square root of a number

srand() Seeds the random number generator

tan() Returns the tangent of a number

tanh() Returns the hyperbolic tangent of a number

61

Pallavi Engineering College


PHP Programming _IV_ECE

Unit-3
We already discussed variables, but we did not already discuss the variables that come ready-made in PHP. Predefined
variables are already defined, as their name implies, and can be used without you having to create them first.

The majority of predefined variables are used to provide information from and about the web server, the web browser, and
the user. They are called superglobals.

The following superglobals are available:

Variable Name Variable Description

$_GET HTTP GET Variables

$_POST HTTP POST Variables

$_FILES HTTP File Upload Variables

$_SERVER Server And Environment Information

$_COOKIE HTTP Cookies

$_SESSION Session Variables

$_REQUEST HTTP Request Variables

$GLOBALS References All Variables In A Global Scope

$php_errormsg The Previous (Last) Error Message

We will discuss many of these superglobals in detail on the following pages, so for now we will only briefly demonstrate
how they are used with a demonstration of the $_SERVER superglobal.

<?php
echo "Your IP Address Is: " . $_SERVER['REMOTE_ADDR'] . "<br>";
echo "The Current Page Name Is: " . $_SERVER['PHP_SELF'] . "<br>";
echo "You Came From A Page Called: " . $_SERVER['HTTP_REFERER'] . "<br>";
?>

Superglobals, such as the $_SERVER variable, are arrays, which we have not yet learned about. The are a single variable
that contain multiple values, all of which are separate and can be referenced separately. The brackets and single quotes at
the end of the variable contain the reference name of the real value that we want. The result of the above example is:

Your IP Address Is: 117.211.191.194


The Current Page Name Is: /php/php-forms-predefined-variables-superglobals.php
You Came From A Page Called: http://www.phpforkids.com/php/php-tutorial-table-of-contents.php

The $_SERVER variable has over thirty elements available, most of which are actually useful. The most common elements,
assuming your server supports them, are:

Variable Description

$_SERVER['PHP_SELF'] The filename of the currently executing script, relative to the document root.
62
$_SERVER['SERVER_ADDR'] The IP address of the server under which the current script is executing.

$_SERVER['SERVER_NAME'] The name of the server host under which the current script is executing. If the script
is running on a virtual host, this will be the value defined for that virtual host.

Pallavi Engineering College


PHP Programming _IV_ECE

$_SERVER['SERVER_SOFTWARE'] Server identification string, given in the headers when responding to requests.

$_SERVER['SERVER_PROTOCOL'] Name and revision of the information protocol via which the page was requested;
i.e. 'HTTP/1.0';

$_SERVER['REQUEST_METHOD'] Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST',
'PUT'.

$_SERVER['REQUEST_TIME'] The timestamp of the start of the request. Available since PHP 5.1.0.

$_SERVER['QUERY_STRING'] The query string, if any, via which the page was accessed.

$_SERVER['DOCUMENT_ROOT'] The document root directory under which the current script is executing, as defined
in the server's configuration file.

$_SERVER['HTTP_CONNECTION'] Contents of the Connection: header from the current request, if there is one.
Example: 'Keep-Alive'.

$_SERVER['HTTP_HOST'] Contents of the Host: header from the current request, if there is one.

$_SERVER['HTTP_REFERER'] The address of the page (if any) which referred the user agent to the current page.

$_SERVER['HTTP_USER_AGENT'] This is a string denoting the user agent being which is accessing the page. A typical
example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586).

$_SERVER['HTTPS'] Set to a non-empty value if the script was queried through the HTTPS protocol.

$_SERVER['REMOTE_ADDR'] The IP address from which the user is viewing the current page.

$_SERVER['REMOTE_HOST'] The Host name from which the user is viewing the current page. The reverse dns
lookup is based off the REMOTE_ADDR of the user.

$_SERVER['REMOTE_PORT'] The port being used on the user's machine to communicate with the web server.

$_SERVER['SCRIPT_FILENAME'] The absolute pathname of the currently executing script.

$_SERVER['SERVER_ADMIN'] The value given to the SERVER_ADMIN (for Apache) directive in the web server
configuration file.

$_SERVER['SERVER_PORT'] The port on the server machine being used by the web server for communication.
For default setups, this will be '80'.

$_SERVER['SERVER_SIGNATURE'] String containing the server version and virtual host name which are added to
server-generated pages, if enabled.

$_SERVER['PATH_TRANSLATED'] Filesystem based path to the current script.

$_SERVER['SCRIPT_NAME'] Contains the current script's path. This is useful for pages which need to point to
themselves.

$_SERVER['REQUEST_URI'] The URI which was given in order to access this page; for instance, '/index.html'.

$_SERVER['PHP_AUTH_DIGEST'] When running under Apache as module doing Digest HTTP authentication this
variable is set to the 'Authorization' header sent by the client.

$_SERVER['PHP_AUTH_USER'] When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP 63
authentication this variable is set to the username provided by the user.

$_SERVER['PHP_AUTH_PW'] When running under Apache or IIS (ISAPI on PHP 5) as module doing HTTP
authentication this variable is set to the password provided by the user.

Pallavi Engineering College


PHP Programming _IV_ECE

$_SERVER['AUTH_TYPE'] When running under Apache as module doing HTTP authenticated this variable is
set to the authentication type.

Getting Form Field Data

Obtaining information that is entered into an HTML form is actually a simple process using PHP. All you need to know is
the method used to send the form data, the name of each form field, and what you want to do with the information that you
obtain.

When the form method used is "get", the information entered into the form is sent via the URL when the form is submitted.
It is visible to everyone, and limited to 100 characters.

Using the $_GET superglobal along with the name of the form field, we can obtain the value of each field.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="GET">


Type In Something: <input name="random-info" type="text" size="25">
<input type="submit" value="Submit">
</form> <br>

<?php
echo "You Typed: " . $_GET['random-info'];
?>

Submit
Type In Something:

You Typed:

If you tried the demo above you will see that the HTML form, when submitted, uses $_SERVER['PHP_SELF'] to send you
right back to the page that the form was submitted from. If you had typed anything into the form, it is echoed directly onto
the page, and can also be seen at the end of the URL if you look in the address bar.

Obviously, using the GET method is limiting in both size and security, so use it wisely. It is useful if you want to allow
your users to bookmark a page to come back to later, because they will be returned to the page with the same information
already submitted.

Posting Form Field Data

The method of obtaining information that is entered into an HTML form using the POST method is nearly identical to
obtaining information that uses the GET method. The only difference? The spelling!

When the form method used is "post", the information entered into the form is sent behind-the-scenes when the form is
submitted. It is not visible in the address bar, but it is limited to 8MB in size. (Don't worry about the limit; that's a LOT of
data!).

Using the $_POST superglobal along with the name of the form field, we can obtain the value of each field.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">


Type In Something: <input name="random-info" type="text" size="25">
<input type="submit" value="Submit">
</form> <br>

<?php
64
echo "You Typed: " . $_POST['random-info'];
?>

Pallavi Engineering College


PHP Programming _IV_ECE

Submit
Type In Something:

You Typed:

If you tried the demo above you will see that the HTML form, when submitted, uses $_SERVER['PHP_SELF'] to send you
right back to the page that the form was submitted from. If you had typed anything into the form, it is echoed directly onto
the page.

This method is used for the majority of form-related tasks.

Getting & Posting Checkbox & Radio Button Results

Obtaining data from radio buttons and checkboxes can be a little tricky, generally due to a lack of understanding of how
radio buttons and checkboxes work.

It is important to remember two facts:

Checkbox "Names" Must Be Unique to Each Checkbox


Radio Button "Names" Must Be Identical For Each Group of Buttons

Let's jump right into an example:

<form action="php-forms-get-post-checkbox-radio-data.php" method="post">

Why don't they play poker in the jungle?<br>


<input type="radio" name="jungle" value="treefrog"> Too many tree frogs.<br>
<input type="radio" name="jungle" value="cheetah"> Too many cheetahs.<br>
<input type="radio" name="jungle" value="river"> Too many rivers.<br><br>

Check the box if you want your answer to be graded:


<input type="checkbox" name="grade" value="yes"><br><br>

<input type="submit" name="submit" value="Submit"><br>

</form>

The code produces the following result:

Why don't they play poker in the jungle?

Too many tree frogs.

Too many cheetahs.

Too many rivers.

Check the box if you want your answer to be graded:

Submit

Now let's use the $_POST[] superglobal to get the form data that was submitted. It is best to begin by checking to see if the
form was submitted. This can be done using the isset() function to see if the submit button has been clicked.
65
<?php
if (isset($_POST['submit'])) { /* Do Something Here */ }
else { echo "Please submit the form."; }
?>

Pallavi Engineering College


PHP Programming _IV_ECE

As you can see, the name of each $_POST[] superglobal corresponds with the name of the HTML form field in question.

Next, we can check to see if the submitted form should be graded. Checkboxes only return a value if they are checked. If a
checkbox is not checked, then no value will be sent, so we can use the empty() function to determine our next course of
action.

<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['grade'])) { /* Grade the question. */ }
else { echo "Your answer will not be graded."; }
} else { echo "Please submit the form."; }
?>

Now we can find out which answer was chosen.

<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['grade'])) {
if (!empty($_POST['jungle'])) { /* Get Radio Button Value */ }
else { echo "You did not choose an answer."; }
} else { echo "Your answer will not be graded."; }
} else { echo "Please submit the form."; }
?>

And at last, we can determine whether or not it was the right answer.

<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['grade'])) {
if (!empty($_POST['jungle'])) {
if ($_POST['jungle']=="cheetah") { echo "You got the right answer!"; }
else { echo "Sorry, wrong answer."; }
} else { echo "You did not choose an answer."; }
} else { echo "Your answer will not be graded."; }
} else { echo "Please submit the form."; }
?>

Submit the form in the example at the top of the page to see the results below. (Notice that the form action will return you
to this page when the form is submitted.)

Please submit the form.

PHP File Uploads

Allowing anyone and everyone to upload files to your web server opens up many, many concerns about security, but we
will not address them all here. Instead, we will focus on the very basic mechanics of uploading files so that you can
experiment with this feature.

To begin, you will need an HTML file upload form with a method of "post" and a specific encoding type, such as the
following example. (The action should lead to the php file where the file upload script is located.)

<form action="upload.php" method="post" enctype="multipart/form-data">


<input type="file" name="my-file" size="50" maxlength="25"> <br>
<input type="submit" name="upload" value="Upload">
</form>
66
When a file is uploaded, it gets stored in a temporary area on the server until it is moved. The file has to be moved from that
area, or else it will be destroyed. In the meantime, the $_FILES[] superglobal array is filled up with data about the uploaded
file. Since the file's upload field in our example is called "my-file", the following data is created:

Pallavi Engineering College


PHP Programming _IV_ECE

Superglobal Description

$_FILES['my-file']['name'] Original Name of File Before It Was Uploaded

$_FILES['my-file']['type'] The MIME Type of File, Provided By the Browser

$_FILES['my-file']['size'] Size of the File (In Bytes)

$_FILES['my-file']['tmp_name'] Location of Temporary File on Server

$_FILES['my-file']['error'] Any Error Codes Resulting From the File Upload


To begin the file upload script, we will use the is_uploaded_file() function as an alternative to the isset() and empty()
functions to verify that a file has been uploaded to its temporary location.

<?php
if (is_uploaded_file($_FILES['my-file']['tmp_name']) && $_FILES['my-file']['error']==0) {
echo "The file was uploaded successfully but has not been saved.<br>";
echo "The file is temporarily stored: " . $_FILES['my-file']['tmp_name'] . "<br>";
echo "The file name was: " . $_FILES['my-file']['name'] . "<br>";
echo "The file type is: " . $_FILES['my-file']['type'] . "<br>";
echo "The file size is: " . $_FILES['my-file']['size'] . "<br>";
} else {
echo "The file was not uploaded successfully.";
echo "(Error Code:" . $_FILES['my-file']['error'] . ")";
}
?>

The next step, if you want to only accept certain file types and sizes, would be to check out those factors and send out error
messages accordingly. In our example we'll move right along and determine whether or not the file has already been
uploaded, since we do not want to over-write an existing file. We can use the file_exists() function for this purpose.

<?php
if (is_uploaded_file($_FILES['my-file']['tmp_name']) && $_FILES['my-file']['error']==0) {
$path = '/var/www/html/phpforkids.com/uploads/' . $_FILES['my-file']['name'];
if (!file_exists($path)) {
echo "File does not exist. It is safe to move the temporary file.";
} else {
echo "File already exists. Please upload another file.";
}
} else {
echo "The file was not uploaded successfully.";
echo "(Error Code:" . $_FILES['my-file']['error'] . ")";
}
?>

And now, at long last, we can use the move_uploaded_file() function to move the temporary file into its permanent
location.

<?php
if (is_uploaded_file($_FILES['my-file']['tmp_name']) && $_FILES['my-file']['error']==0) {
$path = '/var/www/html/phpforkids.com/uploads/' . $_FILES['my-file']['name'];
if (!file_exists($path)) {
if (move_uploaded_file($_FILES['my-file']['tmp_name'], $path)) {
echo "The file was uploaded successfully.";
} else {
echo "The file was not uploaded successfully."; 67
}
} else {
echo "File already exists. Please upload another file.";
}
} else {

Pallavi Engineering College


PHP Programming _IV_ECE

echo "The file was not uploaded successfully.";


echo "(Error Code:" . $_FILES['my-file']['error'] . ")";
}
?>

That's all it takes!

Two common problems that you may run into, causing the upload process to fail, are the file size and directory permissions.
PHP sets a default "upload_max_filesize" to limit the size of the file uploaded. The default is 2M (megabytes) and any file
that exceeds this limit will not upload. Also, if the directory (folder) where you try to move the file must have certain
permissions set, or you will not be allowed to move the file into that directory.

PHP Url Functions

PHP provides several functions used to deal with URL strings. A URL is an address used to identify a website, and a URL
string might look something like this: http://www.phpforkids.com/php/php-functions-url.php

The URL functions that we will learn about here are:

Function Description

get_headers() Fetches all the headers sent by the server in response to a HTTP request

get_meta_tags() Extracts all meta tag content attributes from a file and returns an array

parse_url() Parse a URL and return its components

urlencode() URL-encodes string

urldecode() Decodes URL-encoded string

rawurlencode() URL-encode according to RFC 1738

rawurldecode() Decode URL-encoded strings


Am I the only one that wants all that translated into English?! Let's begin with get_headers(), which will return an array
containing the headers sent by the server in response to an HTTP request.

Example Code:
<?php
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Example: http://www.phpforkids.com/php/php-functions-url.php
$headers = get_headers($url);
print_r($headers);
?>

Result (Array Created):


Array (
[0] => HTTP/1.1 200 OK
[1] => Date: Sun, 05 Sep 2010 22:30:39 GMT
[2] => Server: Apache/2.2.3 (CentOS)
[3] => X-Powered-By: PHP/5.1.6
[4] => Set-Cookie: PHPSESSID=ggnc33i24gukchi5iqnqg8b4a7; path=/
[5] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
[6] => Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 68
[7] => Pragma: no-cache
[8] => Vary: Accept-Encoding
[9] => Content-Length: 6746
[10] => Connection: close
[11] => Content-Type: text/html
Pallavi Engineering College
PHP Programming _IV_ECE

[12] => Content-Language: en


)

..ooookkkkaaayyy... moving on (to something more useful?), the get_meta_tags() function returns an array containing the
meta tags found between the HTML <head> and </head> tags of the specified webpage.

Example Code:
<?php
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// Example: http://www.phpforkids.com/php/php-functions-url.php
$MetaTags = get_meta_tags($url);
print_r($MetaTags);
?>

Result (Array Created):


Array (
[description] => Free Tutorial On PHP Url Functions At PHP For Kids.com
[keywords] => php, tutorial, learn, free, url, functions
)

The parse_url() functions takes a url and returns it to you in little pieces stored in an array.

Example Code:
<?php
$url = "http://www.phpforkids.com/php/php-functions-url.php?question=testing-testing";
$ParsedUrl = parse_url($url);
print_r($ParsedUrl);
?>

Result (Array Created):


Array (
[scheme] => http
[host] => www.phpforkids.com
[path] => /php/php-functions-url.php
[query] => question=testing-testing
)

The urlencode() and rawurlencode() functions both encode strings by replacing all non-alphanumeric characters such as
spaces and symbols with placeholders that can later be decoded to return the original string. These functions are ideal for
preserving strings used in URL queries, or even passed between pages as "GET" data when a form is submitted.

The urldecode() and rawurldecode() functions can be used to decode the strings once they reach their destination and need
to be used or displayed in their original format.

The urlencode() function works with urldecode() and the rawurlencode() function works with rawurldecode(). The
difference between the two sets of functions is only in the style that they used to encode each string.

Example Code:
<?php
$string1 = "What is a mouse's favorite game?";
$result = urlencode($string1);
echo $result . "<br />";
$result = urldecode($string1);
echo $result . "<br />";

$string2 = "Hide and squeak!";


echo rawurlencode($string2);
echo rawurldecode($string2); 69
?>

Result of urlencode() and urldecode():


What+is+a+mouse%27s+favorite+game%3F
What is a mouse's favorite game?

Pallavi Engineering College


PHP Programming _IV_ECE

Result of rawurlencode() and rawurldecode():


Hide%20and%20squeak%21
Hide and squeak!

Opening & Closing Files

The ability to manipulate files can be both fun and useful. The first step of the process would be to identify the file that you
want to manipulate, and open it.

PHP uses the fopen() function for the purpose of opening an existing file or creating a new file if the specified file does not
already exist. The function syntax is: fopen(filename, method);

It is probably obvious that "filename" refers to the name (and also the path) of the file, but method may not be quite as
obvious. It refers to the type of access that is allowed each time the file is opened. The most common options are:

Mode Description

r Open for reading only; place the file pointer at the beginning of the file.

r+ Open for reading and writing; place the file pointer at the beginning of the file.

w Open for writing only; place the file pointer at the beginning of the file and truncate the file to
zero length. If the file does not exist, attempt to create it.

w+ Open for reading and writing; place the file pointer at the beginning of the file and truncate the
file to zero length. If the file does not exist, attempt to create it.

a Open for writing only; place the file pointer at the end of the file. If the file does not exist,
attempt to create it.

a+ Open for reading and writing; place the file pointer at the end of the file. If the file does not
exist, attempt to create it.

x Create and open for writing only; place the file pointer at the beginning of the file. If the file
already exists, the fopen() call will fail by returning FALSE and generating an error of level
E_WARNING. If the file does not exist, attempt to create it.

x+ Create and open for reading and writing; otherwise it has the same behavior as 'x'.

c Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither
truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file
pointer is positioned on the beginning of the file.

c+ Open the file for reading and writing; otherwise it has the same behavior as 'c'.
When using fopen(), a file handle is returned which identifies the open file connection and will later be used to
read/write/close the file, all very important steps. We can store that file handle in a variable. Let's look at some examples of
how to open a file. 70

<?php
$FileHandle1 = fopen('storage.txt', 'w');

$FileHandle2 = fopen('http://www.your-website.com/', 'a+') or die("Uh-oh! Errors!");


Pallavi Engineering College
PHP Programming _IV_ECE

$FileName = "directory-path-to-file/filename.php";

$FileHandle3 = fopen($FileName, 'r');


?>

So as you can see, you can mix and match your options as needed to get the job done.

The most important part of opening a file is remembering to close it when you are done editing. The fclose() function
accepts one parameter, that parameter being the file handle of the open file that needs closed.

<?php
$FileHandle1 = fopen('storage.txt', 'w');
fclose($FileHandle1);

$FileHandle2 = fopen('http://www.your-website.com/', 'a+') or die("Uh-oh! Errors!");


fclose($FileHandle2);

$FileName = "/directory-path-to-file/filename.php";
$FileHandle3 = fopen($FileName, 'r');
fclose($FileHandle3);
?>

If you are getting errors when trying to open/edit/close files, it might be because PHP does not have permission to edit files
on the server. You will need write permission enabled in the directory that the file is stored in.

Next up, we will learn how to read and write to files.

Summary:

Function Description

fopen() Opens a File Or a URL

fclose() Closes An Open File Pointer

Reading Files

In order to read a file, the file must first be opened with the appropriate mode to allow you to perform the function(s) that
you have planned.

Three different functions are useful for reading files.

Function Description

feof() Tests For End-of-File On a File Pointer

fgets() Gets Line From File Pointer

fread() Binary-Safe File Read

filesize() Gets the Size Of a Given File 71


The end-of-file test function, feof(), is commonly used along with the fgets() function to get (read) the entire contents of a
file, one line at a time. The filesize() function is commonly used along with the fread() function to read an entire file,
otherwise fread() requires that a length/limit be specified and will stop reading the file once that length (number of bytes)
has been reached.
Pallavi Engineering College
PHP Programming _IV_ECE

Let's look at some examples before we continue.

<?php
$FileName = "test.txt";
$FileHandle = fopen($FileName, 'r') or die("File Cannot Be Opened");
$FileData = fread($FileHandle, filesize($FileName));
fclose($FileHandle);

?>

The above example opens a file and stores the entire contents of the file in a variable before closing the file. The variable
containing the file's contents can then be used as needed.

<?php
$FileName = "test.txt";
$FileHandle = fopen($FileName, 'r') or die("File Cannot Be Opened");
while (!feof($FileHandle)) {
echo fgets($FileHandle) . '<br>';
}
fclose($FileHandle);

?>

The above code opens a file and, while the file still contains unread data, reads each line and displays it before closing the
file.

Next, we will learn how to write data to a file.

Summary:

Function Description

feof() Tests For End-of-File On a File Pointer

fgets() Gets Line From File Pointer

fread() Binary-Safe File Read

filesize() Gets the Size Of a Given File

Writing to Files

In order to write to a file, the file must first be opened with the appropriate mode to allow you to perform the function(s)
that you have planned.

After the file is opened we can use the fwrite() function to write to the file. Two parameters are required; the file
identification handle and the data to write to the file. The syntax is: fwrite(handle, data);

<?php
$FileData = "What is the difference between a cat and a comma?\n";
$FileName = "joke.txt";
$FileHandle = fopen($FileName, 'w') or die("File Cannot Be Opened or Created");
fwrite($FileHandle, $FileData); 72
fclose($FileHandle);

?>

In the above example we used "w" access to open the file, meaning that it was opened for writing only, and any existing
Pallavi Engineering College
PHP Programming _IV_ECE

contents of the file were erased. Then we wrote our line of text to the file. The "\n" at the end of the string is a carriage
return, or newline character, indicating to the file that the line has ended and the file pointer should jump to the next line
down. It will not show up when you read the contents of the file.

By opening the file with another access key, such as "a", we can add data to the end of the file without wiping out the
existing contents of the file. This action is also known as "appending".

<?php
$FileData = "One has the paws before the claws and the other has the clause before the pause.\n";
$FileName = "joke.txt";
$FileHandle = fopen($FileName, 'a') or die("File Cannot Be Opened or Created");
fwrite($FileHandle, $FileData);
fclose($FileHandle);

?>

Now, if we were to read our "joke.txt" file, we would see the following:

What is the difference between a cat and a comma?


One has the paws before the claws and the other has the clause before the pause.

Summary:

Function Description

fwrite() Binary-Safe File Write

Deleting Files

Files can be deleting using the unlink() function. As will all functions that remove data, make double sure that you really
want the data gone for good, and that you don't delete the wrong data!

To lessen confusion, make sure that your file is closed before you try to delete/unlink it. Then, a single line of code with do
the trick:

<?php
unlink('storage.txt');

?>

It's as easy as that!

Summary:

Function Description

unlink() Deletes a File

Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the
foundation for pattern-matching functionality.
73
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

Pallavi Engineering College


PHP Programming _IV_ECE

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 explanation for few concepts being used in POSIX regular expression. After that we will
introduce you with 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.

Sr.No Expression & Description

1
[0-9]

It matches any decimal digit from 0 through 9.

2
[a-z]

It matches any character from lower-case a through lowercase z.

3
[A-Z]

It matches any character from uppercase A through uppercase Z.

4
[a-Z]

It matches any character from lowercase a through uppercase Z.

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 74
special character. Each special character having a specific connotation. The +, *, ?, {int. range}, and $
flags all follow a character sequence.

Pallavi Engineering College


PHP Programming _IV_ECE

Sr.No Expression & Description

1
p+

It matches any string containing at least one p.

2
p*

It matches any string containing zero or more p's.

3
p?

It matches any string containing zero or one p's.

4
p{N}

It matches any string containing a sequence of N p's

5
p{2,3}

It matches any string containing a sequence of two or three p's.

6
p{2, }

It matches any string containing a sequence of at least two p's.

7
p$

It matches any string with p at the end of it.

8
^p

It matches any string with p at the beginning of it.

Examples
Following examples will clear your concepts about matching characters.

Sr.No Expression & Description

1
[^a-zA-Z]

It matches any string not containing any of the characters ranging from a through z and A
75
through Z.

2
p.p

Pallavi Engineering College


PHP Programming _IV_ECE

It matches any string containing p, followed by any character, in turn followed by another p.

3
^.{2}$

It matches any string containing exactly two characters.

4
<b>(.*)</b>

It matches any string enclosed within <b> and </b>.

5
p(hp)*

It matches any string containing a p followed by zero or more instances of the sequence php.

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 −

Sr.No Expression & Description

1
[[:alpha:]]

It matches any string containing alphabetic characters aA through zZ.

2
[[:digit:]]

It matches any string containing numerical digits 0 through 9.

3
[[:alnum:]]

It matches any string containing alphanumeric characters aA through zZ and 0 through 9.

4
[[: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 −

Sr.No Function & Description


76

1 ereg()

Pallavi Engineering College


PHP Programming _IV_ECE

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.

2 ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces pattern with
replacement if found.

3 eregi()
The eregi() function searches throughout a string specified by pattern for a string specified by
string. The search is not case sensitive.

4 eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the search for
pattern in string is not case sensitive.

5 split()
The split() function will divide a string into various elements, the boundaries of each element
based on the occurrence of pattern in string.

6 spliti()
The spliti() function operates exactly in the same manner as its sibling split(), except that it is
not case sensitive.

7 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 explanation for few concepts being used in PERL regular expressions. After that we will
introduce you wih regular expression related functions.

Meta characters
A meta character 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' meta character: /([\d]+)000/,
Here \d will search for any string of numerical character. 77

Following is the list of meta characters which can be used in PERL Style Regular Expressions.
Character Description
. a single character

Pallavi Engineering College


PHP Programming _IV_ECE

\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
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 −

Sr.No Function & Description

1 preg_match()

The preg_match() function searches string for pattern, returning true if pattern exists, and false
otherwise.

2 preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.

3 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.

4 preg_split()
The preg_split() function operates exactly like split(), except that regular expressions are
accepted as input parameters for pattern.

5 preg_grep()
The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern. 78

6 preg_ quote()

Pallavi Engineering College


PHP Programming _IV_ECE

Quote regular expression characters

PHP has built in functions that allow us to work with regular functions. Let’s now look at the commonly
used regular expression functions in PHP.

 preg_match – this function is used to perform a pattern match on a string. It returns true if a match
is found and false if a match is not found.
 preg_split – this function is used to perform a pattern match on a string and then split the results
into a numeric array
 preg_replace – this function is used to perform a pattern match on a string and then replace the
match with the specified text.

Below is the syntax for a regular expression function such as preg_match,preg_split or preg_replace.

<?php
function_name('/pattern/',subject);
?>

HERE,

 "function_name(...)" is either preg_match, preg_split or preg_replace.


 "/.../" The forward slashes denote the beginning and end of our regular expression
 "'/pattern/'" is the pattern that we need to matched
 "subject" is the text string to be matched against

PHP Preg_match
The first example uses the preg_match function to perform a simple pattern match for the word guru in a
given URL.

The code below shows the implementation for the above example.

<?php
$my_url = "www.guru99.com";
if (preg_match("/guru/", $my_url))
{
echo "the url $my_url contains guru";
}
else
{
echo "the url $my_url does not contain guru";
}
?>

79
 "preg_match(...)" is the PHP regular expression function
 "'/guru/'" is the regular expression pattern to be matched
 "$my_url" is the variable containing the text to be matched against.

Pallavi Engineering College


PHP Programming _IV_ECE

The diagram below summarizes the above points

PHP Preg_split
Let’s now look at another example that uses the preg_split function.

We will take a string phrase and explode it into an array; the pattern to be matched is a single space.

The text string to be used in this example is "I Love Regular Expressions".

The code below illustrates the implementation of the above example.

<?php

$my_text="I Love Regular Expressions";

$my_array = preg_split("/ /", $my_text);

print_r($my_array );

?>

PHP Preg_replace
Let’s now look at the preg_replace function that performs a pattern match and then replaces the pattern
with something else.

The code below searches for the word guru in a string.

It replaces the word guru with the word guru surrounded by css code that highlights the background colour.

<?php

$text = "We at Guru99 strive to make quality education affordable to the masses. Guru99.com";

$text = preg_replace("/Guru/", '<span style="background:yellow">Guru</span>', $text);

echo $text;

?>

Meta characters
The above examples used very basic patterns; metacharacters simply allow us to perform more complex
pattern matches such as test the validity of an email address. Let’s now look at the commonly used
metacharacters.
80

Metacharacter Description Example

. Matches any single character except a new /./ matches anything that has a single

Pallavi Engineering College


PHP Programming _IV_ECE

line character

^ Matches the beginning of or string / excludes /^PH/ matches any string that starts with
characters PH

$ Matches pattern at the end of the string /com$/ matches guru99.com,yahoo.com


Etc.

* Matches any zero (0) or more characters /com*/ matches computer,


communication etc.

+ Requires preceding character(s) appear at /yah+oo/ matches yahoo


least once

\ Used to escape meta characters /yahoo+\.com/ treats the dot as a literal


value

[...] Character class /[abc]/ matches abc

a-z Matches lower case letters /a-z/ matches cool, happy etc.

A-Z Matches upper case letters /A-Z/ matches WHAT, HOW, WHY etc.

0-9 Matches any number between 0 and 9 /0-4/ matches 0,1,2,3,4

The above list only gives the most commonly used metacharacters in regular expressions.

Let’s now look at a fairly complex example that checks the validity of an email address.

<?php
$my_email = "name@company.com";
if (preg_match("/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+.[a-zA-Z.]{2,5}$/", $my_email)) {
echo "$my_email is a valid email address";
}
else
{
echo "$my_email is NOT a valid email address";
}
?>

Explaining the pattern "[/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-


Z.]{2,5}$/]"
HERE,

 "'/.../'" starts and ends the regular expression


 "^[a-zA-Z0-9._-]" matches any lower or upper case letters, numbers between 0 and 9 and dots, 81
underscores or dashes.
 "+@[a-zA-Z0-9-]" matches the @ symbol followed by lower or upper case letters, numbers
between 0 and 9 or dashes.

Pallavi Engineering College


PHP Programming _IV_ECE

 "+\.[a-zA-Z.]{2,5}$/" escapes the dot using the backslash then matches any lower or upper case
letters with a character length between 2 and 5 at the end of the string.

Unit-4
Error & Exception Handling
Error handling is the process of catching errors raised by your program and then taking appropriate
action. If you would handle errors properly then it may lead to many unforeseen consequences.
Its very simple in PHP to handle an errors.
Using die() function
While writing your PHP program you should check all possible error condition before going ahead
and take appropriate action when required.
Try following example without having /tmp/test.xt file and with this file.
<?php
if(!file_exists("/tmp/test.txt")) {
die("File not found");
}else {
$file = fopen("/tmp/test.txt","r");
print "Opend file sucessfully";
}
// Test of the code here.
?>
This way you can write an efficient code. Using above technique you can stop your program
whenever it errors out and display more meaningful and user friendly message.
Defining Custom Error Handling Function
You can write your own function to handling any error. PHP provides you a framework to define
error handling function.
This function must be able to handle a minimum of two parameters (error level and error message) but
can accept up to five parameters (optionally: file, line-number, and the error context) −
Syntax
error_function(error_level,error_message, error_file,error_line,error_context);
Sr.No Parameter & Description

1 82
error_level
Required - Specifies the error report level for the user-defined error. Must be a value
number.

Pallavi Engineering College


PHP Programming _IV_ECE

2
error_message
Required - Specifies the error message for the user-defined error

3
error_file
Optional - Specifies the file name in which the error occurred

4
error_line
Optional - Specifies the line number in which the error occurred

5
error_context
Optional - Specifies an array containing every variable and their values in use when the
error occurred

Possible Error levels


These error report levels are the different types of error the user-defined error handler can be used for.
These values cab used in combination using | operator

Sr.No Constant & Description Value

1 1
.E_ERROR
Fatal run-time errors. Execution of the script is halted

2 2
E_WARNING
Non-fatal run-time errors. Execution of the script is not halted

3 4
E_PARSE
Compile-time parse errors. Parse errors should only be generated by the parser.

4 8
E_NOTICE
Run-time notices. The script found something that might be an error, but could
also happen when running a script normally

5 16
E_CORE_ERROR
83
Fatal errors that occur during PHP's initial start-up.

Pallavi Engineering College


PHP Programming _IV_ECE

6 32
E_CORE_WARNING
Non-fatal run-time errors. This occurs during PHP's initial start-up.

7 256
E_USER_ERROR
Fatal user-generated error. This is like an E_ERROR set by the programmer using
the PHP function trigger_error()

8 512
E_USER_WARNING
Non-fatal user-generated warning. This is like an E_WARNING set by the
programmer using the PHP function trigger_error()

9 1024
E_USER_NOTICE
User-generated notice. This is like an E_NOTICE set by the programmer using the
PHP function trigger_error()

10 2048
E_STRICT
Run-time notices. Enable to have PHP suggest changes to your code which will
ensure the best interoperability and forward compatibility of your code.

11 4096
E_RECOVERABLE_ERROR
Catchable fatal error. This is like an E_ERROR but can be caught by a user
defined handle (see also set_error_handler())

12 8191
E_ALL
All errors and warnings, except level E_STRICT (E_STRICT will be part of
E_ALL as of PHP 6.0)

All the above error level can be set using following PHP built-in library function where level cab be
any of the value defined in above table.
int error_reporting ( [int $level] )
Following is the way you can create one error handling function −
<?php
function handleError($errno, $errstr,$error_file,$error_line) {
echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
84
echo "<br />";
echo "Terminating PHP Script";

die();
Pallavi Engineering College
PHP Programming _IV_ECE

}
?>
Once you define your custom error handler you need to set it using PHP built-in
library set_error_handler function. Now lets examine our example by calling a function which does
not exist.
<?php
error_reporting( E_ERROR );

function handleError($errno, $errstr,$error_file,$error_line) {


echo "<b>Error:</b> [$errno] $errstr - $error_file:$error_line";
echo "<br />";
echo "Terminating PHP Script";

die();
}

//set error handler


set_error_handler("handleError");

//trigger error
myFunction();
?>
Exceptions Handling
PHP 5 has an exception model similar to that of other programming languages. Exceptions are
important and provides a better control over error handling.
Lets explain there new keyword related to exceptions.
 Try − A function using an exception should be in a "try" block. If the exception does not
trigger, the code will continue as normal. However if the exception triggers, an exception is
"thrown".
 Throw − This is how you trigger an exception. Each "throw" must have at least one "catch".
 Catch − A "catch" block retrieves an exception and creates an object containing the exception
information.
When an exception is thrown, code following the statement will not be executed, and PHP will
attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be
issued with an "Uncaught Exception ...
 An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a
try block.
 Each try must have at least one corresponding catch block. Multiple catch blocks can be used
to catch different classes of exceptions.
 Exceptions can be thrown (or re-thrown) within a catch block. 85
Example
Following is the piece of code, copy and paste this code into a file and verify the result.

Pallavi Engineering College


PHP Programming _IV_ECE

<?php
try {
$error = 'Always throw this error';
throw new Exception($error);

// Code following an exception is not executed.


echo 'Never executed';
}catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>
In the above example $e->getMessage function is used to get error message. There are following
functions which can be used from Exception class.
 getMessage() − message of exception
 getCode() − code of exception
 getFile() − source filename
 getLine() − source line
 getTrace() − n array of the backtrace()
 getTraceAsString() − formated string of trace
Creating Custom Exception Handler
You can define your own custom exception handler. Use following function to set a user-defined
exception handler function.
string set_exception_handler ( callback $exception_handler )
Here exception_handler is the name of the function to be called when an uncaught exception occurs.
This function must be defined before calling set_exception_handler().
Example
<?php
function exception_handler($exception) {
echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');
throw new Exception('Uncaught Exception');

echo "Not Executed\n";


?>
86

GD-Library:

The "GD Library" is the most used image-processing tool in PHP, allowing the dynamic creation and
Pallavi Engineering College
PHP Programming _IV_ECE

editing of images, charts, thumbnails, etc.

The file types that can be created and/or edited using the GD library are GIF, JPEG and PNG.

The GD library will be included with most PHP installations. To confirm if the GD library is activated
on your server/host, you can run <?php echo phpinfo(); ?> and scroll down to "GD" to confirm its
status.

The GD library includes over 100 functions:

Function Description

gd_info Retrieve information about the currently installed GD library

getimagesize Get the size of an image

image_type_to_extension Get file extension for image type

image_type_to_mime_type Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail


exif_imagetype

image2wbmp Output image to browser or file

imagealphablending Set the blending mode for an image

imageantialias Should antialias functions be used or not

imagearc Draws an arc

imagechar Draw a character horizontally

imagecharup Draw a character vertically

imagecolorallocate Allocate a color for an image

imagecolorallocatealpha Allocate a color for an image

imagecolorat Get the index of the color of a pixel

imagecolorclosest Get the index of the closest color to the specified color

imagecolorclosestalpha Get the index of the closest color to the specified color + alpha

imagecolorclosesthwb Get the index of the color which has the hue, white and blackness

imagecolordeallocate De-allocate a color for an image


87
imagecolorexact Get the index of the specified color

imagecolorexactalpha Get the index of the specified color + alpha

Pallavi Engineering College


PHP Programming _IV_ECE

imagecolormatch Makes the colors of the palette version of an image more closely match the true color vers

imagecolorresolve Get the index of the specified color or its closest possible alternative

imagecolorresolvealpha Get the index of the specified color + alpha or its closest possible alternative

imagecolorset Set the color for the specified palette index

imagecolorsforindex Get the colors for an index

imagecolorstotal Find out the number of colors in an image's palette

imagecolortransparent Define a color as transparent

imageconvolution Apply a 3x3 convolution matrix, using coefficient and offset

imagecopy Copy part of an image

imagecopymerge Copy and merge part of an image

imagecopymergegray Copy and merge part of an image with gray scale

imagecopyresampled Copy and resize part of an image with resampling

imagecopyresized Copy and resize part of an image

imagecreate Create a new palette based image

imagecreatefromgd2 Create a new image from GD2 file or URL

imagecreatefromgd2part Create a new image from a given part of GD2 file or URL

imagecreatefromgd Create a new image from GD file or URL

imagecreatefromgif Create a new image from file or URL

imagecreatefromjpeg Create a new image from file or URL

imagecreatefrompng Create a new image from file or URL

imagecreatefromstring Create a new image from the image stream in the string

imagecreatefromwbmp Create a new image from file or URL

imagecreatefromxbm Create a new image from file or URL

imagecreatefromxpm Create a new image from file or URL 88

imagecreatetruecolor Create a new true color image

Pallavi Engineering College


PHP Programming _IV_ECE

imagedashedline Draw a dashed line

imagedestroy Destroy an image

imageellipse Draw an ellipse

imagefill Flood fill

imagefilledarc Draw a partial arc and fill it

imagefilledellipse Draw a filled ellipse

imagefilledpolygon Draw a filled polygon

imagefilledrectangle Draw a filled rectangle

imagefilltoborder Flood fill to specific color

imagefilter Applies a filter to an image

imagefontheight Get font height

imagefontwidth Get font width

imageftbbox Give the bounding box of a text using fonts via freetype2

imagefttext Write text to the image using fonts using FreeType 2

imagegammacorrect Apply a gamma correction to a GD image

imagegd2 Output GD2 image to browser or file

imagegd Output GD image to browser or file

imagegif Output image to browser or file

imagegrabscreen Captures the whole screen

imagegrabwindow Captures a window

imageinterlace Enable or disable interlace

imageistruecolor Finds whether an image is a truecolor image

imagejpeg Output image to browser or file

imagelayereffect Set the alpha blending flag to use the bundled libgd layering effects 89

imageline Draw a line

Pallavi Engineering College


PHP Programming _IV_ECE

imageloadfont Load a new font

imagepalettecopy Copy the palette from one image to another

imagepng Output a PNG image to either the browser or a file

imagepolygon Draws a polygon

imagepsbbox Give the bounding box of a text rectangle using PostScript Type1 fonts

imagepsencodefont Change the character encoding vector of a font

imagepsextendfont Extend or condense a font

imagepsfreefont Free memory used by a PostScript Type 1 font

imagepsloadfont Load a PostScript Type 1 font from file

imagepsslantfont Slant a font

imagepstext Draws a text over an image using PostScript Type1 fonts

imagerectangle Draw a rectangle

imagerotate Rotate an image with a given angle

imagesavealpha Set the flag to save full alpha channel information (as opposed to single-color transparenc
when saving PNG images

imagesetbrush Set the brush image for line drawing

imagesetpixel Set a single pixel

imagesetstyle Set the style for line drawing

imagesetthickness Set the thickness for line drawing

imagesettile Set the tile image for filling

imagestring Draw a string horizontally

imagestringup Draw a string vertically

imagesx Get image width

imagesy Get image height


90
imagetruecolortopalette Convert a true color image to a palette image

imagettfbbox Give the bounding box of a text using TrueType fonts

Pallavi Engineering College


PHP Programming _IV_ECE

imagettftext Write text to the image using TrueType fonts

imagetypes Return the image types supported by this PHP build

imagewbmp Output image to browser or file

imagexbm Output XBM image to browser or file

iptcembed Embeds binary IPTC data into a JPEG image

iptcparse Parse a binary IPTC block into single tags.

jpeg2wbmp Convert JPEG image file to WBMP image file

png2wbmp Convert PNG image file to WBMP image file

Creating An Image With the PHP GD Library

The three standard type of images that can be created from scratch with the PHP GD Library are: JPG,
GIF and PNG.

JPG Is Designed to Compress Full-Color Images, & Is Ideal For Digital Photos, Etc.
GIF Is Designed to Support Only 256 Colors, Along With Transparency, Interlacing & Animation
PNG Is Designed As An Alternative to GIF, With the Same Basic Features, But Does Not Support
Animation

The header() function is used to tell the browser which content type it will be sent. This must be
specified before any other output is sent to the browser, whether it is blank lines, PHP code, HTML
tags, etc. The header options for images are:

header('Content-type: image/jpeg');
header('Content-type: image/gif');
header('Content-type: image/png');

Now we can use the imagecreate() function to create a blank image, assign it a width and height, and
store it in a variable. The syntax is: imagecreate(width, height)

So far, our code might look like this:

<?php

header('Content-type: image/png');
$png_image = imagecreate(150, 150);
91
?>

Using the imagecreatetruecolor() function will create a black image (instead of a blank image) with

Pallavi Engineering College


PHP Programming _IV_ECE

your specified width and height, which you can then see against a white background.

Alternatively, the next step would be to specify the background color of the image, or fill it, using the
imagecolorallocate() function. The syntax is: imagecolorallocate(image, red, green, blue)

"Red", "Green" and "Blue" indicate where the values of these color components should be specified.
The parameters allow integers between 0 and 255, or hexadecimals between 0x00 and 0xFF.

<?php

header('Content-type: image/png');
$png_image = imagecreate(150, 150);
imagecolorallocate($png_image, 15, 142, 210);
?>

Alternatively, the imagecolorallocate() function is used to specify a color and store it in a variable,
while the imagefilltoborder() function is actually used to flood fill the entire image with color.

If you tried out either of the above examples, you received an error, didn't you? That is because the
code was not complete. To complete the code, we can now send our image to the browser. Three
functions are available for this purpose, one for each type of image.

imagejpeg()
imagegif()
imagepng()

Afterward, we can clear up the memory that is being taken up by storing the image. The
imagedestroy() function us used for this purpose.

<?php

header('Content-type: image/png');
$png_image = imagecreate(150, 150);
imagecolorallocate($png_image, 15, 142, 210);
imagepng($png_image);
imagedestroy($png_image);
?>

And there we have it, our image is now created, colored and sent to the browser. Try it out!

See Example 92

Note: To save an image to the server on the fly, use the image function's second parameter to specify a
location and filename.

Pallavi Engineering College


PHP Programming _IV_ECE

$path_image = 'saved-example.png';
imagepng($png_image, $path_image);

Summary:

Function Description

header() Send a Raw HTTP Header

imagecreate() Create a New (Blank) Palette-Based Image

imagecreatetruecolor() Create a New True-Color (Black) Image

imagecolorallocate() Allocate a Color For An Image

imagefilltoborder() Flood Fill to Specific Color

imagejpeg() Output a JPEG/JPG Image to Browser or File

imagegif() Output a GIF Image to Browser or File

imagepng() Output a PNG Image to Browser or File

imagedestroy() Destroy An Image

How to Draw Lines On An Image

Before we begin drawing on our image, there are two functions that we should consider, for added
variety.

1. Line color can be modified using the imagecolorallocate() function, which we learned about before.
It should be stored in a variable to be used later.

2. Line thickness can be modified using the imagesetthickness() function, which requires two
parameters: imagesetthickness(image, thickness)

The imageline() function itself requires 6 parameters. The syntax is: imageline(image, x1, y1, x2, y2,
color)

image = Refers to the Image Resource That the Line Will Be Applied to
x1 = x-coordinate For First Point
y1 = y-coordinate For First Point
x2 = x-coordinate For Second Point
y2 = y-coordinate For Second Point 93
color = Refers to the Line Color Identifier Created With imagecolorallocate()

<?php

Pallavi Engineering College


PHP Programming _IV_ECE

header('Content-type: image/png');
$png_image = imagecreate(150, 150);
imagecolorallocate($png_image, 15, 142, 210);
$black = imagecolorallocate($png_image, 0, 0, 0);
imageline($png_image, 0, 0, 150, 150, $black);
imagepng($png_image);
imagedestroy($png_image);
?>

Guess what the program above will do? It will draw a diagonal black line from the top left to the
bottom right of the image.

Now, can you figure out how to draw a thick black border around the entire image? That might be
more of a challenge...

<?php

header('Content-type: image/png');
$png_image = imagecreate(150, 150);

imagecolorallocate($png_image, 15, 142, 210);


imagesetthickness($png_image, 5);
$black = imagecolorallocate($png_image, 0, 0, 0);

$x = 0;
$y = 0;
$w = imagesx($png_image) - 1;

$z = imagesy($png_image) - 1;

imageline($png_image, $x, $y, $x, $y+$z, $black);


imageline($png_image, $x, $y, $x+$w, $y, $black);
imageline($png_image, $x+$w, $y, $x+$w, $y+$z, $black);
imageline($png_image, $x, $y+$z, $x+$w ,$y+$z, $black);

imagepng($png_image);
imagedestroy($png_image);
?>
94
See Example

To draw dashed lines, use the following function and syntax: imagedashedline(image, x1, y1, x2, y2,
Pallavi Engineering College
PHP Programming _IV_ECE

color)

<?php

header('Content-type: image/png');
$png_image = imagecreate(150, 150);

imagecolorallocate($png_image, 15, 142, 210);


imagesetthickness($png_image, 5);
$black = imagecolorallocate($png_image, 0, 0, 0);

$x = 0;
$y = 0;
$w = imagesx($png_image) - 1;

$z = imagesy($png_image) - 1;

imageline($png_image, $x, $y, $x, $y+$z, $black);


imageline($png_image, $x, $y, $x+$w, $y, $black);
imageline($png_image, $x+$w, $y, $x+$w, $y+$z, $black);
imageline($png_image, $x, $y+$z, $x+$w ,$y+$z, $black);

imagedashedline($png_image, 150, 0, 0, 150, $black);

imagepng($png_image);
imagedestroy($png_image);
?>

See Example

Summary:

Function Description

imagecolorallocate() Allocate a Color For An Image

imagesetthickness() Set the Thickness For Line Drawing

imageline() Draw a Line


95
imagedashedline() Draw a Dashed Line

Pallavi Engineering College


PHP Programming _IV_ECE

How to Add Text to An Image

In order to add text to an image, you need two things: the image and the font.

For our example, we will use an existing image, rather than creating our own. We will also need a ".ttf"
font file (of any font type/style that you want) uploaded to the server that your script will be running
from. (You can download fonts at websites such as Search Free Fonts.)

Three functions are used to create an image from an existing image, so that it can be used/edited. These
functions are imagecreatefromgif(), imagecreatefromjpeg() and imagecreatefrompng(). You simply
choose which function to use based on your image file type.

The imagettftext() function will be used to actually write the text to the image. The syntax is:
imagettftext(resource $image, float $size, float $angle, int $x, int $y, int $color, string $fontfile, string
$text)

Most of the imagettftext() function's parameters are self-explanatory, but let's review each on briefly.

Image = Identifies the Image to Add Text To


Size = Specifies Font Size, Usually Measured in Pixels
Angle = Degree/Angle Text Should be Printed, With 0 Being Left-to-Right "Normal" Text
X = Coordinate (From Left) Indicating Beginning Location of Text
Y = Coordinate (From Top) Indicating Beginning Location of Text
Color = Color of Text, Usually Already Stored In Variable Using imagecolorallocate() Function
Font File = Path to the TrueType ".ttf" Font File
Text = String of Text to Be Printed On Image (UTF-8 Encoding)

Now let's go over the basic outline of the steps that we need to perform:

Set the Content Type


Create Image From Existing File
Allocate A Color For The Text
Set Path to Font File
Set Text to Be Printed On Image
Print Text On Image
Send Image to Browser
Clear Memory

From here, the code should be relatively simple.

<?php
//Set the Content Type
header('Content-type: image/jpeg');
96
// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('sunset.jpg');

// Allocate A Color For The Text


Pallavi Engineering College
PHP Programming _IV_ECE

$white = imagecolorallocate($jpg_image, 255, 255, 255);

// Set Path to Font File


$font_path = 'font.TTF';

// Set Text to Be Printed On Image


$text = "This is a sunset!";

// Print Text On Image


imagettftext($jpg_image, 25, 0, 75, 300, $white, $font_path, $text);

// Send Image to Browser


imagejpeg($jpg_image);

// Clear Memory
imagedestroy($jpg_image);
?>

Assignment: Try adjusting the angle and coordinates of the text to come up with these results:

Summary:

Function Description

imagecreatefromgif() Creates a New Image From GIF File or URL

imagecreatefromjpeg() Creates a New Image From JPG File or URL

imagecreatefrompng() Creates a New Image From PNG File or URL

imagettftext() Write Text to An Image Using TrueType Fonts

Cookies Vs. Sessions

Before we learn how to create cookies and sessions it is important to understand the difference
between these two similar (and yet very different) methods of storing information. And before we
begin to explain that, let's get one very important detail out of the way; the kind of cookies that we will
be discussing are no more edible than my keyboard. (And yes, my keyboard is plastic.)

The basic task of both cookies and sessions is to store visitor data so that it can be accessed by every 97
page on a website. This data is usually provided by the visitor and used to customize the experience,
including their visit statistics, identity, setting and/or preferences, etc.

Cookies are small files that are stored in the visitor's browser.
Pallavi Engineering College
PHP Programming _IV_ECE

Cookies can have a long lifespan, lasting months or even years.


Cookies are limited in size depending on each browser's default settings.
Cookies can be disabled if the visitor's browser does not allow them (uncommon).
Cookies can be edited by the visitor. (Do not use cookies to store sensitive data.)

Sessions are small files that are stored on the website's server.
Sessions have a limited lifespan; they expire when the browser is closed.
Sessions are only limited in size if you limit their size on the server.
Sessions cannot be disabled by the visitor because they are not stored in the browser.
Sessions cannot be edited by the visitor.

In short, cookies serve as a temporary or long-term storage unit on the visitor's computer that should
not contain sensitive information, and sessions serve as a temporary storage unit not on the visitor's
computer that can hide sensitive information. For most tasks I find it efficient to use sessions and
cookies together.

By giving each visitor a cookie with a unique ID, I can use that cookie to recognize each visitor when
they return. I can then use sessions to handle the page-to-page data exchange that actually provides
each visitor with their customized settings and information, which are provided by each visitor and
stored in a database until they are reference by the unique ID stored in the cookie.

Now that's wasn't too hard to swallow, was it? But, now that you know the difference between sessions
and cookies, feel free to skip over actually learning them, until you plan to use them... they are not yet
vital knowledge.

PHP Cookies

Cookies are small files that are stored in the visitor's browser.Cookies can be used to identify return
visitors, keep a user logged into a website indefinitely, track the time of the user's last visit, and much
more.

Cookies accept seven different arguments, but only the "name" is required. (Keep in mind that all
values are stored on the visitor's computer, so the data is not private. Never store passwords in cookies,
for example!) The options are:

Argument Description

name Name of the Cookie

value Value of the Cookie

expire Time When Cookie Expires (Unix Timestamp) (If "0", Or Omitted, Cookie Will Expire
When Browser Closes) (Set to Client's Time, Not Server's)

path Server Path Where Cookie Is Available (If Path Is the Root Directory, Cookie Is Available
In Entire Domain) (Default Value Is Current Directory)
98
domain Domain That Cookie Is Available

secure Indicates That Cookie Should Only Be Transmitted Over a Secure HTTPS Connection

Pallavi Engineering College


PHP Programming _IV_ECE

From Client

httponly When TRUE, Cookie Is Only Accessible Through HTTP Protocol

PHP allows you to create, retrieve and update cookies. The setcookie() function is used to first create a
cookie. This function must be run before any other data is sent to the browser, such as the opening
<html> tag or random whitespace. The syntax is: setcookie(name, value, expire, path, domain);

<?php
setcookie("Example", "Whatever Value I Want", time()+2592000);
?>

Here we have set a cookie called "Example" that has a useless value of "Whatever Value I Want" and
an expiration date one month in the future. (We have not yet studied php date and time functions, so I
will briefly clarify that the time() function collects the current timestamp and adds 2591000 seconds to
it, which is 30 day's worth of seconds, thus creating an expiration date 30 days in the future.)

Now, we are free to retrieve the "value" that is stored in our cookie, using the $_COOKIE superglobal.
It is best to use the isset() function for this, because if a cookie has not been set on the computer that
we are trying to retrieve it from, headaches can result.

<?php
if (isset($_COOKIE["Example"])) {
echo $_COOKIE["Example"];
} else {
echo "No Cookie Named 'Example' Is Set";
}
?>

Here we check to see if the cookie that we created really was created, and echo the value if it was. The
value that will be echoed is "Whatever Value I Want". A more practical example might have stored the
user's name or preferences, but it's fun to be unpredictable.

Deleting a cookie is as simple as using the setcookie() function with an expiration date in the past.
Since there are 3600 seconds in an hour, using -3600 will set the expiration date an hour previous and
the cookie will expire and disappear.

<?php
setcookie("Example", "", time()-3600);
?>

Finally! A cookie that your mother won't limit your intake of!

PHP Sessions
99
Sessions are small, temporary files that are stored on the website's server. Sessions can be used to store
unique information about, or change unique settings for each visitor, but only for the duration of each
separate visit.

Pallavi Engineering College


PHP Programming _IV_ECE

Sessions work by assigning each visitor a unique string that is used to identify them as they move from
page to page. This prevents one visitor's information from being mixed up with another's.

PHP allows you to create and destroy a session, as well as assign, retrieve and update session variables.
The session_start() function is used to first create a session, or to continue the current session if one
already exists. This function must be run on every page, before any other data is sent to the browser,
such as the opening <html> tag or random whitespace. The code is very simple.

<?php
session_start();
?>

After starting the session you can store session variables in the $_SESSION superglobal, as well as
update and retrieve them. Each value stored in this array is assigned a "key" or name by which to
identify the specific value. The syntax is: $_SESSION['key'] = value;

<?php
session_start();

$_SESSION['question'] = 'What happens when you throw a green stone in the red sea?';

$_SESSION['answer'] = 'It gets wet!';


?>

Due to the nature of sessions, you can assign a session value on one page and retrieve it on a
completely separate page, as long as session_start() is set at the beginning of the file. The best practice
is to check and see if each session value exists before retrieving it, by using the isset() function.

<?php
session_start();

if (isset($_SESSION['question']) && isset($_SESSION['answer'])) {


echo $_SESSION['question'];
echo $_SESSION['answer'];
}
?>

Although sessions will end themselves and erase all session variables after a period of inactivity, it is
possible to speed up the process. This is necessary if you are using sessions to keep a person logged
into a website, for example, and they click "logout". The unset() function will free (erase) a specific
session variable, and the session_destroy() function will end the session completely, as well as erase all
session variables.

<?php
unset($_SESSION['question']);
unset($_SESSION['answer']);
100
session_destroy();
?>

PHP mail:
Pallavi Engineering College
PHP Programming _IV_ECE

The mail() function allows you to send emails, as long as the server has a fully-functional email system
already set up.

This function accepts five different parameters, only four of which we will discuss here, and only three
of which are required.

Parameter Importance Description

to Required Recipient(s) of Email

subject Required Subject of Email

message Required Message Body of Email

headers Optional From, Reply-To, CC, BCC, Date, Etc.

Listed in order of appearance, the parameters are: mail(to,subject,message,headers)

One of the most simple examples of the mail() function is:

<?php

mail("an-email@a-domain.com","Brilliant Subject","Boring message body.");

?>

The addition of headers allows you to specify who the email is from and who should be copied and/or
blind copied on an email

<?php

$to = "an-email@a-domain.com";
$subject = "Why do dogs bury bones in the ground?";
$message = "Because they can't bury them in trees!";
$headers = 'From: <an-email@a-domain.com>' . "\r\n";

$headers .= 'Reply-To: an-email@a-domain.com' . "\r\n";

$headers .= 'Cc: an-email@a-domain.com' . "\r\n";

$headers .= 'Bcc: an-email@a-domain.com' . "\r\n";


101
mail($to,$subject,$message,$headers);
?>

Pallavi Engineering College


PHP Programming _IV_ECE

HTML emails can be sent by specifying the appropriate content-type in the header.

<?php

$to = "an-email@a-domain.com";
$subject = "This is an HTML email!";
$message = "
<html>
<body>
<h2>Cool, right?</h2>
</body>
</html>
";
$headers = 'From: <an-email@a-domain.com>' . "\r\n";

$headers .= "MIME-Version: 1.0" . "\r\n";

$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";


mail($to,$subject,$message,$headers);
?>

Unit-5
MySQL Database Introduction
What is MySQL?
MySQL is an open-source relational database management system (RDBMS). It is the most popular database
system used with PHP. MySQL is developed, distributed, and supported by Oracle Corporation.
 The data in a MySQL database are stored in tables which consists of columns and rows.
 MySQL is a database system that runs on a server.
 MySQL is ideal for both small and large applications.
 MySQL is very fast, reliable, and easy to use database system.It uses standard SQL
 MySQL compiles on a number of platforms.
Downloading MySQL Database
MySQL can be downloaded for free from this link.
How to connect PHP with MySQL Database?
PHP 5 and later can work with a MySQL database using:
1. MySQLi extension.
2. PDO (PHP Data Objects).
Difference Between MySQLi and PDO
 PDO works on 12 different database systems, whereas MySQLi works only with MySQL databases. 102
 Both PDO and MySQLi are object-oriented, but MySQLi also offers a procedural API.
 If at some point of development phase, the user or the development team wants to change the database then it is easy
to that in PDO than MySQLi as PDO supports 12 different database systems.He would have to only change the
connection string and a few queries. With MySQLi,he will need to rewrite the entire code including the queries.

Pallavi Engineering College


PHP Programming _IV_ECE

There are three ways of working with MySQl and PHP


1. MySQLi (object-oriented)
2. MySQLi (procedural)
3. PDO
Connecting to MySQL database using PHP
There are 3 ways in which we can connect to MySQl from PHP as listed above and described below:
1. Using MySQLi object-oriented procedure: We can use the MySQLi object-oriented procedure to establish a
connection to MySQL database from a PHP script.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = new mysqli($servername, $username, $password);

// Checking connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Output:

Explanation: We can create an instance of the mysqli class providing all the necessary details required to establish
the connection such as host, username, password etc. If the instance is created successfully then the connection is
successful otherwise there is some error in establishing connection.
2. Using MySQLi procedural procedure : There is also a procedural approach of MySQLi to establish a
connection to MySQL database from a PHP script as described below.
Syntax:
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Creating connection
$conn = mysqli_connect($servername, $username, $password);

// Checking connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Output:
Connected successfully
1. Explanation: In MySQLi procedural approach instead of creating an instance we can use the
mysqli_connect() function available in PHP to establish a connection. This function takes the information as
arguments such as host, username , password , database name etc. This function returns MySQL link 103
identifier on successful connecction or FALSE when failed to establish a connection.
2. Using PDO procedure: PDO stands for PHP Data Objects. That is, in this method we connect to the
database using data objects in PHP as described below:
Syntax:

Pallavi Engineering College


PHP Programming _IV_ECE

<?php
$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// setting the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Output:

Explanation:The exception class in PDO is used to handle any problems that may occur in our database
queries. If an exception is thrown within the try{ } block, the script stops executing and flows directly to the
first catch(){ } block.
Closing A Connection
When we establish a connection to MySQL database from a PHP script , we should also disconnect or close the
connection when our work is finished. Here we have described the syntax of closing the connection to a MySQL
database in all 3 methods described above. We have assumed that the reference to the connection is stored in
$conn variable.
1. Using MySQLi object oriented procedure
Syntax
2. $conn->close();
3. Using MySQLi procedural procedure
Syntax
4. mysqli_close($conn);
5. Using PDO procedure
Syntax
$conn = null;

PHP CRUD Create, edit, update and delete posts


with MySQL database

Creating, editing, updating and deleting content on a website is what makes the site dynamic.
That's what we are going to be doing in this post.

A user who visits our site will be able to create posts that will be saved in a mysql database, 104
retrieve the posts from the database and display them on the web page. Each post will be
displayed with an edit and delete button to permit the user to update posts as well as delete them.

First, create a database named crud. In the crud database, create a table called info. The info
Pallavi Engineering College
PHP Programming _IV_ECE

table should have the following columns:

 id - int(11)

 name - varchar(100)
 address - varchar(100)

Yap! Just two fields. I'm trying to keep things simple here. so, let's move on to the next step.

Create a file called index.php and paste in it the following code:

<!DOCTYPE html>
<html>
<head>
<title>CRUD: CReate, Update, Delete PHP MySQL</title>
</head>
<body>
<form method="post" action="server.php" >
<div class="input-group">
<label>Name</label>
<input type="text" name="name" value="">
</div>
<div class="input-group">
<label>Address</label>
<input type="text" name="address" value="">
</div>
<div class="input-group">
<button class="btn" type="submit" name="save" >Save</button>
</div>
</form>
</body>
</html>

If you save and open the site on your browser, you get something like this:

105

Doesn't look like the best form in the world right? Let's fix that. Add this line directly below the
Pallavi Engineering College
PHP Programming _IV_ECE

<title> tag in the head section of your index.php file:

<link rel="stylesheet" type="text/css" href="style.css">

Thats the link to load styling from the stylesheet file. Let's create the styles.css file and add this
styling code in it.

body {
font-size: 19px;
}
table{
width: 50%;
margin: 30px auto;
border-collapse: collapse;
text-align: left;
}
tr {
border-bottom: 1px solid #cbcbcb;
}
th, td{
border: none;
height: 30px;
padding: 2px;
}
tr:hover {
background: #F5F5F5;
}

form {
width: 45%;
margin: 50px auto;
text-align: left;
padding: 20px;
border: 1px solid #bbbbbb;
border-radius: 5px; 106
}

.input-group {
Pallavi Engineering College
PHP Programming _IV_ECE

margin: 10px 0px 10px 0px;


}
.input-group label {
display: block;
text-align: left;
margin: 3px;
}
.input-group input {
height: 30px;
width: 93%;
padding: 5px 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid gray;
}
.btn {
padding: 10px;
font-size: 15px;
color: white;
background: #5F9EA0;
border: none;
border-radius: 5px;
}
.edit_btn {
text-decoration: none;
padding: 2px 5px;
background: #2E8B57;
color: white;
border-radius: 3px;
}

.del_btn {
text-decoration: none;
padding: 2px 5px;
color: white;
border-radius: 3px; 107
background: #800000;
}
.msg {
Pallavi Engineering College
PHP Programming _IV_ECE

margin: 30px auto;


padding: 10px;
border-radius: 5px;
color: #3c763d;
background: #dff0d8;
border: 1px solid #3c763d;
width: 50%;
text-align: center;
}

Now let's check our form out in the browser again:

That's better!

I usually like to separate my HTML code from my PHP code as much as possible. I consider that
good practice. On that note, let's create another file called php_code.php where we implement all
php functionalities like connecting to the database, query the database and the like.

So open php_code.php and paste the following code in it:

<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'crud');

// initialize variables
$name = "";
$address = "";
$id = 0;
$update = false;

if (isset($_POST['save'])) {
$name = $_POST['name'];
108
$address = $_POST['address'];

mysqli_query($db, "INSERT INTO info (name, address) VALUES ('$name',


'$address')");
Pallavi Engineering College
PHP Programming _IV_ECE

$_SESSION['message'] = "Address saved";


header('location: index.php');
}

// ...

Now include this file at the top (the very first line) of your index.php file. Like so:

<?php include('server.php'); ?>

At this point, all that this code does is connect to the database, initialize some variables and
saves submitted data from the form to the database in the info we created earlier. That's only the
CReate part of CRUD. Let's proceed with the others.

Now visit again your index.php file and add this code right under the <body> tag:

// ...
<body>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>

This code displays a confirmation message to tell the user that a new record has been created in
the database.

To retrieve the database records and display them on the page, add this code immediately above
the input form:

109
<?php $results = mysqli_query($db, "SELECT * FROM info"); ?>

<table>
Pallavi Engineering College
PHP Programming _IV_ECE

<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th colspan="2">Action</th>
</tr>
</thead>

<?php while ($row = mysqli_fetch_array($results)) { ?>


<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['address']; ?></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>"
class="edit_btn" >Edit</a>
</td>
<td>
<a href="server.php?del=<?php echo $row['id']; ?>"
class="del_btn">Delete</a>
</td>
</tr>
<?php } ?>
</table>

<form>
// ...

Let's create a new record and see if this stuff works:

..and voila!! It works perfect!

Now we move onto editting. At the top of your index.php file (immediately after the include
statement) add the following code:
110

<?php
if (isset($_GET['edit'])) {
Pallavi Engineering College
PHP Programming _IV_ECE

$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM info WHERE id=$id");

if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$address = $n['address'];
}
}
?>

When editting a database record, we need to put the old values in the form so that they can be
modified. To do so, let's modify our input fields on the form and set those values taken from the
database ($name, $address) as values to the value attribute of the form fields.

Also add a hidden field to hold the id of the record we will be updating so that it can be
recognized in the database uniquely by it's id. This explains it better:

// newly added field


<input type="hidden" name="id" value="<?php echo $id; ?>">

// modified form fields


<input type="text" name="name" value="<?php echo $name; ?>">
<input type="text" name="address" value="<?php echo $address; ?>">

Remember all of that is in the input <form>.

Now if we click on the edit button on a particular record from the database, the values will be filled
in the form and we will be able to edit them. Since we are editing on the same form as when we
are creating, we have to put a condition that determines the appropriate button to be displayed.
For example, when editing, we display the update button on the form and when creating, we
display the save button. We do this using the update variable which is boolean. When update is
true, the update button is displayed and if false, the save button is displayed.

Replace your save button on the form like this: 111

Replace ..

Pallavi Engineering College


PHP Programming _IV_ECE

<button class="btn" type="submit" name="save" >Save</button>

with...

<?php if ($update == true): ?>


<button class="btn" type="submit" name="update" style="background: #556B2F;"
>update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif ?>

Now if we run this on the browser and click the edit button, we get this:

Now you can see it is the update button that is displayed. Let's add the code that will be executed
when this button is clicked.

Open php_code.php file and add this code at the button:

// ...

if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$address = $_POST['address'];

mysqli_query($db, "UPDATE info SET name='$name', address='$address' WHERE


id=$id");
$_SESSION['message'] = "Address updated!";
header('location: index.php');
}

112
Now change the values in the form and click the update button.

Pallavi Engineering College


PHP Programming _IV_ECE

Great!

One last thing: deleting records. Just add this code at the end of you php_code.php file and
you're good to go:

if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM info WHERE id=$id");
$_SESSION['message'] = "Address deleted!";
header('location: index.php');
}

If you click the delete button, it deletes the record from the database and displays the message
just like the other actions.

Introduction to PHP's Built-In MYSQL Functions

If you are thinking "What is a database?" or "Why MYSQL?", head on over to our MYSQL Tutorial. There you will
not only learn the answer to these questions, you will also learn the basic commands needed to use MYSQL.

Once you are up to speed you can begin to learn how to integrate MYSQL commands directly into your PHP
code.

PHP's MYSQLI class has over 60 built-in functions to meet your MYSQL interfacing needs. Just about anything
that you ever wanted to do (and a few that you didn't) can be done with one function or another, but we will, in
the next few pages, only concentrate on the fourteen functions that are most suited to our needs:

Function Description

mysqli_affected_rows() Returns the number of affected rows in the previous MySQL operation

mysqli_close() Closes a previously opened database connection

mysqli_connect() Opens a new connection to the MySQL server

mysqli_errno() Returns the last error code for the most recent function call
113
mysqli_error() Returns the last error description for the most recent function call

mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both

Pallavi Engineering College


PHP Programming _IV_ECE

mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both

mysqli_fetch_assoc() Fetches a result row as an associative array

mysqli_fetch_row() Fetches one row from a result-set and returns it as an enumerated array

mysqli_free_result() Frees the memory associated with a result

mysqli_num_rows() Returns the number of rows in a result set

mysqli_query() Performs a query against the database

mysqli_real_escape_string() Escapes special characters in a string for use in an SQL statement

mysqli_select_db() Changes the default database for the connection

MYSQL Connect & Close

The #1 most important step of integrating MYSQL into your PHP script is connecting to the database. And while
it is not strictly necessary to close the connection, it is always good practice to tie up any loose ends. Here we
will learn how to do both.

The mysqli_connect() function is used to connect. It requires four parameters, in the following order:
mysqli_connect(servername, username, password, databasename)

The value of "servername" will specify what server you need to connect to. Since the database is usually on the
same server as the script/connection, the default value is "localhost".

The username and password should be self-explanatory. Your web host probably provided them already. The
database name is whatever you named your database.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password", "database_name");
if (!$con) { die('Could Not Connect: ' . mysqli_error($con) . mysqli_errno($con)); }
// Do Database Stuff Here
mysqli_close($con);
?>

See what we did there? We have connected to our database and stored the connection details/handle in the
$con variable for later reference. Then we tested our connection using the handle and told the script to stop
working if the connection was faulty. And last but not least, we used mysqli_close() to close the open connection.

Notice the use of mysqli_error() and mysqli_errno(), two functions that help to debug MYSQL-related problems.
These functions can be used separately, but used together they will tell you what problem occurred and give you
the error number for that problem, enabling you to research the problem in more detail.

What could be more simple? (Don't answer that.)

Summary: 114

Function Description

Pallavi Engineering College


PHP Programming _IV_ECE

mysqli_connect() Opens a new connection to the MySQL server

mysqli_close() Closes a previously opened database connection

mysqli_errno() Returns the last error code for the most recent function call

mysqli_error() Returns the last error description for the most recent function call

Running MYSQL Queries In PHP

The mysql_query() function is a "catch all" that can run about any MYSQL query that you give it. Let's look into
the execution of some standard insert, select, update and delete statements.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password", "database_name");
if (!$con) { die('Could Not Connect: ' . mysql_error($con) . mysql_errno($con)); }

$insert = mysqli_query($con, "INSERT INTO table_name (col1, col2) VALUES('Value 1', 'Value 2'
);");
if (!$insert) { die (mysql_error($con)); }

$select = mysqli_query($con, "SELECT * FROM table_name;");


if (!$select) { die (mysql_error($con)); }

$update = mysqli_query($con, "UPDATE table_name SET col2 = 'Value' WHERE col2 LIKE 'Value 2';");
if (!$update) { die (mysql_error($con)); }

$delete = mysqli_query($con, "DELETE FROM table_name WHERE col2 LIKE 'Value';");


if (!$delete) { die (mysql_error($con)); }

mysqli_close($con);
?>

As you can see, each time mysqli_query() is used, it can be assigned a handle that we can later use to identify the
results of the statement. Also, the function is (optionally) given the opportunity to print out an error message
and die if errors occurred during execution of the statement.

Handling MYSQL Query Results In PHP

Now, how do we handle the results of the MYSQL statements executed? Decisions, decisions... That all depends
on what you want to do.

The mysqli_num_rows() function, when handed the result of an executed SELECT or SHOW statement, will return
the number of rows that will be returned.

The mysqli_affected_rows() function, when handed the result of a recently executed statement, will return how
many rows were affected by the execution of the statement.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password", "database_name");
$select = mysqli_query($con, "SELECT * FROM table_name;");
echo mysqli_num_rows($select) . ' rows were selected.'; 115

$update = mysqli_query($con, "UPDATE table_name SET col2 = 'Value' WHERE col2 LIKE 'Value 2';");
echo mysqli_affected_rows($update) . ' rows were updated.';

mysqli_close($con);
Pallavi Engineering College
PHP Programming _IV_ECE

?>

But perhaps the most useful functions are those that can help you identify and read selected data. The two most
common functions for this purpose are mysqli_fetch_array() and mysqli_fetch_assoc().

Using a while loop in combination with either of these two functions, we can come up with a simple solution to
process multiple results to an executed query.

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password", "database_name");
$result = mysql_query($con, "SELECT * FROM table_name;");

while ($list = mysqli_fetch_assoc($result)) {


echo 'Label 1: ' . $list['column_name_1'] . '<br>';
echo 'Label 2: ' . $list['column_name_2'] . '<br><br>';
}

mysqli_close($con);
?>

We can read it like this: While there is another row of results being returned from the executed query, assign it
to the $list array. Then, since we used the mysqli_fetch_assoc() function, the array will be 'associated' with the
name of each column of the database. We use those database column names to identify the data that we want
to display/format/use.

Substituting the mysqli_fetch_array() function is different only in the sense that you do not need to memorize
the column/field names in your database... You only need to memorize what order they are in, so that they can
be identified by number (beginning with '0').

<?php
$con = mysqli_connect("localhost","my_username","my_secret_password", "database_name");
$result = mysql_query($con, "SELECT * FROM table_name;");

while ($list = mysqli_fetch_array($result)) {


echo 'Label 1: ' . $list[0] . '<br>';
echo 'Label 2: ' . $list[1] . '<br><br>';
}

mysqli_close($con);
?>

One option is as good as the other, so you choose which you prefer. Just keep in mind that when referring back
to your code later on, the field names might make more sense than random numbers.

Summary:

Function Description

mysqli_affected_rows() Returns the number of affected rows in the previous MySQL operation

mysqli_fetch_all() Fetches all result rows as an associative array, a numeric array, or both

mysqli_fetch_array() Fetches a result row as an associative, a numeric array, or both 116

mysqli_fetch_assoc() Fetches a result row as an associative array

Pallavi Engineering College


PHP Programming _IV_ECE

mysqli_num_rows() Returns the number of rows in a result set

117

Pallavi Engineering College


PART – A (SHORT ANSWER QUESTIONS)
Bloom’s Course
S. No. Questions
Taxonomy Level Outcome

1 What is PHP? Remember 2


2 What is the difference between $name and $$name? Remember 2
3 What are the differences between Get and post methods. Remember 2
4 How can we create a database using PHP and MySQL? Remember 10
5 What is the use of header() function in PHP ? Remember 2
6 How can we get second of the current time using date function? Remember 3
7 List out the predefined classes in PHP? Remember 3
8 What type of inheritance that PHP supports? Remember 2
9 What are the advantages/disadvantages of MySQL and PHP? Remember 10
10 What is the difference between PHP and Javascript? Remember 3

PART – B (LONGANSWER QUESTIONS)

Bloom’s Course
S. No. Questions
Taxonomy Level Outcome

1 What are the different types of errors in PHP? Remember 2


2 What is the functionality of the function strstr and stristr? Remember 2
3 Explain about various datatypes in PHP. Understand 3
4 Explain about Arrays in PHP. Understand 2
5 List and Explain the string functions in PHP. Remember 2
6 List the statements that are used to connect PHP with MySQL. Remember 10
7 How PHP is different from PHP Script? Explain. Understand 3
8 Explain PHP form processing with an example. Understand 2
9 How can I retrieve values from one database server and store Remember
10
them in other database server using PHP?
10 What are the differences between Get and post methods in Remember
form submitting. Give the case where we can use get and we 3
can use post methods?

PART – C (PROBLEM SOLVING AND CRITICAL THINKING QUESTIONS)

Bloom’s
Course
S. No. Questions Taxonomy
Level Outcome

1 List and Explain PHP development framework Understand 2


2 Explain about database connectivity with PHP with suitable Understand
3
examples.
3 How strings are declared in PHP? Explain string operators. Remember 2
4 How array is declared in PHP. Also explain various types of Remember
2
array with proper examples.
5 Build simple calculator using PHP. Apply 3
6 Build a program using PHP that creates the web application Apply
3
for result publication
7 Build application to send a email using PHP Apply 3
8 Build a shopping cart application using PHP with use of Apply
2
cookies.
9 Explain about the control statements in PHP with example. Understand 2
10 Explain about cookies in PHP with example. Understand 3
17922 17922 17922 17922 17922 17922 17922 17922 17922

17922 Roll No.


17922 17922 17922 17922 17922 Total17922
No. of Pages
17922 : 02 17922

Total No. of Questions : 07


B.sc.(IT) (2015 Batch) (Sem.–4)
17922 17922 17922 PROGRAMMING
17922 17922 IN17922
PHP 17922 17922 17922

Subject Code : BSIT-401


Paper ID : [74083]
17922 Time : 3 Hrs.
17922 17922 17922 17922 17922 Max. Marks
17922 17922 : 60 17922

INSTRUCTIONS TO CANDIDATES :
1. SECTION-A is COMPULSORY consisting of TEN questions carrying T WO marks
17922 17922
each. 17922 17922 17922 17922 17922 17922 17922

2. SECTION-B contains SIX questions carrying TEN marks each and students have
to attempt any FOUR questions.

17922 17922 17922 17922 17922 17922 17922 17922 17922

SECTION-A

17922 1.
17922 Write briefly
17922 : 17922 17922

o m17922 17922 17922 17922

.r c
a) What these tags specify in PHP : <?php and ?>

m
17922 17922 17922 17922 17922 17922 17922 17922 17922

e
b) Can we run PHP from HTML file? If yes, how?

p
c) Why PHP is known as scripting language?
o
a .r c
17922 17922 17922 17922 17922 17922 17922 17922 17922

p
d) Write a program in PHP to calculate Square Root of a number.

17922 17922
e) How can we create
17922

b r links in PHP17922
17922
pages? 17922

p e 17922 17922 17922

a
f) What is the function of foreach construct in PHP?

rp
17922 17922 g) What is the purpose
17922 of “nl2br “string
17922 17922 function?17922 17922 17922 17922

17922 17922 17922


of arguments.
17922 17922 b
h) Write the name of PHP functions that can be used to build a function that accepts any
number 17922

i) What's the difference between include and require?


17922 17922 17922

17922 17922 j) Differences


17922 between
17922GET and POST
17922 methods. 17922 17922 17922 17922

17922 17922 17922 17922 17922 17922 17922 17922 17922

17922 1|M
17922 c o d e - 717922
4083 17922 17922 17922 17922 ( S 317922
)- E-1 17922

17922 17922 17922 17922 17922 17922 17922 17922 17922


17922 17922 17922 17922 17922 17922 17922 17922 17922

SECTION-B
17922 17922 17922 17922 17922 17922 17922 17922 17922

2. a) Write a program to create Index Based and Associative Arrays in PHP.

17922 17922 b) Write a program of


17922 Using Text in
17922 a Image.
17922 17922 17922 17922 17922

3. a) Write a program to find average of first ten natural numbers using for loop.
17922 17922 17922 17922 17922 17922 17922 17922 17922
b) Write a note on various library functions available in PHP.

4. What is the difference between Session and Cookie? Write a program to create a session,
17922 17922 to set a17922
value in session,
17922and to remove
17922data from a17922
session. 17922 17922 17922

5. Explain in detail the types of inheritance supports by PHP>.


17922 17922 17922 17922 17922 17922 17922 17922 17922
6. Write programs to scrap data from website and to upload file on website using CURL.

17922
7.
17922 17922 17922 17922

o m
What are different types of sorting functions in PHP? Explain with example in detail.
17922 17922 17922 17922

17922 17922 17922 17922 17922


.r c 17922 17922

m
17922 17922

p e o
a .r c
17922 17922 17922 17922 17922 17922 17922 17922 17922

r p e
17922 17922 17922

b 17922 17922

a
17922

p
17922 17922 17922

rp
17922 17922 17922 17922 17922 17922 17922 17922 17922

17922 17922 17922 17922 17922 b 17922 17922 17922 17922

17922 17922 17922 17922 17922 17922 17922 17922 17922

17922 17922 17922 17922 17922 17922 17922 17922 17922

17922 2|M
17922 c o d e - 717922
4083 17922 17922 17922 17922 ( S 317922
)- E-1 17922

17922 17922 17922 17922 17922 17922 17922 17922 17922


Roll No.

Total No. of Questions: 07 Total No. of Pages: 01


B.Sc. (IT) (Sem. 4)
PROGRAMMING IN PHP
Subject Code: BSIT-401
Paper ID: 74083
Time: 3 Hrs. Max. Marks: 60

INSTRUCTIONS TO CANDIDATES:
1. Section A is COMPULSORY consisting of TEN questions carrying TWO marks each.
2. Section B contains SIX questions carrying TEN marks each and students have to
attempt any FOUR questions.

SECTION A
1. Write briefly about:
a) Difference between PHP and ASP.

c) Server Side Scripting.


o m
b) What are the hardware and software requirements for PHP?

d) Scope of variable.
.r c m
e) Use of substring function.

p e o
.r c
f) Role of for each in PHP.

p a
g) What is the use of hidden Fields?

h) RDBMS.

i) Cookies.
b r p e
a
rp
j) FTP.

2.
SECTION B

Explain various data types available in PHP.


b
3. Advantages and types of functions. Explain with example.

4. Explain array with example.

5. What are the various types of joins in SQL?

6. Explain various Math function available in PHP.

7. Write steps to join web form with database in PHP.

| M74083 Page 1 of 1
22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917

Roll No. Total No. of Pages : 02


Total No. of Questions : 07
22917 22917 22917 22917
B.Sc.(IT) (2015 &22917
Onwards)22917 (Sem.–4)
22917 22917 22917

PROGRAMMING IN PHP
Subject Code : BSIT-401
22917 22917 22917 22917 Paper22917
ID : [74083]
22917 22917 22917 22917

Time : 3 Hrs. Max. Marks : 60

22917 INSTRUCTIONS
22917 22917 TO CANDIDATES
22917 : 22917 22917 22917 22917 22917
1. SECTION-A is COMPULSORY consisting of TEN questions carrying T WO marks
each.
2. SECTION-B contains SIX questions carrying TEN marks each and students have
22917 22917 to attempt
22917 any FOUR22917
questions. 22917 22917 22917 22917 22917
3. Use of non-programmable scientific calculator is allowed.

22917 22917 22917 22917 SECTION-A


22917

o m 22917 22917 22917 22917

.r c
Q1) Answer briefly :
22917 22917 22917 22917 22917 22917 22917 22917 22917
a) What is Google Caffeine?

p e m
pa
b) What is SQL Injection?
o
.r c
22917 22917 22917 22917 22917 22917 22917 22917 22917

br
c) Explain Cookies in detail.

22917 22917
d) Write22917
Process to Access
22917
Hidden Fields
22917

p
using suitablee
22917
example. 22917 22917 22917

e) What is outer Join? Explain it.


p a
22917 22917 22917
f) Differentiate 22917
While and Do-While 22917
b
Statement.r 22917 22917 22917 22917

g) Write Procedure for uploading a Data File.


22917 22917 22917 22917 22917 22917 22917 22917 22917
h) What do you mean by Dynamic Function? Explain it.

i) Explain GET Method in detail.


22917 22917 22917 22917 22917 22917 22917 22917 22917

j) Explain Single & Multidimensional array.

22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 1|M
22917 - 7 4 0 8 22917
3 22917 22917 22917 22917 ( S 22917
3)-378 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917


22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917


SECTION-B

Q2) How to create a connection between PHP and My SQL? Explain its step by step
22917 22917 22917 22917 22917 22917 22917 22917 22917
procedure.

Q3) Explain various data types and operators available in PHP.


22917 22917 22917 22917 22917 22917 22917 22917 22917
Q4) How web pages are formed in PHP using CSS? Explain it using suitable example.

Q5) Explain array using suitable example and discuss how looping and accessing of data is
22917 22917
done. 22917 22917 22917 22917 22917 22917 22917

Q6) Discuss in detail Email and File configuration.


22917 22917 22917 22917 22917 22917 22917 22917 22917
Q7) a) Explain Debugging process of PHP.

b) Discuss Control structures of PHP.


22917 22917 22917 22917 22917

o m 22917 22917 22917 22917

22917 22917 22917 22917


.r c22917 22917 22917 22917 22917

p e m
pa o
.r c
22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 22917 22917


br 22917 22917

p e
22917 22917 22917 22917

p a
22917 22917 22917 22917 22917

br 22917 22917 22917 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917

22917 2|M
22917 - 7 4 0 8 22917
3 22917 22917 22917 22917 ( S 22917
3)-378 22917

22917 22917 22917 22917 22917 22917 22917 22917 22917


22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 Roll No.


22306 22306 22306 22306 22306 Total22306
No. of Pages
22306 : 02 22306

Total No. of Questions : 07


B.sc.(IT) (2015 & Onwards) (Sem.–4)
22306 22306 22306 PROGRAMMING
22306 22306 IN22306
PHP 22306 22306 22306

Subject Code : BSIT-401


Paper ID : [74083]
22306 Time : 3 Hrs.
22306 22306 22306 22306 22306 Max. Marks
22306 22306 : 60 22306

INSTRUCTIONS TO CANDIDATES :
1. SECTION-A is COMPULSORY consisting of TEN questions carrying T WO marks
22306 22306
each. 22306 22306 22306 22306 22306 22306 22306

2. SECTION-B contains SIX questions carrying TEN marks each and students have
to attempt any FOUR questions.

22306 22306 22306 22306 22306 22306 22306 22306 22306

SECTION-A

22306 1.
22306 Write briefly
22306 : 22306 22306

o m22306 22306 22306 22306

.r c
a) What the function name in PHP to delete an element from an array?

m
22306 22306 22306 22306 22306 22306 22306 22306 22306

e
b) What is Google Caffeine?

p
c) Write different programs using “for” and “foreach” statement.
o
a .r c
22306 22306 22306 22306 22306 22306 22306 22306 22306

p
d) How to write HTML code in PHP?

22306 22306
e) What
22306
r
is SQL Injection?

b22306 22306 22306

p e 22306 22306 22306

a
f) Differentiate between “<input type=’button’>” and “<input type=’submit’>”.

g) What is escaping in PHP?

rp
22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 22306
h) What is the purpose of $_PHP_SELF?
22306 22306 22306
i) What is the use of final keyword?
b 22306 22306 22306 22306

j) How will you generate random number using PHP?


22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 1|M
22306 c o d e - 722306
4083 22306 22306 22306 22306 ( S 22306
3)-462 22306

22306 22306 22306 22306 22306 22306 22306 22306 22306


22306 22306 22306 22306 22306 22306 22306 22306 22306

SECTION-B
22306 22306 22306 22306 22306 22306 22306 22306 22306

2. Write a program on sorting of an array by taking the user input from single textbox of
HTML (Comma Separated).
22306 22306 22306 22306 22306 22306 22306 22306 22306
3. Write a program to check the user credentials, whether they are correct are not.
If the credentials are correct then the user will be redirected to another page.
22306 22306
4. What is22306
the difference22306 22306
between session and cookie?22306
Explain with 22306
an example. 22306 22306

5. What is function overloading and overriding? Explain with an example.


22306 22306 22306 22306 22306 22306 22306 22306 22306
6. How web pages are formed using CSS?

7. What is SQL? How to update the contents from TABLE A to TABLE B?


22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 22306 22306 22306 22306

o m22306 22306 22306 22306

22306 22306 22306 22306 22306


.r c 22306 22306

m
22306 22306

p e o
a .r c
22306 22306 22306 22306 22306 22306 22306 22306 22306

r p e
22306 22306 22306

b 22306 22306

a
22306

p
22306 22306 22306

rp
22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 22306 22306 22306 22306 b 22306 22306 22306 22306

22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 22306 22306 22306 22306 22306 22306 22306 22306

22306 2|M
22306 c o d e - 722306
4083 22306 22306 22306 22306 ( S 22306
3)-462 22306

22306 22306 22306 22306 22306 22306 22306 22306 22306


Roll No. Total No. of Pages: 02
Total No. of Questions: 07

B.sc.(IT) (2015 & Onwards) (Sem. – 4)


PROGRAMMING IN PHP
M Code: 74083
Subject Code: BSIT-401
Paper ID: [74083]
Time: 3 Hrs. Max. Marks: 60

INSTRUCTIONS TO CANDIDATES:
1. SECTION-A is COMPULSORY consisting of TEN questions carrying TWO marks each.
2. SECTION-B contains SIX questions carrying TEN marks each and students have to
attempt any FOUR questions.

1. Explain the following:


SECTION A

o m
a) GET method
.r c m
e
b) Google Caffeine
c) WYSIWYG
p o
d) Array

p a .r c
e) Cookies
f) Outer join
b r p e
g) For loop
a
h) String
i) Function
j) Create Image b rp

M-74083 Page 1 of 2
SECTION B
2. Explain various data types in PHP.
3. What is a join? Explain its types.
4. What is the difference between function overloading and overriding? Explain.
5. How web pages are formed using CSS?
6. Explain various date and time functions in PHP.
7. What is RDBMS? How to create a connection between PHP and My SQL?

o m
.r c m
p e o
p a .r c
b r p e
a
b rp

M-74083 Page 2 of 2
Roll No. Total No. of Pages : 02
Total No. of Questions : 07
B.Sc.(IT) (2015 & Onwards) (Sem.–4)
PROGRAMMING IN PHP
Subject Code : BSIT-401
M.Code : 74083
Time : 3 Hrs. Max. Marks : 60

INSTRUCTIONS TO CANDIDATES :
1. SECTION-A is COMPULSORY consisting of TEN questions carrying T WO marks
each.
2. SECTION-B contains SIX questions carrying TEN marks each and students have
to attempt any FOUR questions.

SECTION-A

1) Answer briefly :

o m
.r c
a) What are the basic DML commands?

p e
b) PHP is server side language or client side language? Explain your answer.

m
a
c) Write the connectivity string in PHP with Mysql database.
o
r p .r c
d) Which operator is used to check the data types of the variables, whether they are same
or not?
b p e
e) Differentiate between session and cookie.

p a
r
f) How to retrieve a value from textbox in PHP on click event of button?
b
g) What is WYSIWYG?

h) Which server is used to compile PHP code?

i) Differentiate between $_GET and $_POST methods in PHP.

j) What are interfaces in PHP?

1|M - 7 4 0 8 3 (S3)-633
SECTION-B

2) Write a PHP script which takes the username, password and e-mail values from user and
checks whether the user has filled the textboxes or not. Also, check the e-mail field
whether it is incorrect format or not.

3) Write a function that interchange and prints the value of two integers A and B without
using any extra variable.

4) How a Browser communicate with Web Servers?

5) How to save the user's data in file? Also, write a program on it?

6) Write a program to update a value of database on user request.

7) What are FORMS? Explain different Form fields.

o m
.r c
p e m
a o
r p .r c
b p e
p a
b r

NOTE : Disclosure of Identity by writing Mobile No. or Making of passing request on any
page of Answer Sheet will lead to UMC against the Student.

2|M - 7 4 0 8 3 (S3)-633

You might also like