You are on page 1of 14

WEB PROGRAMMING USING PHP

MODULE 4
1. What is HTML form?

An HTML form is used to collect user input. The user input can then be sent to a server for
processing. An HTML form contains form elements.

Form elements are different types of input elements, like: text fields, checkboxes, radio buttons,
submit buttons, and more.

The HTML <form> tag is used to create an HTML form and it has following syntax −

<form action = "Script URL" method = "GET | POST">


form elements like input, textarea etc.
</form>
2. How to Retrieve HTML Form Data with PHP?

To set up a form for server processing and data retrieval, two important form attributes that
controls how the form data is processed whenever it is submitted must be specified. These two
form attributes are:

• Method Attributes
• Action Attributes

Action Attributes: specifies the PHP script file location for processing when it is submitted. If
no script file location is specified, the browser submits the form by using the current PHP script
file location.

Method Attributes: specifies what type of method the form will use to send the data. We have
two methods, the GET and POST. By default, if no method is specified, the GET method is
used.

The element's name attribute value is used by PHP as key to enable access to the data value of
the specified form field element when you submit the form.

3. What is the purpose of GET and POST Method?

PHP provides two methods through which a client (browser) can send information to the server.
These methods are GET and POST

Get and Post methods are the HTTP request methods used inside the <form> tag to send form
data to the server.

4. Explain GET Method

This method instructs the browser to send the encoded information (the name/value pairs)
through the URL parameter by appending it to the page request. The browser implements this
method by concatenating the question mark character (?) to the end of the page request.
When you submit a form through the GET method, PHP provides a super global variable,
called $_GET. PHP uses this $_GET variable to create an associative array with keys to access
all the sent information (form data). The keys are created using the element's name attribute
values.

5. Explain POST Method

The form POST method sends information via HTTP header. All information sent through this
method is invisible to anyone else since all the information is embedded within the body of the
HTTP request.

When you submit a form to a server through the POST method, PHP provides a super global
variable called $_POST. The $_POST variable is used by PHP to create an associative array with
an access key. PHP uses the form field element name attribute to create the key.

6. Differentiate between GET and POST Methods

GET Method

• The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? Character.
• The GET method is restricted to send upto 1024 characters only.
• Never use GET method if you have password or other sensitive information to be sent to
the server.
• GET can't be used to send binary data, like images or word documents, to the server.
• The data sent by GET method can be accessed using QUERY_STRING environment
variable.
• The PHP provides $_GET associative array to access all the sent information using GET
method

POST Method

• The POST method transfers information via HTTP headers.


• The POST method does not have any restriction on data size to be sent.
• The POST method can be used to send ASCII as well as binary data.
• The data sent by POST method goes through HTTP header so security depends on HTTP
protocol.
• The PHP provides $_POST associative array to access all the sent information using
POST method.
7. What is a function? How does User Defined Function is created in PHP?

A Function is nothing but a 'block of statements' which generally performs a specific task and
can be used repeatedly in our program. This 'block of statements' is also given a name so that
whenever we want to use it in our program/script, we can call it by its name.
Syntax:
<?php
function function_name()
{
// function code statements
}
?>

A function name can only contain alphabets, numbers and underscores. No other special
character is allowed.
The name should start with either an alphabet or an underscore. It should not start with a number.
The opening curly brace {after the function name marks the start of the function code, and the
closing curly brace } marks the end of function code
Example
<?php
function add($a, $b)
{
$sum = $a + $b;
return $sum;
}

▪ echo add(5, 10) ;


?>

8. What is session? Explain with example


PHP session is used to store and pass information from one page to another temporarily. A
session is a global variable stored on the server. Each session is assigned a unique id which is
used to retrieve stored values. You can store user information (e.g. username, items selected,
etc.) in the server side for later use using PHP session. Session variables are stored in the
$_SESSION array variable. Sessions have the capacity to store relatively large data.
PHP session_start() function is used to start the session.

<?php
session_start();
?>

You can store all your session data as key-value pairs in the $_SESSION[] superglobal array.
The stored data can be accessed during lifetime of a session.

<?php
$_SESSION["favcolor"]="green";
$_SESSION["favanimal"]="cat";
?>

PHP session_destroy() function is used to destroy all session variables completely.

9. What is a Cookie?

PHP cookie is a small piece of information which is stored at client browser. It is used to
recognize the user. Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such way, cookie can be
received at the server side.

10. How to create cookie in PHP

PHP setcookie() function is used to set cookie with HTTP response. Once cookie is set, you can
access it by $_COOKIE superglobal variable.

Syntax:

setcookie ( name, value, expire, path, domain, secure);

name - Specifies the name of the cookie.


value - Specifies the value of the cookie.
Expire - Specifies when the cookie expires.
Path - Specifies the server path of the cookie. If set to "/", the cookie will be available within the
entire domain.
Domain - Specifies the domain name of the cookie.
Secure - Specifies whether or not the cookie should only be transmitted over a secure
HTTPSconnection.

11. Differentiate between session and cookies in PHP

Cookies Sessions

Cookies are stored in browser as text file


Sessions are stored in server side.
format.

It is stored limit amount of data allowing


It is stored unlimited amount of data
4kb

It is not holding the multiple variable in It is holding the multiple variables in sessions.
cookies.

We can access the cookies values in easily. We cannot access the session values in easily.
So it is less secure. So it is more secure.

12. Explain about various string handling function in PHP

PHP has a vast selection of built-in string handling functions that allow you to easily manipulate
strings in almost any possible way. String functions are built-in language constructs and
functions that are designed to manipulate and display strings

• explode()
The explode function splits a string by a given delimiter and returns an array with all the
substrings between the delimiters

Syntax:

explode(delimiter, string)
delimiter - What character you want to split the string by
string - The original string
Example
<?php
$str="Toyota,BMW,Honda,Mercedes”;
$a=explode(“,”,$str);
pint_r($a);
?>
Output
Array
(
[0] => Toyota
[1] => BMW
[2] => Honda
[3] => Mercedes
)
• strlen() function returns the length of a string.
<?php
echo strlen("Hello world!");
?>
output
12
• str_word_count() function is used to count numbers of words in given string.
<?php
echo str_word_count("Hello world!");
?>
Output
2
• strrev() function is used to revers any string.
Example
<?php
echo strrev("Hello world!");
?>
output
!dlrow olleH

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

• str_replace() function is used to replaces some characters with some other characters in
a string.
Example
<?php
echo str_replace("world", "Glob", "Hello world!");
?>
Output
Hello Glob
• ucwords() function is used to convert first latter of every word into upper case.
<?php
$str="hellow world”;
$str=ucwords($str);
echo $str;
?>
Output
Hello World
• strtolower() function is used to convert uppercase latter into lowercase letter.
• strtoupper() function is used to convert lowercase latter into uppercase latter
• substr() function Returns a Part of a String
Syntax:
substr(string, start,length)
The first argument is the string itself, second argument is the starting index of the
substring to be extracted and the third argument is the length of the substring to be
extracted.
Example
<?php
echo substr(“computer”,3,3);
?>
output
mpu
• str_repeat()
Syntax:
str_repeat($str, $counter)
This function is used to repeat a string a given number of times. The first argument is the
string and the second argument is the number of times the string should be repeated.
Example
<?php
echo str_repeat(“Web”,5)
?>
Output
WebWebWebWebWeb
• strcmp()
Syntax
strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done alphabetically. If
the first string is greater than second string, the result will be greater than 0, if the first
string is equal to the second string, the result will be equal to 0 and if the second string is
greater than the first string, then the result will be less than 0
Example
<?php
$s1=”PIN”;
$s2=”PEN”;
echo strcmp($s1,$s2);
echo strcmp($s2,$s1);
echo strcmp($s1,$s1);
?>
Output
4
-4
0
The ASCII value of “I” is 73 and ASCII value of “E” is 69 so the difference is 4 ie 73-69=4

13. Which are the different types of arrays used in PHP? Explain

An array in PHP is a type of data structure that allows us to store multiple elements of similar
data type under a single variable. An array can hold any number of values. Each value in an array
is called an element. You access each element via its index.
An element can store any type of value, such as an integer, a string, or a Boolean. You can mix
types within an array — for example, the first element can contain an integer, the second can
contain a string, and so on.
There are basically three types of arrays in PHP:
1. Indexed or Numeric Arrays
2. Associative Arrays
3. Multidimensional Arrays
• Indexed or Numeric Arrays
These types of arrays can be used to store any type of elements, but an index is always a number.
By default, the index starts at zero, so the first element has an index of 0; the second has an index
of 1, and so on. These arrays can be created in two different ways.
First Method
Example
<?php
$fruits=array("Mango", "Orange", "Apple", "Banana");
?>
Second Method
<?php
$fruits[0]=”Mango”
$fruits[1]=”Orange”
$fruits[2]=”Apple”
$fruits[3]=”Banana”
?>
Looping over elements of an indexed array

PHP provides the foreach loop statement that allows you to iterate over elements of an array. To
loop over elements of an indexed array, you use the following syntax:

foreach ($array as $element) {


// process element here;
}
Example
<?php
$fruits=array(“Mango”,”Orange”,”Apple”,”Banana”);
foreach($fruits as $v)
{
echo “$v <br>”;
}
?>
Loop over an array using a for loop
<?php
$fruits=array(“Mango”,”Orange”,”Apple”,”Banana”);
for($i=0;$i<count($fruits); $i++)
{
echo $fruits[$i],”<br>”;
}
?>
• Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear storage, every value
can be assigned with a user-defined key of string type.
An associative array is in the form of key-value pair, where the key is the index of the array and
value is the element of the array. Here the key can be user-defined. It is similar to the numeric
array, but the keys and values which are stored in the form of a key-value pair.
First Method
$fruits=array(“M”=>”Mango”,”O”=>”Orange”,”A”=>”Apple”);
Second Method
$fruits[“M”]=”Mango”;
$fruits[“O”]=”Orange”
$fruits[“A”]=”Apple”

Loop Through an Associative Array


Using foreach loop
<?php
$fruits=array(“M”=>”Mango”,”O”=>”Orange”,”A”=>”Apple”);
foreach($fruits as $k => $v)
{
echo $v “<br>”;
}
?>
Using for loop
<?php
$fruits=array(“M”=>”Mango”,”O”=>”Orange”,”A”=>”Apple”);
$length = count($family);
$keys = array_keys($family);
for($i=0;$i<$length;$i++)
{
echo $fruits[$keys[$i]],”<br>”;
}
<?

• Multidimensional Arrays in PHP

A multidimensional array is an array with elements that are arrays themselves. The
multidimensional array is an array in which each element can also be an array and each element
in the sub-array can be an array or further contain array within itself and so on.
Syntax

$myArray = array(
array( value1, value2, value3 ),
array( value4, value5, value6 ),
array( value7, value8, value9 )
);

e.g
<?php
$food= array('fruits'=>array('Apple', 'Orange', 'Mango', 'Banana'),
'vegitable'=>array('Tomato','Carrot','Cabbage'));

foreach($food as $k =>$f)
{
echo "<b>$k </b><br>";
foreach($f as $v)
echo "$v <br>";
}

?>
Output
fruits
Apple
Orange
Mango
Banana
vegitable
Tomato
Carrot
Cabbage
14. Explain different Array function with example

• Count ()
You can use count function to find the size of an array. If the value of array is not set or having
an empty array, then count will return 0. And, if it is not an array, then count will return 1.

Example
<?php
A=array(10,20,30,40);
echo count(A);
?>
Output
4
• Sizeof ()
This function returns the size of the array or the number of data elements stored in the array. The
sizeof() function is an alias of the count() function.
Example
<?php
A=array(10,20,30,40);
echo sizeof(A);
?>
Output
4
• array_combine()- which creates an array using one array for keys and another for its
values:
e.g
<?php
$k = array('sky', 'grass', 'orange');
$v = array('blue', 'green', 'orange');
$a = array_combine($k, $v);
print_r($a);
?>
Output
Array
(
[sky] => blue
[grass] => green
[orange] => orange
)
• in_array()

The in_array() function is an inbuilt function in PHP. The in_array() function is used to check
whether a given value exists in an array or not. It returns TRUE if the given value is found in the
given array, and FALSE otherwise.
Example
<?php
$a=(20,30,40,50)
if(in_array(30,$a))
{
echo “Found”;
}
else
{
echo “Not Found “;
}
Output
Found
• array_search()

This inbuilt function of PHP is used to search for a particular value in an array, and if the value is
found then it returns its corresponding key. If there is more than one value then the key of first
matching value will be returned.

Example

<?php
$a=array(23,45,67,89,20);
echo array_search(89,$a);
?>
Output
3
• array_count_values()

The array_count_values() This function returns an associative array with key-value pairs in
which keys are the elements of the array passed as parameter and values are the frequency of
these elements in an array.

<?php
$a = array("orange", "mango", "banana", "orange", "banana" );
$b = array_count_values($a)
print_r($b);
?>
Output

Array
(
[orange] => 2
[mango] => 1
[banana] => 2
)
• array_fill() – This function is used to fill an array with values.
<?php
$a=array_fill(0,4,"blue");
print_r($a);
?>

output

Array
(
[0] => blue
[1] => blue
[2] => blue
[3] => blue

• array_sum()

This function returns the sum of all the values in an array. It takes an array parameter and returns
the sum of all the values in it.

Example
<?php
$a = array(12, 24, 36, 48);
print_r(array_sum($a));
?>
OUTPUT
120
• array_reverse()
This function is used to reverse the order of the elements in an array.
Example
<?php
$num= array(100,200,300,400,500);
$y = array_reverse($num);
print_r($y);
?>
OUTPUT
Array
(
[0] => 500
[1] => 400
[2] => 300
[3] => 200
[4] => 100
)
Sorting an array
• sort() – sorts arrays in ascending order
• rsort() – sorts arrays in descending order
Example
<?php
$num = array(40, 61, 2, 22, 13);
sort($num);
rsort($num);
?>
15. What is list() in PHP

list() is used to assign the array values to multiple variables at a time. It works only on the
numeric or indexed arrays. The first element in the given array is assigned to the first variable
passed and the second element to the second variable and so on, till the number of variables
passed in parameter. It accepts a list of variables as parameter separated by comma.

Example

<?php
$f=array(“Mango”,”Apple”,”Grapes”);
list($a,$b,$c)=$f;
echo “$a <br>”;
echo “$b <br>”;
echo “$c <br>”;
?>
Output
Mango
Apple
Orange

You might also like