PHP Module 4
PHP Module 4
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.
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>!
Your email address is <?php echo $_POST["email"]; ?>
</body>
</html>
Program Output:
Welcome Alex!
There are two ways the browser (client) can send information to the web server.
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:
<html>
<body>
Welcome <?php echo $_GET["name"]; ?>!
2
Page
</body>
</html>
The variable names and values will be visible in URL if HTML forms submitted by the
GET method.
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.
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)
Example:
<html>
<body>
Welcome <?php echo $_POST["name"]; ?>!
Your email address is <?php echo $_POST["email"]; ?>
</body>
</html>
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 $_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.
Syntax
Note: Only the name parameter is required. All other parameters are optional.
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).
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
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>
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
?>
<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.
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.
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.
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)
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.
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>
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>
PHP STRINGS
In this session, we will look at some commonly used functions to manipulate strings.
Example
<?php
echo strlen("Hello world!"); // outputs 12
?>
12
Page
13 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
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
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
13
The PHP str_replace() function replaces some characters with some other characters in a
string.
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
Syntax
Ucwords(string)
Example
<?php
echo ucwords(“welcome to the php world”);
?>
Output
Welcome To The Php World
Syntax
Strtoupper(string);
Example
<?php
14
into uppercase
15 Yuvakshetra Institute of Management Studies- PHP Notes (BSc.CS 2017-20 Batch)
?>
Output
WELCOME TO CLOUDWAYS
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)
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
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:
Output : world!
The array functions allow you to access and manipulate arrays.Simple and multi-dimensional
18
Installation
The array functions are part of the PHP core. There is no installation needed to use these
functions.
Function Description
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_intersect() Compare arrays, and returns the matches (compare values only)
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_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_udiff() Compare arrays, and returns the differences (compare values only,
20
each() Deprecated from PHP 7.2. Returns the current key and value pair
from an array
extract() Imports variables into the current symbol table from an array
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:
<?php
22
// perform multiplication of
?>
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
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:
Content-Type declaration
Page Redirection
Table of Contents
1. Redirecting Browser
24
3. Content Types
Redirecting Browser
<?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
?>
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