0% found this document useful (0 votes)
12 views

PHP Module 4

web programming using PHP - Calicut University 5th sem BSc Computer science

Uploaded by

uzhunnanshinana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

PHP Module 4

web programming using PHP - Calicut University 5th sem BSc Computer science

Uploaded by

uzhunnanshinana
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.

CS 2017-20 Batch)

UNIT- IV
PASSING INFORMATION BETWEEN PAGES

$_GET and $_POST are PHP Form global variables in PHP which used to collect data from
HTML form

The example below contains an HTML form with two input fields, and a submit button:

Example:

<html>
<body>
<form action="registration.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>

When the user fills out and submits the form, then form data will be sent to PHP file:
called registration.php.

registration.php page has following code to print submitted data:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>!
Your email address is <?php echo $_POST["email"]; ?>
</body>
</html>

Program Output:

Welcome Alex!

Your email address is [email protected].


1
Page
2 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Form GET/POST method and PHP $_GET/$_POST

There are two ways the browser (client) can send information to the web server.

 The GET Method


 The POST Method

PHP $_GET Variable

In PHP, the $_GET variable is used to collect values from HTML forms using method get.
Information sent from an HTML form with the GET method is displayed in the browser's
address bar, and it has a limit on the amount of information to send.

Example:

<html>
<body>
<form action="registration.php" method="get">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>

When the user clicks on the "Submit button", the URL will be something like this:

registration.php looks like this:

<html>
<body>
Welcome <?php echo $_GET["name"]; ?>!
2
Page

Your email address is <?php echo $_GET["email"]; ?>


3 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

</body>
</html>

When to use method="get"?

 The variable names and values will be visible in URL if HTML forms submitted by the
GET method.

 The GET method is restricted to send up to 2048 characters only.

 When you submit sensitive information like passwords then should not use this method.

 GET method can't be used, to send binary data like images and Word documents.

 GET method data can be accessed using PHP QUERY_STRING environment variable.

 PHP $_GET associative array is used to access all the sent information by GET method.

PHP $_POST Variable

In PHP, the $_POST variable is used to collect values from HTML forms using method post.
Information sent from a form with the POST method is invisible and has no limits on the
amount of information to send.

Note: However, there is an 8 MB max size for the POST method, by default (can be changed
by setting the post_max_size in the php.ini file).

Example:

<html>
<body>
<form action="registration.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body> </html>
3

When the user clicks on the "Submit button", the URL will be something like this:
Page
4 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

registration.php looks like this:

Example:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>!
Your email address is <?php echo $_POST["email"]; ?>
</body>
</html>

When to use method="post"?

 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. By using Secure HTTP, you can make sure that your information is secure.

 PHP $_POST associative array is used to access all the sent information by POST method.

 Variables are not visible in the URL so users can't bookmark your page.

The PHP $_REQUEST Variable

The $_REQUEST variable contains the contents of $_GET, $_POST, and $_COOKIE.

Example:

<html>
<body>
Welcome <?php echo $_REQUEST["name"]; ?>!
Your email address is <?php echo $_REQUEST["Email"]; ?>
4
Page

</body>
5 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

</html>

PHP COOKIES

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax

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

Note: Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie

The following example creates a cookie named "user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer).We then retrieve the value of the cookie
"user" (using the global variable $_COOKIE). We also use the isset()function to find out if the
cookie is set:

Example

<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
5

<body>
Page
6 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Note: The setcookie() function must appear BEFORE the <html> tag.

Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Modify a Cookie Value

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example

<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
6
Page

echo "Cookie '" . $cookie_name . "' is set!<br>";


7 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

echo "Value is: " . $_COOKIE[$cookie_name];


}
?>
</body>
</html>

Delete a Cookie

To delete a cookie, use the setcookie() function with an expiration date in the past:

Example

<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are enabled. First,
try to create a test cookie with the setcookie() function, then count the $_COOKIE array
variable:

Example

<?php
7

setcookie("test_cookie", "test", time() + 3600, '/');


Page
8 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>

PHP SESSIONS

A session is a way to store information (in variables) to be used across multiple pages.Unlike
a cookie, the information is not stored on the users computer.

What is a PHP Session?

When you work with an application, you open it, do some changes, and then you close it. This
is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does
not know who you are or what you do, because the HTTP address doesn't maintain state.
Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color, etc). By default, session variables last until the user closes
the browser.So; Session variables hold information about one single user, and are available to
all pages in one application.

Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session


8
Page

A session is started with the session_start() function.


9 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:

Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>

Note: The session_start() function must be the very first thing in your document. Before any
HTML tags.

Get PHP Session Variable Values

Next, we create another page called "demo_session2.php". From this page, we will access the
session information we set on the first page ("demo_session1.php").Notice that session
variables are not passed individually to each new page, instead they are retrieved from the
session we open at the beginning of each page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION variable:
9
Page
10 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

Another way to show all the session variable values for a user session is to run the following
code:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>
</body>
10

</html>
Page
11 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

How does it work? How does it know it's me?

Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it
scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a
new session.

Modify a PHP Session Variable

To change a session variable, just overwrite it:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session,


use session_unset() and session_destroy():
11
Page
12 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

PHP STRINGS

PHP String Functions

In this session, we will look at some commonly used functions to manipulate strings.

strlen() - Return the Length of a String

The PHP strlen() function returns the length of a string.

Example

Return the length of the string "Hello world!":

<?php
echo strlen("Hello world!"); // outputs 12
?>
12
Page
13 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

str_word_count() - Count the Number of Words in a String

The PHP str_word_count() function counts the number of words in a string.

Example

Count the number of word in the string "Hello world!":

<?php
echo str_word_count("Hello world!"); // outputs 2
?>

strrev() - Reverse a String

The PHP strrev() function reverses a string.

Example

Reverse the string "Hello world!":

<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>

strpos() - Search For a Text Within a String

The PHP strpos() function searches for a specific text within a string. If a match is found, the
function returns the character position of the first match. If no match is found, it will return
FALSE.

Example

Search for the text "world" in the string "Hello world!":

<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
13

Tip: The first character position in a string is 0 (not 1).


Page
14 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

str_replace() - Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters in a
string.

Example

Replace the text "world" with "Dolly":

<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>

Converting lowercase into Title Case

Ucwords() is used to convert first alphabet of every word into uppercase.

Syntax
Ucwords(string)
Example
<?php
echo ucwords(“welcome to the php world”);

?>
Output
Welcome To The Php World

Converting a whole string into UPPERCASE

Strtoupper() is used to convert a whole string into uppercase.

Syntax
Strtoupper(string);
Example
<?php
14

echo strtoupper(“welcome to cloudways”);// It will convert all letters of string


Page

into uppercase
15 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

?>
Output

WELCOME TO CLOUDWAYS

Converting whole String to lowercase

Strtolower() is used to convert a string into lowercase.

Syntax

Strtolower(string)
Example

<?php
echo strtolower(“WELCOME TO CLOUDWAYS”);

?>
Output

welcome to cloudways

Repeating a String

PHP provides a built-in function for repeating a string a specific number of times.

Syntax

Str_repeat(string,repeat)
Example

<?php
echo str_repeat(“=”,13);
15

?>
Page
16 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Output

=============

Comparing Strings

You can compare two strings by using strcmp(). It returns output either greater than zero, less
than zero or equal to zero. If string 1 is greater than string 2 then it returns greater than zero.
If string 1 is less than string 2 then it returns less than zero. It returns zero, if the strings are
equal.

Syntax

Strcmp(string1,string2)
Example

<?php
echo strcmp(“Cloudways”,”CLOUDWAYS”);
echo “<br>”;
echo strcmp(“cloudways”,”cloudways”);//Both the strings are equal
echo “<br>”;
echo strcmp(“Cloudways”,”Hosting”);
echo “<br>”;
echo strcmp(“a”,”b”);//compares alphabetically
echo “<br>”;
echo strcmp(“abb baa”,”abb baa caa”);//compares both strings and returns the
result in terms of number of characters.
?>
Output

1
0
-1
-1

-4
16
Page
17 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Displaying part of String

Through substr() function you can display or extract a string from a particular position.

Syntax

substr(string,start,length)
Example

<?php
echo substr(“Welcome to Cloudways”,6).”<br>”;
echo substr(“Welcome to Cloudways”,0,10).”<br>”;

?>
Output

e to Cloudways
Welcome to

Removing white spaces from a String


Trim() is dedicated to remove white spaces and predefined characters from a both the sides of
a string.

Syntax

trim(string,charlist)
Example

<?php
$str = “Wordpess Hosting”;
echo $str . “<br>”;
echo trim(“$str”,”Wording”);

?>
Output

Wordpess Hosting
17

pess Host
Page
18 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

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:

Input : $string = "Hello world!", $search = "world"

Output : world!

Input : $string = "Geeks for Geeks!", $search = "k"

Output : ks for Geeks!

PHP ARRAY FUNCTIONS

PHP Array Introduction

The array functions allow you to access and manipulate arrays.Simple and multi-dimensional
18

arrays are supported.


Page
19 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

Installation

The array functions are part of the PHP core. There is no installation needed to use these
functions.

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

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

array_count_values() Counts all the values of an array

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_key_exists() Checks if the specified key exists in the array

array_keys() Returns all the keys of an array

array_map() Sends each value of an array to a user-made function, which returns


new values
19
Page
20 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

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

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

array_reverse() Returns an array in the reverse order

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

array_shift() Removes the first element from an array, and returns the value of
the 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

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

using a user-defined key comparison function)


Page
21 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

array_unique() Removes duplicate values from an array

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

array_values() Returns all the values 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

each() Deprecated from PHP 7.2. Returns the current key and value pair
from an 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

list() Assigns variables as if they were an array

next() Advance the internal array pointer of an array

pos() Alias of current()

prev() Rewinds the internal array pointer


21
Page
22 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

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

PHP | LIST() FUNCTION

The list() function is an inbuilt function in PHP which is used to assign array values to multiple
variables at a time. This function will only work on numerical arrays. When the array is
assigned to multiple values, then the first element in the array is assigned to the first variable,
second to the second variable and so on, till the number of variables. The number of variables
cannot exceed the length of the numerical array.

Syntax:
list($variable1, $variable2....)

Parameter: It accepts a list of variables separated by spaces. These variables are assigned
values. The first variable is mandatory.
Return Value: The function returns the assigned array to the multiple variables passed. It
does not assign a value to the $variableM if m>n, where n is the length of the array.
Below programs illustrate the list() function in PHP:

Program 1: Program to demonstrate the use of list() function.

<?php
22

// PHP program to demonstrate the use of list() function


Page
23 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

$array = array(1, 2, 3, 4);

// assign array values to variables

list($a, $b, $c) = $array;

/ print all assigned values

echo "a =", ($a), "\n";

echo " b =", ($b), "\n";

echo " c =", ($c), "\n";

// perform multiplication of

// those assigned numbers

echo "a*b*c =", ($a*$b*$c);

?>

Output:

a =1

b =2

c =3

a*b*c =6

FOREACH LOOP()

The foreach loop is mainly used for looping through the values of an array. It loops over the
array, and each value for the current array element is assigned to $value, and the array pointer
is advanced by one to go the next element in the array.

Syntax:

<?php
foreach (array as $value){
23

//code to be executed;
Page
24 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

}
?>

Example:

<?php
$salary[]=2000;
$salary[]=3000;
$salary[]=5000;
foreach($salary as $value){
echo "Salary: $value<br>";
}
?>

Program Output:

Salary: 2000
Salary: 3000
Salary: 5000

PHP | HEADER() FUNCTION

When you open a Web page in your browser, apart from the web page, you're also bringing
back something called an HTTP HEADER. It is some additional information, such as a type of
programme making the request, date requested, should it be displayed as an HTML document,
how long the document is, and a lot more besides.

PHP headers can perform certain things, some of them are listed below:

 Tell browser not to cache the pages.

 Content-Type declaration

 Page Redirection

Table of Contents
1. Redirecting Browser
24

2. Do not cache pages


Page
25 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

3. Content Types

Redirecting Browser

You can redirect your user to some other page.

<?php
header("Location: http://www.example.com/");
?>

The following command will redirect the browser window to the given location as soon as
the command is executed.Please note that Location starts with capital L, some browsers
might not redirect if small l is used.Even though you redirected the user successfully, yet this
is not the proper way to do it. The above command does not generate the 301 response which
means the target page will lose a hit count and SEO ranking. To avoid that, you have to add
an additional header.

<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com/");
?>

Furthermore, you can add some redirection interval by using the following code:

<?php
header("Refresh: 5; url=http://www.example.com"); //will redirect after 5 seconds
?>

Do not cache pages


25

You can prevent the browser to cache pages by using the following code:
Page
26 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)

<?php
//Date in the past, tells the browser that the cache has expired
header("Expires: Mon, 20 Feb 2005 20:12:03 GMT");
/* The following tell the browser that the last modification is right not so it must load the p
age again */ header("Last-Modified: ". gmdate("D, d M Y H:i:s"). "GMT");
//HTTP/1.0
header("Pragma: no-cache");
?>

The above code will let the browser load the page fresh from the server every time it is
called. The reason is simple; we tell the browser that the content just expired and it was just
last modified too. Furthermore, we also tell it Pragma: no-cache to make sure it gets a fresh
server copy each time.

Content Types

Other than HTML, you can also generate different types of data, e.g., you can parse an image,
zip, XML, JSON, etc. If you do that then, you need to tell to the browser that content type is
something else.

<?php
//Browser will deal page as PDF
header ( "Content-type: application/pdf" );
//myPDF.pdf will called
header ( "Content-Disposition: attachment; filename=myPDF.pdf' " );
?>
26
Page

You might also like