module 4
module 4
PHP is a server side scripting language. that is used to develop Static websites or Dynamic
websites or Web applications. PHP stands for Hypertext Pre-processor, that earlier stood for
Personal Home Pages.
PHP scripts can only be interpreted on a server that has PHP installed.
The client computers accessing the PHP scripts require a web browser only.
A PHP file contains PHP tags and ends with the extension ".php".
A scripting language is a language that interprets scripts at runtime. Scripts are usually
embedded into other software environments.
The purpose of the scripts is usually to enhance the performance or perform routine tasks for an
application.
Server side scripts are interpreted on the server while client side scripts are interpreted by the
client application.
PHP is a server side script that is interpreted on the server while JavaScript is an example of a
client side script that is interpreted by the client browser. Both PHP and JavaScript can be
embedded into HTML pages.
Has all the features needed to develop complete Mostly used for routine tasks
applications.
The code has to be compiled before it can be The code is usually executed without compiling
executed
Does not need to be embedded into other Is usually embedded into other software
languages environments.
PHP code may be embedded into HTML code, or it can be used in combination with various web
template systems, web content management system and web frameworks.
Php Syntax
A PHP file can also contain tags such as HTML and client side scripts such as JavaScript.
HTML is an added advantage when learning PHP Language. You can even learn PHP
without knowing HTML but it’s recommended you at least know the basics of HTML.
Database management systems DBMS for database powered applications.
For more advanced topics such as interactive applications and web services, you will
need JavaScript and XML.
The flowchart diagram shown below illustrates the basic architecture of a PHP web application
and how the server handles the requests.
Why use PHP?
You have obviously heard of a number of programming languages out there; you may be
wondering why we would want to use PHP as our poison for the web programming. Below are
some of the compelling reasons.
In terms of market share, there are over 20 million websites and application on the internet
developed using PHP scripting language.
The diagram below shows some of the popular sites that use PHP
PHP vs Asp.Net VS JSP VS CFML
ASP – Active Server Pages, JSP – Java Server Pages, CFML – Cold Fusion Markup language
The table below compares the various server side scripting languages with PHP
Learning curve short Longer than Longer than Longer than PHP
PHP PHP
File extension and Tags In order for the server to identify our PHP files and scripts, we
must save the file with the “.php” extension. Older PHP file extensions include
.phtml
.php3
.php4
.php5
.phps
PHP was designed to work with HTML, and as such, it can be embedded into the HTML code.
You can create PHP files without any html tags and that is called Pure PHP file .
The server interprets the PHP code and outputs the results as HTML code to the web browsers.
In order for the server to identify the PHP code from the HTML code, we must always enclose
the PHP code in PHP tags.
A PHP tag starts with the less than symbol followed by the question mark and then the words
“php”.
The PHP tags themselves are not case-sensitive, but it is strongly recommended that we use
lower case letter. The code below illustrates the above point.
<?php … ?>
We will be referring to the PHP lines of code as statements. PHP statements end with a semi
colon (;). If you only have one statement, you can omit the semi colon. If you have more than
one statement, then you must end each line with a semi colon. For the sake of consistency, it is
recommended that you always end your statement(s) with a semi colon. PHP scripts are
executed on the server. The output is returned in form of HTML.
The program shown below is a basic PHP application that outputs the words “Hello World!”
When viewed in a web browser.
<?php
echo "Hello world";
?>
Output:
Hello world
What is HTTP?
The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients
and servers.
HTTP works as a request-response protocol between a client and server.
A web browser may be the client, and an application on a computer that hosts a web site may be
the server.
A client (browser) submits an HTTP request to the server; then the server returns a response to
the client. The response contains status information about the request and may also contain the
requested content.
We have two HTTP request methods in PHP for handling the forms, where submitted form-data
from users can be collected using these methods. In order to send information to the webserver
from the browser client, we use GET and POST methods.
These methods encode using a scheme called URL encoding before the browser sends the
information. Non-alphanumeric characters are replaced with hexadecimal values, and Gaps are
removed and replaced with the + character. After encoding the information, it is sent to the
server.
Example:
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
7 <title>Document</title>
8 </head>
9 <body>
11 <label for="inputName">Name:</label>
14 </form>
15 </body>
16 </html>
Output –
Advantages of Using the GET Method
Since the data sent by the GET method are displayed in the URL, it is possible to
bookmark the page with specific query string values.
GET requests can be cached and GET requests remain in the browser history.
GET requests can be bookmarked.
Disadvantages of Using the GET Method
The GET method is not suitable for passing sensitive information such as the username and
password, because these are fully visible in the URL query string as well as potentially
stored in the client browser’s memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the
URL is limited. So, there is a limitation for the total data to be sent.
Now let’s move ahead and have a look at the POST method.
Example:
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
7 <title>Document</title>
8 </head>
9 <body>
11 <label for="inputName">Name:</label>
13 <label for="password">password:</label>
16 </form>
17 </body>
18 </html>
Output-
Advantages of using POST Method
It is more secure than GET because user-entered information is never visible in the URL
query string or in the server logs.
There is a much larger limit on the amount of data that can be passed and one can send text
data as well as binary data (uploading a file) using POST.
Disadvantages of using the POST Method
Since the data sent by the POST method is not visible in the URL, so it is not possible to
bookmark the page with specific query.
Now that you know what are GET and POST methods, let’s have a look at the comparison of
GET vs POST method.
PHP | Cookies
<?php
?>
Note: Only the name argument in the setcookie() function is mandatory.To skip an
argument,the argument can be replaced by an empty string(“”).
Checking Whether a Cookie Is Set Or Not: It is always advisable to check whether a
cookie is set or not before accessing its value.Therefore to check whether a cookie is set or
not, the PHP isset() function is used.
To check whether a cookie “Auction_Item” is set or not,the isset() function is executed as
follows:
<?php
if(isset($_COOKIE["Auction_Item"])){
echo "Auction Item is a " . $_COOKIE["Auction_Item"];
} else{
echo "No items for auction.";
}
?>
Output:
Auction Item is a Luxury Car.
Accessing Cookie Values: For accessing a cookie value, the PHP $_COOKIE superglobal
variable is used.It is an associative array that contains a record of all the cookies values sent
by the browser in the current request.The records are stored as a list where cookie name is
used as the key.
To access a cookie named “Auction_Item”,the following code can be executed:
<?php
?>
Output:
Auction Item is a Luxury Car.
Deleting Cookies: The setcookie() function can be used to delete a cookie.For deleting a
cookie, the setcookie() function is called by passing the cookie name and other arguments
or empty strings but however this time, the expiration date is required to be set in the past.
To delete a cookie named “Auction_Item”,the following code can be executed:
<?php
?>
Important Points
1. If the expiration time of the cookie is set to 0, or omitted, the cookie will expire at the end
of the session i.e. when the browser closes.
2. The same path, domain, and other arguments should be passed that were used to create the
cookie in order to ensure that the correct cookie is deleted.
PHP | Sessions
What is a session?
In general, session refers to a frame of communication between two medium. A PHP session is
used to store data on a server rather than the computer of the user. Session identifiers or SID is a
unique number which is used to identify every user in a session based environment. The SID is
used to link the user with his information on the server like posts, emails etc.
How are sessions better than cookies?
Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to easily
modify the content of the cookie.Addition of harmful data by the attackers in the cookie may
result in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user data each
time the user views a page.Every time the browser requests a URL to the server, all the cookie
data for that website is automatically sent to the server within the request.
Below are different steps involved in PHP sessions:
Starting a PHP Session: The first step is to start up a session. After a session is started,
session variables can be created to store information. The PHP session_start() function is
used to begin a new session.It als creates a new session ID for the user.
Below is the PHP code to start a new session:
<?php
session_start();
?>
Storing Session Data: Session data in key-value pairs using the $_SESSION[] superglobal
array.The stored data can be accessed during lifetime of a session.
Below is the PHP code to store a session with two session variables Rollnumber and Name:
<?php
session_start();
$_SESSION["Rollnumber"] = "11";
$_SESSION["Name"] = "Ajay";
?>
Accessing Session Data: Data stored in sessions can be easily accessed by firstly
calling session_start() and then by passing the corresponding key to
the $_SESSION associative array.
The PHP code to access a session data with two session variables Rollnumber and Name is
shown below:
<?php
session_start();
?>
Output:
The Name of the student is :Ajay
The Roll number of the student is :11
Destroying Certain Session Data: To delete only a certain session data,the unset feature
can be used with the corresponding session variable in the $_SESSION associative array.
The PHP code to unset only the “Rollnumber” session variable from the associative session
array:
<?php
session_start();
if(isset($_SESSION["Name"])){
unset($_SESSION["Rollnumber"]);
}
?>
Destroying Complete Session: The session_destroy() function is used to completely
destroy a session. The session_destroy() function does not require any argument.
<?php
session_start();
session_destroy();
?>
Important Points
1. The session IDs are randomly generated by the PHP engine .
2. The session data is stored on the server therefore it doesn’t have to be sent with every
browser request.
3. The session_start() function needs to be called at the beginning of the page, before any
output is generated by the script in the browser.
PHP | Strings
Strings can be seen as a stream of characters. For example, ‘G’ is a character and
‘GeeksforGeeks’ is a string. We have learned about basics of string data type in PHP in PHP |
Data types and Variables. In this article we will discuss about strings in details. Every thing
inside quotes , single (‘ ‘) and double (” “) in PHP is treated as a string.
Creating Strings
There are two ways of creating strings in PHP:
1. Single-quote strings: This type of strings does not processes special characters inside
quotes.
<?php
// single-quote strings
echo $site;
?>
Output:
Welcome to GeeksforGeeks
The above program compiles correctly. We have created a string ‘Welcome to
GeeksforGeeks’ and stored it in variable and printing it using echo statement.
Let us now look at the below program:
<?php
// single-quote strings
$site = 'GeeksforGeeks';
?>
Output:
Welcome to $site
In the above program the echo statement prints the variable name rather than printing the
contents of the variables. This is because, single-quotes strings in PHP does not processes
special characters. Hence, the string is unable to identify the ‘$’ sign as start of a variable
name.
2. Double-quote strings : Unlike single-quote strings, double-quote strings in PHP is capable
of processing special characters.
<?php
// double-quote strings
$site = "GeeksforGeeks";
?>
Output:
Welcome to GeeksforGeeks
Welcome to GeeksforGeeks
In the above program we can see that the double-quote strings is processing the special
characters according the their properties. The ‘\n’ character is not printed and is considered
as a new-line. Also instead of the variable name $site, “GeeksforGeeks” is printed.
PHP treats everything inside double quotes(” “) as Strings. In this article, we will learn about the
working of the various string functions and how to implement them along with some special
properties of strings. Unlike other data types like integers, doubles etc. Strings do not have any
fix limits or ranges. It can extend to any length as long as it is within the quotes.
It has been discussed earlier that string with single and double quotes are treated differently.
Strings within single quote ignores the special characters but double-quoted strings recognize the
special characters and treat them differently.
Example:
<?php
$name = "Krishna";
echo "The name of the geek is $name \n";
echo 'The name of the geek is $name';
?>
Output:
The name of the geek is Krishna
The name of the geek is $name
Some of the important and frequently used special characters that are used with double-quoted
strings are explained below:
The character beginning with a backslash(“\”) are treated as escape sequences and are
replaced with special characters. Here are few important escape sequences.
1. “\n” is replaced by a new line
2. “\t” is replaced by a tab space
3. “\$” is replaced by a dollar sign
4. “\r” is replaced by a carriage return
5. “\\” is replaced by a backslash
6. “\”” is replaced by a double quote
7. “\'” is replaced by a single quote
The string starting with a dollar sign(“$”) are treated as variables and are replaced with the
content of the variables.
Built-in String functions
Built-in functions in PHP are some existing library functions which can be used directly in our
programs making an appropriate call to them. Below are some important built-in string functions
that we use in our daily and regular programs:
1. strlen() function: This function is used to find the length of a string. This function accepts
the string as argument and return the length or number of characters in the string.
Example:
<?php
?>
Output:
20
2. strrev() function: This function is used to reverse a string. This function accepts a string as
argument and returns its reversed string.
Example:
<?php
?>
Output:
!skeeGrofskeeG olleH
3. str_replace() function: This function takes three strings as arguments. The third argument
is the original string and the first argument is replaced by the second one. In other words
we can say that it replaces all occurrences of the first argument in the original string by
second argument.
Example:
<?php
?>
Output:
Hello WorldforWorld!
Hello GeeksWorldGeeks!
In the first example, we can see that all occurrences of the word “Geeks” is replaced by
“World” in “Hello GeeksforGeeks!”.
4. strpos() function: This function takes two string arguments and if the second string is
present in the first one, it will return the starting position of the string otherwise returns
FALSE. Example:
<?php
?>
Output:
6
11
bool(false)
We can see in the above program, in the third example the string “Peek” is not present in
the first string, hence this function returns a boolean value false indicating that string is not
present.
5. trim() function: This function allows us to remove whitespaces or strings from both sides
of a string. Example:
<?php
?>
Output:
llo Worl
PHP | strcmp() Function
Comparing two strings is one of the most commonly used string operation in programming and
web development practices. The strcmp() is an inbuilt function in PHP and is used to compare
two strings. This function is case-sensitive which points that capital and small cases will be
treated differently, during comparison. This function compares two strings and tells us that
whether the first string is greater or smaller than the second string or equals to the second string.
Syntax:
strcmp($string1, $string2)
Parameters: This function accepts two parameters which are described below:
1. $string1 (mandatory): This parameter refers to the first string to be used in the comparison
2. $string2 (mandatory): This parameter refers to the second string to be used in the
comparison.
Return Values: The function returns a random integer value depending on the condition of
match, which is given by:
Returns 0 if the strings are equal.
Returns a negative value (<0), if $string2 is greater than $string1.
Returns a positive value (>0) if $string1 is greater than $string2.
In this code we will try to understand the working of strcmp() function:
<?php
?>
Output:
0
31
-31
PHP | strstr() Function
The strstr() function is a built-in function in PHP. It searches for the first occurrence of a string
inside another string and displays the portion of the latter starting from the first occurrence of the
former in the latter (before if specified). This function is case-sensitive.
Syntax :
strstr( $string, $search, $before )
Parameters : This function accepts three parameters as shown in the above syntax out of which
the first two parameters must be supplied and the third one is optional. All of these parameters
are described below:
$string : It is a mandatory parameter which specifies the string in which we want to
perform the search.
$search : It is a mandatory parameter which specifies the string to search for. If this
parameter is a number, it will search for the character matching the ASCII value of the
number
$before : It is an optional parameter. It specifies a boolean value whose default is false. If
set to true, it returns the part of the $string before the first occurrence of the $search
parameter.
Return Value : The function returns the rest of the string (from the matching point), or FALSE,
if the string to search for is not found.
Examples:
Output:
ks for Geeks!
Program 2: In this program we will display the portion of $string before the first occurrence of
$search.
<?php
echo stristr("Geeks for Geeks!", "k", true);
?>
Output:
Gee
Program 3: In this program we will pass an integer as $search.
<?php
$string = "Geeks";
echo stristr($string, 101); // 101 is ASCII value of lowercase e
?>
Output:
eeks
PHP | substr() function
The substr() is a built-in function in PHP that is used to extract a part of string.
Syntax:
substr(string_name, start_position, string_length_to_cut)
Parameters:
The substr() function allows 3 parameters or arguments out of which two are mandatory and one
is optional.
1. string_name: In this parameter, we pass the original string or the string that needs to cut or
modified. This is a mandatory parameter
2. start_position: This refers to the position of the original string from where the part needs
to be extracted. In this, we pass an integer. If the integer is positive it refers to the start of
the position in the string from the beginning. If the integer is negative then it refers to the
start of the position from the end of the string. This is also a mandatory parameter.
3. string_length_to_cut: This parameter is optional and of integer type. This refers to the
length of the part of the string that needs to be cut from the original string. If the integer is
positive, it refers to start from start_position and extract length from the beginning. If the
integer is negative then it refers to start from start_position and extract length from the end
of the string. If this parameter is not passed, then the substr() function will return the string
starting from start_position till the end of string.
Return Type:
Returns the extracted part of the string if successful otherwise FALSE or an empty string on
failure.
Below is a program to illustrate working of substr() in PHP:
<?php
// Driver Code
$str="GeeksforGeeks";
Substring($str);
?>
Output:
Geeks
forGeeks
Geeks
for
Convert Strings to Uppercase or Lowercase
PHP includes several functions that convert characters in strings to uppercase or lowercase. Pass
a string to these functions and they will apply upper or lower case to either:
The entire string (strtolower and strtoupper),
The first character of the string (lcfirst and ucfirst), or
The first character of each word in the string (ucwords).
We demonstrate and describe each of these functions below.
PHP - Arrays
Arrays in PHP is a type of data structure that allows us to store multiple elements of similar data
type under a single variable thereby saving us the effort of creating a different variable for every
data. The arrays are helpful to create a list of elements of similar types, which can be accessed
using their index or key. Suppose we want to store five names and print them accordingly. This
can be easily done by the use of five different string variables. But if instead of five, the number
rises to a hundred, then it would be really difficult for the user or developer to create so many
different variables. Here array comes into play and helps us to store every element within a
single variable and also allows easy access using an index or a key. An array is created using
an array() function in PHP.
There are basically three types of arrays in PHP:
Indexed or Numeric Arrays: An array with a numeric index where values are stored
linearly.
Associative Arrays: An array with a string index where instead of linear storage, each
value can be assigned a specific key.
Multidimensional Arrays: An array which contains single or multiple array within it and
can be accessed via multiple indices.
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
</body>
</html>
This will produce the following result −
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the
best choice. Instead, we could use the employees names as the keys in our associative array, and
the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would not
return any value.
Example
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);
</body>
</html>
This will produce the following result −
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects −
This example is an associative array, you can create numeric array in the same fashion.
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
</html>
This will produce the following result −
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
The array() function is an inbuilt function in PHP which is used to create an array. There are
three types of array in PHP:
Indexed array: The array which contains numeric index.
Syntax:
array( val1, val2, val3, ... )
Associative array: The array which contains name as keys.
Syntax:
array( key=>val, key=>val, key=>value, ... )
Multidimensional array: The array which contains one or more arrays.
Syntax:
array( array( val11, val12, ...)
array( val21, val22, ...)
... )
Parameters: This function accepts atmost two parameters as mentioned above and described
below:
<?php
// Create an array
$sub = array("DBMS", "Algorithm", "C++", "JAVA");
<?php
<?php
// Declare 2D array
$detail = array(array(1, 2, 3, 4),
array(5, 6, 7, 8));
<?php
?>
Output:
a =1
b =2
c =3
a*b*c =6
Program 2: Program to demonstrate the runtime error of list() function.
<?php
?>
Output:
PHP Notice: Undefined offset: 4 in
/home/619f1441636b952bbd400f1e9e8e3d0c.php on line 6
Program 3: Program to demonstrate assignment of particular index values in the array to
variables.
<?php
// PHP program to demonstrate assignment of
// variables.
?>
Output:
a=3
PHP | header() Function
The header() function is an inbuilt function in PHP which is used to send a raw HTTP header.
The HTTP functions are those functions which manipulate information sent to the client or
browser by the Web server, before any other output has been sent. The PHP header() function
send a HTTP header to a client or browser in raw form. Before HTML, XML, JSON or other
output has been sent to a browser or client, a raw data is sent with request (especially HTTP
Request) made by the server as header information. HTTP header provide required information
about the object sent in the message body more precisely about the request and response.
Syntax:
void header( $header, $replace = TRUE, $http_response_code )
Parameters: This function accepts three parameters as mentioned above and described below:
$header: This parameter hold the header string. There are two types of header calls. The
first header starts with string “HTTP/”, which is used to figure out the HTTP status code to
send. The second case of header is the “Location:”. It is mandatory parameter.
$replace: It is optional parameter. It denotes the header should replace previous or add a
second header. The default value is True (will replace). If $replace value is False then it
force multiple headers of the same type.
$http_response_code: It is an optional parameter. It forces the HTTP response code to the
specified value (PHP 4.3 and higher).
Return Values: This function doesn’t return any value.
Example 1:
<?php
// PHP program to describes header function
?>
Output:
This will change location of header, i.e. redirect to the URL
Example 2:
<?php
// PHP program to describes header function
<html>
<body>
<p>Hello World!</p>