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

chp2 - Sem6 Bca

The document discusses various PHP web variables and superglobals that are used to collect form data submitted to a PHP script. Some of the key variables discussed include $_GET, $_POST, and $_REQUEST which contain HTTP GET, POST, and overall request variables respectively. $_SERVER contains information about headers, paths, and scripts. PHP automatically creates the $_REQUEST array containing elements of $_GET, $_POST, and $_COOKIE. Form data can be self-processed on the same PHP page using the PHP_SELF variable. File uploads involve moving uploaded files and validating sizes using the $_FILES array. Response headers can also be set using the header() function.

Uploaded by

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

chp2 - Sem6 Bca

The document discusses various PHP web variables and superglobals that are used to collect form data submitted to a PHP script. Some of the key variables discussed include $_GET, $_POST, and $_REQUEST which contain HTTP GET, POST, and overall request variables respectively. $_SERVER contains information about headers, paths, and scripts. PHP automatically creates the $_REQUEST array containing elements of $_GET, $_POST, and $_COOKIE. Form data can be self-processed on the same PHP page using the PHP_SELF variable. File uploads involve moving uploaded files and validating sizes using the $_FILES array. Response headers can also be set using the header() function.

Uploaded by

aishwarya saji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Web Variables:

• The PHP scripts must communicate with the outside world.


• The PHP scripts sends the data to the browser and collect
data from the same.
• From the outside world , the input generally comes from
HTML forms.
• These fields of the form are turned into variables.
• When the URL is specified in the browser then first task of the
browser is to break it into parts.
• The first part is the protocol HTTP.
• Next is the name of the web server to which the browser
makes a connection.
• The browser identifies the document it want from the web
server and it is done using HTTP protocol.
• The browser may provide some extra lines of information
called headers.
• The web server places these headers into environment
variable to conform with CGI(common gateway interface)
• The header is sent by the browser as user agent.
• The web server creates an environment variable called
HTTP_USER_AGENT.
• PHP creates a separate global variable for every form
parameter.
1. Superglobals — Superglobals are built-in variables that are
always available in all scopes
2. $GLOBALS — References all variables available in global scope
3. $_SERVER — Server and execution environment information
4. $_GET — HTTP GET variables
5. $_POST — HTTP POST variables
6. $_FILES — HTTP File Upload variables
7. $_REQUEST — HTTP Request variables
8. $_SESSION — Session variables
9. $_ENV — Environment variables
10. $_COOKIE — HTTP Cookies

• PHP automatically creates the $_REQUEST array which contains


the element of the $_GET,$_POST and $_COOKIE array all in
one array variable.
• PHP $GLOBAL:
• $GLOBAL is a PHP super global variable which is used to access global
variables from anywhere in the PHP scripts.
• PHP stores all global variables in an array called $GLOBAL.
• Example:
• <?PHP
• $a=80;
• $b=20;
• function addition()
• {
• $GLOBAL[‘c’]=$GLOBAL[‘a’]+$GLOBAL[‘b’];
• }
• addition()
• Echo $c;
• ?> OUTPUT:100
• c is a variable present within the $GLOBAL array, it is accessible from
outside the function
• $_SERVER is an array containing information such as headers,
paths, and script locations.
• The entries in this array are created by the web server.
• There is no guarantee that every web server will provide any
of these; servers may omit some, or provide others not listed
here
• <?php
echo $_SERVER['SERVER_NAME'];
?>
• Output: www.google.com
• <?php
echo $_SERVER[‘PHP_SELF'];
?>
• The filename of the currently executing script, relative to the
document root.
• http://example.com/foo/bar.php
• PHP $_REQUEST
• PHP $_REQUEST is used to collect data after submitting an HTML form.
• <html>
<body>

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


  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_REQUEST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>
• PHP $_POST
• PHP $_POST is widely used to collect form data after submitting an HTML form with method="post". $_POST is also
widely used to pass variables.
• <html>
<body>

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


  Name: <input type="text" name="fname">
  <input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // collect value of input field
    $name = $_POST['fname'];
    if (empty($name)) {
        echo "Name is empty";
    } else {
        echo $name;
    }
}
?>

</body>
</html>
• PHP $_GET
• PHP $_GET can also be used to collect form data after
submitting an HTML form with method="get".
• $_GET can also collect data sent in the URL.

• <html>
<body>

<a href="test_get.php?
subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>
• <html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>
Self Processing Forms
1. It is easy to process forms in PHP as the form parameters are
available in the $_GET and $_POST arrays.
2. there are two HTTP methods that a client can use to pass
form data to the server: GET and POST.
3. A GET request encodes the form parameters in the URL, in
what is called a query string:
4. A POST request passes the form parameters in the body of
the HTTP request, leaving the URL untouched.
5. The most visible difference between GET and POST is the
URL line.
6. Because all of a form's parameters are encoded in the URL
with a GET request, users can bookmark GET queries. They
cannot do this with POST requests.
• Self processing Pages:
• One PHP page can be used to both generate a form and
process it.

• Program to calculate temp(self1.php)


• PHP_SELF is a variable that returns the current script being
executed.
• This variable returns the name and path of the current file
(from the root folder).
• You can use this variable in the action field of the FORM
• A common use of PHP_SELF variable is in the action field of
the <form> tag.
• The action field of the FORM instructs where to submit the
form data when the user presses the “submit” button.
• <html>
• <head><title>Temperature Conversion</title></head>
• <body>

• <?php
• $fahr = $_GET['fahrenheit'];
• if (is_null($fahr)) {
• ?>
• <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="GET">
• Fahrenheit temperature:
• <input type="text" name="fahrenheit" /> <br />
• <input type="submit" name="Convert to Celsius!" />
• </form>

• <?php
• }
• else
• {
• $celsius = ($fahr - 32) * 5/9;
• printf("%.2fF is %.2fC", $fahr, $celsius);
• }
• ?>

• </body>
• </html>
• sticky forms
• Many web sites use a technique known as sticky forms, in
which the results of a query are accompanied by a search
form whose default values are those of the previous query.
• if you search Google (http://www.google.com) for
"Programming PHP", the top of the results page contains
another search box, which already contains "Programming
PHP".
• To refine your search to "Programming PHP from O'Reilly",
you can simply add the extra keywords.
• Example(wamp-www-monika-s.php)
• Multivalued Parameters
1. Multiple values can be passed to a form.
2. ‘select’ tag is used for multiple selections.
3. To ensure that PHP recognize the multiple values that the
browser passes to a form processing script.
4. You need to make the name of the field in the HTML form
end with [].
• Example
• Wamp-www-monika-mv.php
• Example: <select multiple name="subjects[]">
FILE UPLOADS
1. To handle file uploads use the $_FILES array.
2. Using the various authentication and file upload function,
you can control who is allowed to upload the files and what
to do with those files.
<form enctype=“multipart/form-data” action=“<?php echo
$_SERVER[‘PHP_SELF’];?>” method=“POST”>
<input type=hidden name=“MAX_FILE_SIZE” value=“10240”>
File name: <input type=“file” name=“toProcess”>
<input type=submit value=Upload>
</form>
• The biggest problem with the file uploads is the risk of getting
a file that is too large too process.
• PHP has two ways of preventing this: a hard limit and a soft
limit.
• first, ensure that PHP is configured to allow file uploads.
• In your "php.ini" file, search for the file_uploads directive, and
set it to On:
• The upload_max_filesize option in php.ini gives a hard limit on
the size of uploaded file(2MB).
• If your form submits parameters called MAX_FILE_SIZE before
any file field parameters.
• PHP uses the soft upper limit i.e.10kb(10240)
• Each element in $_FILES is itself an array, giving information
about the uploaded file:
• The keys are:
• name:
• The name of the file supplied by browser.
• type
• The MIME type of uploaded file by the client.
• Size
• The size of the uploaded file.
• tmp_name
• The name of the temporary file on the server that holds the
uploaded file.
• The correct way to test whether a file was successfully
uploaded is to use the function is_uploaded_file()

• Files are stored in the server’s default temporary file directory


which is specified in php.ini with the upload_tmp_dir option.

• To move the file , use the move_uploaded_file() function.


• Setting Response Headers

• The HTTP response that a server sends back to a client contains


headers that identify the type of content in the body of the response,
the server that sent the response, how many bytes are in the body,
when the response was sent, etc.

• PHP and Apache normally take care of the headers for you,
identifying the document as HTML, calculating the length of the
HTML page, and so on.

• Most web applications never need to set headers themselves.


However, if you want to send back something that's not HTML, set
the expiration time for a page, redirect the client's browser, or
generate a specific HTTP error, you'll need to use the header( )
function.
• The only catch to setting headers is that you must do so before
any of the body is generated.
• This means that all calls to header( ) (or setcookie( ), if you're
setting cookies) must happen at the very top of your file, even
before the <html> tag
• <?php
• header('Content-Type: text/plain');
• ?>
• Date: today
• From: fred
• To: barney
• Subject: hands off!
• Different Content Types

• The Content-Type header identifies the type of document


being returned. Ordinarily this is "text/html", indicating an
HTML document, but there are other useful document types.

• For example, "text/plain" forces the browser to treat the page


as plain text. This type is like an automatic "view source," and
it is useful when debugging.
• Redirections
• To send the browser to a new URL, known as a redirection ,
you set the Location header:

• <?php
• header('Location:http://www.example.com/elsewhere.html');
exit( );
• ?>
• If you provide a partial URL the redirection is handled
internally by the web server.
• Expiration
• A server can explicitly inform the browser, and any proxy
caches that might be between the server and browser, of a
specific date and time for the document to expire.
• Proxy and browser caches can hold the document until that
time or expire it earlier.
• Repeated reloads of a cached document do not contact the
server.
• However, an attempt to fetch an expired document does
contact the server.
• To set the expiration time of a document, use the Expires
header:
• header('Expires: Fri, 18 Jan 2002 05:30:00 GMT');
• To expire a document three hours from the time the page was
generated, use time( ) and gmstrftime( ) to generate the
expiration date string:
• Example:
• $now = time( );
• $then = gmstrftime("%a, %d %b %Y %H:%M:%S GMT",
$now + 60*60*3);
• header("Expires: $then");
• The gmstrftime() function formats a GMT/UTC time and/or
date according to locale settings.
• gmstrftime(format,timestamp);
• format Required. Specifies how to return the result:
• %a - abbreviated weekday name
• %A - full weekday name
• %b - abbreviated month name
• %B - full month name
• %c - preferred date and time representation
• %d - day of the month (01 to 31)
• %D - same as %m/%d/%y
• %y - year without a century (range 00 to 99)
• %Y - year including the century
• To indicate that a document "never" expires, use the time a
year from now:
• $now = time( );
• $then = gmstrftime("%a, %d %b %Y %H:%M:%S
GMT", $now + 365*86440);
• header("Expires: $then");

• To mark a document as already expired, use the current time


or a time in the past:
• $then = gmstrftime("%a, %d %b %Y %H:%M:%S
GMT");
• header("Expires: $then");
• Authentication
• HTTP authentication works through request headers and
response statuses.
• A browser can send a username and password (the
credentials ) in the request headers.
• If the credentials aren't sent or aren't satsifactory, the server
sends a "401 Unauthorized" response and identifies the realm
of authentication via the WWW-Authenticate header.
• This typically pops up an "Enter username and password
for ..." dialog box on the browser, and the page is then re-
requested with the updated credentials in the header.
• To handle authentication in PHP, check the username and
password (the PHP_AUTH_USER and PHP_AUTH_PW
elements of $_SERVER) and call header( ) to set the realm
and send a "401 Unauthorized" response:

• Example:

• header('WWW-Authenticate: Basic realm="Top Secret


Files"'); header("HTTP/1.0 401 Unauthorized");
• Maintaining State
• HTTP is a stateless protocol, which means that once a web
server completes a client's request for a web page, the
connection between the two goes away.
• In other words, there is no way for a server to recognize that a
sequence of requests all originate from the same client.

• State is useful, though. You can't build a shopping-cart


application, for example, if you can't keep track of a sequence
of requests from a single user.
• You need to know when a user puts a item in his cart, when he
adds items, when he removes them, and what's in the cart
when he decides to check out.
• To get around the Web's lack of state, programmers have come up
with many tricks to keep track of state information between
requests (also known as session tracking ).
• One such technique is to use hidden form fields to pass around
information. PHP treats hidden form fields just like normal form
fields, so the values are available in the $_GET and $_POST arrays.
• Using hidden form fields, you can pass around the entire contents
of a shopping cart.
• However, a more common technique is to assign each user a
unique identifier and pass the ID around using a single hidden form
field.
• While hidden form fields work in all browsers, they work only for a
sequence of dynamically generated forms, so they aren't as
generally useful as some other techniques.
• Another technique is URL rewriting, where every local URL
on which the user might click is dynamically modified to
include extra information.
• This extra information is often specified as a parameter in the
URL.
• For example, if you assign every user a unique ID, you might
include that ID in all URLs, as follows:
• http://www.example.com/catalog.php?userid=123
• If you make sure to dynamically modify all local links to
include a user ID, you can now keep track of individual users
in your application. URL rewriting works for all dynamically
generated documents,
• A third technique for maintaining state is to use cookies. A
cookie is a bit of information that the server can give to a
client.
• On every subsequent request the client will give that
information back to the server, thus identifying itself.
• Cookies are useful for retaining information through repeated
visits by a browser, but they're not without their own
problems.
• The main problem is that some browsers don't support
cookies, and even with browsers that do, the user can disable
cookies.
• So any application that uses cookies for state maintenance
needs to use another technique as a fallback mechanism.
• Cookies is a string that contains several fields.
• PHP transparently supports cookies.
• Cookies are mechanism for storing data in the browser and
tracking the user or identifying the user.
• Use the setcookie( ) function to send a cookie to the browser:
• Setcookie (name [, value [, expire [, path [, domain [,
secure ]]]]]);
• This function creates the cookie string from the given
arguments and creates a Cookie header with that string as its
value.
• Because cookies are sent as headers in the response,
setcookie( ) must be called before any of the body of the
document is sent.
• The parameters of setcookie( ) are:
• Name: A unique name for a particular cookie. You can have
multiple cookies with different names and attributes. The
name must not contain whitespace or semicolons.
• Value: The arbitrary string value attached to this cookie.
• The original Netscape specification limited the total size of a
cookie (including name, expiration date, and other
information) to 4 KB, so while there's no specific limit on the
size of a cookie value, it probably can't be much larger than
3.5 KB.`
• expire The expiration date for this cookie. If no expiration date
is specified, the browser saves the cookie in memory and not
on disk. When the browser exits, the cookie disappears.
• path The browser will return the cookie only for URLs below
this path.
• The default is the directory in which the current page resides.
For example, if /store/front/cart.php sets a cookie and doesn't
specify a path, the cookie will be sent back to the server for all
pages whose URL path starts with /store/front/.

• domain The browser will return the cookie only for URLs
within this domain. The default is the server hostname.

• secure The browser will transmit the cookie only over https
connections.
• When a browser sends a cookie back to the server, you can
access that cookie through the $_COOKIE array.

• The key is the cookie name, and the value is the cookie's value
field. For instance, the following code at the top of a page
keeps track of the number of times the page has been accessed
by this client:

• <?php $page_accesses = $_COOKIE['accesses'];


setcookie('accesses', ++$page_accesses); ?>

• When decoding cookies, any periods (.) in a cookie's name are


turned into underscores. For instance, a cookie named tip.top
is accessible as $_COOKIE['tip_top'].
• Sessions:
• A session is a way to store information (in variables) to be
used across multiple pages.
• 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)
• So; Session variables hold information about one single user,
and are available to all pages in one application.
• Every Session has a data store associated in it.
• You can register variables to be loaded from the data store
when each page stars and saved back to the store when the
page ends.
• A session is started with the session_start() function.
• Session variables are set with the PHP global variable:
$_SESSION.
• <?php
// Start the session
session_start();
?>

<html>
<body>

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

</body>
</html>
• <?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>
• Destroying a PHP Session
• A PHP session can be destroyed by session_destroy()
function.
• This function does not need any argument and a single call can
destroy all the session variables.
• If you want to destroy a single session variable then you can
use unset() function to unset a session variable.

• <?php unset($_SESSION[‘Favcolor']); ?>

• <?php session_destroy(); ?>

You might also like