You are on page 1of 25

Web Technologies

1 a) HTTP Request: 5M
It's a stateless request-response based communication protocol. It's used to send and receive
data on the Web i.e., over the Internet. This protocol uses reliable TCP connections either for the
transfer of data to and from clients which are Web Browsers in this case. HTTP is a stateless
protocol means the HTTP Server doesn't maintain the contextual information about the clients
communicating with it and hence we need to maintain sessions in case we need that feature for our
Web-applications.

An HTTP client sends an HTTP request to a server in the form of a request message which
includes following format:

A Request-line
Zero or more header (General|Request|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the
header fields
Optionally a message-body

Request-Line:
The Request-Line begins with a method token, followed by the Request-URI and the protocol
version, and ending with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF.

Request Method:
The request method indicates the method to be performed on the resource identified by the given
Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The
following table lists all the supported methods in HTTP/1.1.

GET
The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.

HEAD
Same as GET, but it transfers the status line and the header section only.

POST
A POST request is used to send data to the server, for example, customer information, file
upload, etc. using HTML forms.

PUT
Replaces all the current representations of the target resource with the uploaded content.

DELETE
Removes all the current representations of the target resource given by URI.

CONNECT
Establishes a tunnel to the server identified by a given URI.

OPTIONS
Describe the communication options for the target resource.

TRACE
Performs a message loop back test along with the path to the target resource.

Request-URI:
The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply
the request. Following are the most commonly used forms to specify an URI:
Request-URI = "*" | absoluteURI | abs_path | authority

Request Header Fields:


The request-header fields allow the client to pass additional information about the request, and
about the client itself, to the server. These fields act as request modifiers.Here is a list of some
important Request-header fields that can be used based on the requirement:

Accept-Charset
Accept-Encoding
Accept-Language
Authorization
Expect
From
Host
If-Match

1 b) HTTP Response: 4M
After receiving and interpreting a request message, a server responds with an HTTP
response message:

A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the
header fields
Optionally a message-body

Message Status-Line
A Status-Line consists of the protocol version followed by a numeric status code and its associated
textual phrase. The elements are separated by space SP characters.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

HTTP Version
A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1

Status Code
The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class
of response and the last two digits do not have any categorization role. There are 5 values for the
first digit:

1xx: Informational
It means the request was received and the process is continuing.

2xx: Success
It means the action was successfully received, understood, and accepted.

3xx: Redirection
It means further action must be taken in order to complete the request.

4xx: Client Error


It means the request contains incorrect syntax or cannot be fulfilled.

5xx: Server Error


It means the server failed to fulfill an apparently valid request.

Response Header Fields


The response-header fields allow the server to pass additional information about the response
which cannot be placed in the Status- Line. These header fields give information about the server
and about further access to the resource identified by the Request-URI.

Accept-Ranges
Age
ETag
Location
Proxy-Authenticate
Retry-After
Server
Vary
WWW-Authenticate

1 c) WAMP: 21/2 M
Stands for "Windows, Apache, MySQL, and PHP." WAMP is a variation of LAMP for
Windows systems and is often installed as a software bundle (Apache, MySQL, and PHP). It is
often used for web development and internal testing, but may also be used to serve live websites.

The most important part of the WAMP package is Apache (or "Apache HTTP Server")
which is used run the web server within Windows. By running a local Apache web server on a
Windows machine, a web developer can test webpages in a web browser without publishing them
live on the Internet.

WAMP also includes MySQL and PHP, which are two of the most common technologies
used for creating dynamic websites. MySQL is a high-speed database, while PHP is a scripting
language that can be used to access data from the database. By installing these two components
locally, a developer can build and test a dynamic website before publishing it to a public web
server.

While Apache, MySQL, and PHP are open source components that can be installed
individually, they are usually installed together. One popular package is called "WampServer,"
which provides a user-friendly way to install and configure the "AMP" components on Windows.

NOTE: The "P" in WAMP can also stand for either Perl or Python, which are other scripting
languages. The Mac version of LAMP is known as MAMP.

IIS: 21/2 M
Stands for "Internet Information Services." IIS is a web server software package designed
for Windows Server. It is used for hosting websites and other content on the Web.

Microsofts Internet Information Services provides a graphical user interface (GUI) for
managing websites and the associated users. It provides a visual means of creating, configuring,
and publishing sites on the web. The IIS Manager tool allows web administrators to modify website
options, such as default pages, error pages, logging settings, security settings, and performance
optimizations.

IIS can serve both standard HTML webpages and dynamic webpages, such as ASP.NET
applications and PHP pages. When a visitor accesses a page on a static website, IIS simply sends
the HTML and associated images to the users browser. When a page on a dynamic website is
accessed, IIS runs any applications and processes any scripts contained in the page, then sends the
resulting data to the users browser.

While IIS includes all the features necessary to host a website, it also supports extensions
(or modules) that add extra functionality to the server. For example, the WinCache Extension
enables PHP scripts to run faster by caching PHP processes. The URL Rewrite module allows
webmasters to publish pages with friendly URLs that are easier for visitors to type and remember.
A streaming extension can be installed to provide streaming media to website visitors.

IIS is a popular option for commercial websites, since it offers many advanced features and
is supported by Microsoft. However, it also requires a commercial license and the pricing increases
depending on the number of users. Therefore, Apache HTTP Server, which is open source and free
for unlimited users, remains the most popular web server software.

2 a) Structure of a PHP page: 7M


PHP is a server-side scripting language designed primarily for web development but also
used as a general-purpose programming language. Originally created by Rasmus Lerdorf in 1994,
the PHP reference implementation is now produced by The PHP Development Team. PHP
originally stood for Personal Home Page, but it now stands for the recursive acronym PHP:
Hypertext Preprocessor.
The following "Hello, World!" program is written in PHP code embedded in an HTML document:
<!DOCTYPE html>
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
However, as no requirement exists for PHP code to be embedded in HTML, the simplest version
of Hello, World! may be written like this, with the closing tag omitted as preferred in files
containing pure PHP code.
<?="Hello, world";
The PHP interpreter only executes PHP code within its delimiters. Anything outside its delimiters
is not processed by PHP, although non-PHP text is still subject to control structures described in
PHP code. The most common delimiters are <?php to open and ?> to close PHP sections. The
shortened form <? also exists. This short delimiter makes script files less portable, since support
for them can be disabled in the local PHP configuration and it is therefore discouraged. However,
there is no recommendation against the use of the echo short tag <?=. Prior to PHP 5.4.0, this short
syntax for echo() only works with the short_open_tag configuration setting enabled. The purpose
of all these delimiters is to separate PHP code from non-PHP content, such as JavaScript code or
HTML markup.

The first form of delimiters, <?php and ?>, in XHTML and other XML documents, creates
correctly formed XML processing instructions. This means that the resulting mixture of PHP code
and other markup in the server-side file is itself well-formed XML.

Variables are prefixed with a dollar symbol, and a type does not need to be specified in advance.
PHP 5 introduced type hinting that allows functions to force their parameters to be objects of a
specific class, arrays, interfaces or callback functions.

Unlike function and class names, variable names are case sensitive. Both double-quoted ("") and
heredoc strings provide the ability to interpolate a variable's value into the string. PHP treats
newlines as whitespace in the manner of a free-form language, and statements are terminated by a
semicolon. PHP has three types of comment syntax: /* */ marks block and inline comments; // as
well as # are used for one-line comments. The echo statement is one of several facilities PHP
provides to output text, e.g., to a web browser.

2 b) Problems with Servlets: 3M


Server-side Security Issues
Interception of Session State Information
Forgery of Session State Information
Session Timeout
Buffer Overflow
Data Validation
Page Sequencing
Information Reporting
Browser Residue
User Authentication
Logging of Sensitive Information

Problems with JSP: 4M


Because JSP pages are translated, and then compiled into Java servlets, errors that creep in your
pages are rarely seen as errors arising from the coding of JSP pages. Instead, such errors are seen
as either Java servlet errors or HTML errors. You could look at this as an example of a perceived
strength of JSP that of not needing to compile them as opposed to a weakness. For example, a JSP
developer coding a scriptlet where a JSP declaration is called for would have to interpret a Java
compile error.

The JSP developer would need access to the generated source to properly diagnose the error. Of
course, generated code is rarely a thing of beauty, and often, not easily understood. The JSP
developer needs to know Java. Again, one developer s asset is another s liability. Whereas Java is
certainly more full-featured and flexible than other page scripting languages, no one can argue that
the learning curve for Java is far steeper than other scripting languages. If you already know Java
(you do, right?), this is not an issue.

However, if a corporation is short on Java mavens but wants to use a dynamic Web technology,
JSP may not be the route to go. (Another way to look at the need to know Java is that if you had
to train a rookie in using either JSP or, say, ASP, and you had two days to produce half a dozen
pages, which technology would you opt for?)
JSP pages require about double the disk space to hold the page.

Because JSP pages are translated into class files, the server has to store the resultant class files
with the JSP pages.

JSP pages must be compiled on the server when first accessed. This initial compilation produces
a noticeable delay when accessing the JSP page for the first time.

The developer may compile JSP pages and place them on the server in compiled form (as one or
more class files) to speed up the initial page access. The JSP developer may need to bring down
the server to make the changed classes corresponding to the changed JSP page.

3 a) Call by Value: 31/2 M


PHP allows you to call function by value and reference both. In case of PHP call by value, actual
value is not modified if it is modified inside the function.
Let's understand the concept of call by value by the help of examples.

Example
In this example, variable $str is passed to the adder function where it is concatenated with 'Call By
Value' string. But, printing $str variable results 'Hello' only. It is because changes are done in the
local variable $str2 only. It doesn't reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>

Output:
Hello

Call by Reference: 31/2 M


In case of PHP call by reference, actual value is modified if it is modified inside the function. In
such case, you need to use & (ampersand) symbol with formal arguments. The & represents
reference of the variable.
Let's understand the concept of call by reference by the help of examples.

Example
In this example, variable $str is passed to the adder function where it is concatenated with 'Call By
Reference' string. Here, printing $str variable results 'This is Call By Reference'. It is because
changes are done in the actual variable $str.
<?php
function adder(&$str2)
{
$str2 .= 'Call By Reference';
}
$str = 'This is ';
adder($str);
echo $str;
?>

Output:
This is Call By Reference
3 b) Override the scope with global array: 7M
At some point in PHP programming you will want to read a global variable inside a function - It
can much guarantee that, because it is a very popular thing to do. Luckily, it is made easy for you
by PHP through the $GLOBALS superglobal array, which allows you to access global variables
even from within functions. When it comes to the $GLOBALS array it is quite simple: all variables
declared in the global scope are in the $GLOBALS array, which you can access anywhere in the
script.
To demonstrate this in action, consider the following script:
<?php
function foo() {
$GLOBALS['bar'] = "wombat";
}

$bar = "baz";
foo();
print $bar;
?>

What do you think that will output this time? If you guessed "wombat", you would be correct - the
foo() function literally alters a variable outside of its scope, so that even after it returns control
back to the main script, its effect is still felt. You can of course read variables in the same way,
like this:
$localbar = $GLOBALS['bar'];

However, that is quite hard on the eyes. PHP allows you to use a special keyword, GLOBAL, to
allow a variable to be accessed locally. For example:
function myfunc() {
GLOBAL $foo, $bar, $baz;
++$baz;
}

That would allow a function to read the global variables $foo, $bar, and $baz. The ++$baz line
will increment $baz by 1, and this will be reflected in the global scope also.
4 a) Process of parsing a configuration file: 7M
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's
functionality. The php.ini file is read each time PHP is initialized.in other words, whenever httpd
is restarted for the module version or with each script execution for the CGI version. If your change
isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to
check the path to php.ini.

The configuration file is well commented and thorough. Keys are case sensitive, keyword values
are not; whitespace, and lines beginning with semicolons are ignored. Booleans can be represented
by 1/0, Yes/No, On/Off, or True/False. The default values in php.ini-dist will result in a reasonable
PHP installation that can be tweaked later.
Here we are explaining the important settings in php.ini which you may need for your PHP Parser.

short_open_tag = Off
Short open tags look like this: <? ?>. This option must be set to Off if you want to use XML
functions.

safe_mode = Off
If this is set to On, you probably compiled PHP with the --enable-safe-mode flag. Safe mode is
most relevant to CGI use. See the explanation in the section "CGI compile-time options". earlier
in this chapter.

safe_mode_exec_dir = [DIR]
This option is relevant only if safe mode is on; it can also be set with the --with-exec-dir flag during
the Unix build process. PHP in safe mode only executes external binaries out of this directory. The
default is /usr/local/bin. This has nothing to do with serving up a normal PHP/HTML Web page.

safe_mode_allowed_env_vars = [PHP_]
This option sets which environment variables users can change in safe mode. The default is only
those variables prepended with "PHP_". If this directive is empty, most variables are alterable.

safe_mode_protected_env_vars = [LD_LIBRARY_PATH]
This option sets which environment variables users can't change in safe mode, even if
safe_mode_allowed_env_vars is set permissively

disable_functions = [function1, function2...]


A welcome addition to PHP4 configuration and one perpetuated in PHP5 is the ability to disable
selected functions for security reasons. Previously, this necessitated hand-editing the C code from
which PHP was made. Filesystem, system, and network functions should probably be the first to
go because allowing the capability to write files and alter the system over HTTP is never such a
safe idea.

max_execution_time = 30
The function set_time_limit() won.t work in safe mode, so this is the main way to make a script
time out in safe mode. In Windows, you have to abort based on maximum memory consumed
rather than time. You can also use the Apache timeout setting to timeout if you use Apache, but
that will apply to non-PHP files on the site too.

error_reporting = E_ALL & ~E_NOTICE


The default value is E_ALL & ~E_NOTICE, all errors except notices. Development servers should
be set to at least the default; only production servers should even consider a lesser value

error_prepend_string = [""]
With its bookend, error_append_string, this setting allows you to make error messages a different
color than other text, or what have you.

warn_plus_overloading = Off
This setting issues a warning if the + operator is used with strings, as in a form value.

variables_order = EGPCS
This configuration setting supersedes gpc_order. Both are now deprecated along with
register_globals. It sets the order of the different variables: Environment, GET, POST, COOKIE,
and SERVER (aka Built-in).You can change this order around. Variables will be overwritten
successively in left-to-right order, with the rightmost one winning the hand every time. This means
if you left the default setting and happened to use the same name for an environment variable, a
POST variable, and a COOKIE variable, the COOKIE variable would own that name at the end
of the process. In real life, this doesn't happen much.

register_globals = Off
This setting allows you to decide whether you wish to register EGPCS variables as global. This is
now deprecated, and as of PHP4.2, this flag is set to Off by default. Use superglobal arrays instead.
All the major code listings in this book use superglobal arrays.

gpc_order = GPC
This setting has been GPC Deprecated.

magic_quotes_gpc = On
This setting escapes quotes in incoming GET/POST/COOKIE data. If you use a lot of forms which
possibly submit to themselves or other forms and display form values, you may need to set this
directive to On or prepare to use addslashes() on string-type data.

magic_quotes_runtime = Off
This setting escapes quotes in incoming database and text strings. Remember that SQL adds
slashes to single quotes and apostrophes when storing strings and does not strip them off when
returning them. If this setting is Off, you will need to use stripslashes() when outputting any type
of string data from a SQL database. If magic_quotes_sybase is set to On, this must be Off.

magic_quotes_sybase = Off
This setting escapes single quotes in incoming database and text strings with Sybase-style single
quotes rather than backslashes. If magic_quotes_runtime is set to On, this must be Off.

auto-prepend-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the beginning of every PHP file.
Include path restrictions do apply.

auto-append-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the end of every PHP file.unless
you escape by using the exit() function. Include path restrictions do apply.

include_path = [DIR]
If you set this value, you will only be allowed to include or require files from these directories.
The include directory is generally under your document root; this is mandatory if you.re running
in safe mode. Set this to . in order to include files from the same directory your script is in. Multiple
directories are separated by colons: .:/usr/local/apache/htdocs:/usr/local/lib.

doc_root = [DIR]
If you.re using Apache, you.ve already set a document root for this server or virtual host in
httpd.conf. Set this value here if you.re using safe mode or if you want to enable PHP only on a
portion of your site (for example, only in one subdirectory of your Web root).

file_uploads = [on/off]
Turn on this flag if you will upload files using PHP script.

upload_tmp_dir = [DIR]
Do not uncomment this line unless you understand the implications of HTTP uploads!
session.save-handler = files
Except in rare circumstances, you will not want to change this setting. So don't touch it.

ignore_user_abort = [On/Off]
This setting controls what happens if a site visitor clicks the browser.s Stop button. The default is
On, which means that the script continues to run to completion or timeout. If the setting is changed
to Off, the script will abort. This setting only works in module mode, not CGI.

mysql.default_host = hostname
The default server host to use when connecting to the database server if no other host is specified.

mysql.default_user = username
The default user name to use when connecting to the database server if no other name is specified.

mysql.default_password = password
The default password to use when connecting to the database server if no other password is
specified.

4 b) Program to concatenate two files: 7M


<?php
$lines = file('Country.txt');
$newf = array();
foreach ($lines as $line)
$newf[] = substr($line, 2);
file_put_contents('country2.txt', implode("\n", $newf));
$lines2 = file('countryenglish.txt');
$newf2 = array();
foreach ($lines2 as $line)
$newf2[] = substr($line, 3);
file_put_contents('countryenglish2.txt', implode("\n", $newf2));
?>

5 a) Advantages of Cookies: 31/2 M


A cookie is a small piece of text file stored on user's computer in the form of name-value
pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like
username etc. If any web application using cookies, Server send cookies and client browser will
store it. The browser then returns the cookie to the server at the next time the page is requested.
The most common example of using a cookie is to store User information, User preferences,
Password Remember Option etc.

Here are some of the advantages of using cookies to store session state.
Cookies are simple to use and implement.
Occupies less memory, do not require any server resources and are stored on the user's
computer so no extra burden on server.
We can configure cookies to expire when the browser session ends (session cookies) or
they can exist for a specified length of time on the clients computer (persistent cookies).
Cookies persist a much longer period of time than Session state.

Disadvantages of Cookies: 31/2 M


Cookies are not secure as they are stored in clear text they may pose a possible security
risk as anyone can open and tamper with cookies. You can manually encrypt and decrypt
cookies, but it requires extra coding and can affect application performance because of the
time that is required for encryption and decryption
Several limitations exist on the size of the cookie text(4kb in general), number of
cookies(20 per site in general), etc.
User has the option of disabling cookies on his computer from browsers setting.
Cookies will not work if the security level is set to high in the browser.
Users can delete a cookies.
Users browser can refuse cookies, so your code has to anticipate that possibility.
Complex type of data not allowed (e.g. dataset etc). It allows only plain text (i.e. cookie
allows only string content).

5 b) (i) Setting Cookies: 3M


PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has to be called
separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments

Name This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value This sets the value of the named variable and is the content that you actually want to store.

Expiry This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this
time cookie will become inaccessible. If this parameter is not set then cookie will automatically
expire when the Web Browser is closed.
Path This specifies the directories for which the cookie is valid. A single forward slash character
permits the cookie to be valid for all directories.

Domain This can be used to specify the domain name in very large domains and must contain
at least two periods to be valid. All cookies are only valid for the host and domain which created
them.

Security This can be set to 1 to specify that the cookie should only be sent by secure transmission
using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

5 b) (ii) Reading Cookies: 2M


Use $_COOKIE to retrieve a cookie with PHP. Once the cookies have been set, they can be
accessed on the next page load.
$cookie_name = 'pontikis_net_php_cookie';
if(!isset($_COOKIE[$cookie_name])) {
print 'Cookie with name "' . $cookie_name . '" does not exist...';
} else {
print 'Cookie with name "' . $cookie_name . '" value is: ' . $_COOKIE[$cookie_name];
}

5 b) (iii) Deleting Cookies: 2M


Officially, to delete a cookie you should call setcookie() with the name argument only but this
does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

6 a) Different arguments of super global $_FILES: 7M


$_FILES is a super global array variable used to get information of the upload files to the server.
We can check whether the file uploaded has been successfully uploaded or not. The details of the
file can also be retrieved using $_FILES variable. Let us learn it with an example.

In the example we will upload the file from index.php page and will retrieve its information in
file.php page. Write the following code to upload the file in index.php page.
<html>
<head>
<title>PHP Superglobals</title>
</head>
<body>
<?php
<!--demonstration of $_FILES-->
<h1>Upload an Image:</h1>
<form method="post" action="file.php" enctype="multipart/form-data">
<label for="file">Upload an image:</label>
<input type="file" name="file" id="file"/><br><br>
&nbsp;<input type="submit" value="Submit"/>
</form>
</body>
</html>
In the above code we have created a form to upload the file. The form has post method and it will
take the form data to file.php page as stated in action attribute of the form. The form has one more
attribute called enctype that has value multipart/form-data. The attribute enctype indicates the
encryption type and its value multipart/form-data converts the file data to binary format.

The input type to accept a file from user is file. It gives a browse button to browse the file. When
we click on the browse button an open file dialog appears, which allows us to select the desired
file. We have also included a submit button to submit the form.
To know whether our file has been uploaded or not, we have to write the following code in file.php
page.
<html>
<head>
<title>File</title>
</head>
<body>
<?php
if($_FILES["file"]["error"]>0)
{
echo "Error : ",$_FILES["file"]["error"]."<br>";
}
else
{
echo "File Uploaded Successfully!<br><br>";
echo "File details:<br>";
echo "File name: ".$_FILES["file"]["name"]."<br>";
echo "File type: ".$_FILES["file"]["type"]."<br>";
echo "File size: ".$_FILES["file"]["size"]."<br>";
}
?>
</body>
</html>
We have certain parameters used with $_FILES to know information about the file such as type,
name, size, error, temp_name etc. While including these parameters, first the input type for
uploading the file i.e. file is used and then one of the above parameters are used in the array
notation.
They are shown below:

$_FILES[file][name] gives name of the uploaded file.


$_FILES[file][type] gives type of the uploaded file.
$_FILES[file][size] gives size in bytes of the uploaded file.
$_FILES[file][error] if any error occurs during uploaded file, it gives the error code.
$_FILES[file][tmp_name] gives the temporary name of the file copy stored on
server.

6 b) Create form elements with multiple options: 3M


How do we handle the multi-values fields in PHP? Its kind of tricky. We need to add square
brackets ( []) after the field name of the multi-valued form field. When PHP sees this sign ( []), it
creates a nested array of values within the $_GET or $_POST array based on the method we use
in the form.

The name of the multi-select list box should be formats[] and the name of the checkboxes should
be sizes[].

Validating multi-valued form fields


When you submit the form that contains multi-valued form fields to the web server without
selecting any item from a multi-select list box and or checking any checkbox, nothing is sent to
the web server at all. Therefore you cannot handle the multi-values from fields like single-value
form fields as follows:
// validate the formats fields
if(count($_POST['formats'] > 0)){
// ...
}

Because the formats do not exist in the $_POST array, you will get an error message. To check if
a multi-values field in submitted with value, you use the isset() function:
<?php
// validate the formats fields
if(isset($_POST['formats'])){
$formats = $_POST['formats'];
//
}

In addition, the values of the multi-values form fields are fixed, so you can check the submitted
value against the predefined values. Suppose the allowed formats are stored in the
$allowed_formats array, you can check the submitted value against the values in this array using
the in_array() function:
<?php
$allowed_formats = array('image','flash','video','HTML5');
// validate the formats fields
if(isset($_POST['formats'])){
$formats = $_POST['formats'];
foreach ($formats as $format) {
if(!in_array($format, $allowed_formats)){
// invalid format
//...
}
}
}

To save time, you can generate multi-valued form fields based on the predefined values using PHP
as follows:
<select multiple="multiple" name="formats[]" id="adsformat">
<?php foreach ($allowed_formats as $format): ?>
<option value="<?php echo $format; ?>" <?php set_selected($format); ?>>
<?php echo $format; ?>
</option>
<?php endforeach;?>
</select>

Example: 4M
A Registration Form with Multi-Value Fields
<!DOCTYPE html5>
<html>
<body>
<form action="index.php" method="post">
<label for="firstName">First name</label>
<input type="text" name="firstName" id="firstName" value="" />
<label for="mySelection">What are your favorite widgets?</label>
<select name="mySelection[]" id="mySelection" size="3" multiple="multiple">
<option value="PHP">PHP Language</option>
<option value="Java">Java Language</option>
<option value="CSS">CSS Language</option>
</select>
<label for="tested">Choice One?</label>
<input type="checkbox" name="chioces[]" id="ChoiceOne" value="testTask" />
<label for="designed">Choice Two?</label>
<input type="checkbox" name="chioces[]" id="ChoiceTwo" value="designTask" />
<input type="submit" name="submitButton" id="submitButton" value="Send Details" />
<input type="reset" name="resetButton" id="resetButton" value="Reset Form"/>
</div>
</form>
</body>
</html>

7 a) Mysql_connect(): 5M
PHP provides mysql_connect() function to open a database connection. This function takes five
parameters and returns a MySQL link identifier on success or FALSE on failure.

Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);

server
Optional The host name running the database server. If not specified, then the default value will
be localhost:3306.

user
Optional The username accessing the database. If not specified, then the default will be the name
of the user that owns the server process.

passwd
Optional The password of the user accessing the database. If not specified, then the default will
be an empty password.

new_link
Optional If a second call is made to mysql_connect() with the same arguments, no new
connection will be established; instead, the identifier of the already opened connection will be
returned.

client_flags
Optional A combination of the following constants
MYSQL_CLIENT_SSL Use SSL encryption.
MYSQL_CLIENT_COMPRESS Use compression protocol.
MYSQL_CLIENT_IGNORE_SPACE Allow space after function names.

MYSQL_CLIENT_INTERACTIVE Allow interactive timeout seconds of inactivity before


closing the connection.

7 b) Mysql_close(): 4M
In PHP, mysql_close() is used for closing the non-persistent connection to MySQL server that is
associated with the specified link identifier. You can use the following code to close your
connection:
mysql_close(connection)

Usually, its not necessary to use mysql_close() since non-persistent links automatically close at
the end script execution.
connection Required. Specifies the MySQL connection to close

7 c) mysql_real_escape_string(): 5M
This mysql_real_escape_string() function in php escapes special characters in a string for use in
an SQL statement.

Syntax
string mysql_real_escape_string(string unescaped_string [,resource link_identifier])
Returns the escaped string on success, or FALSE on failure.
This function will escape special characters in the unescaped_string, this differs from
mysql_escape_string() by taking into account of connection's current charset, so that it is safe to
place it in a mysql_query(). This function does not escape % and _.

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which


prepends backslashes to the following characters: x00, n, r, , ', " and x1a. This function must always
(with few exceptions) be used to make data safe before sending a query to MySQL.

8 a) Initialize the XML parser in PHP: 7M


The XML parser is an event-based parser. Look at the following XML fraction:
<from>Jani</from>
An event-based parser reports the XML above as a series of three events:

Start element: from


Start CDATA section, value: Jani
Close element: from

We want to initialize the XML Expat Parser in PHP, define some handlers for different XML
events, and then parse the XML file.
<?php
// Initialize the XML parser
$parser=xml_parser_create();
// Function to use at the start of an element
function start($parser,$element_name,$element_attrs) {
switch($element_name) {
case "NOTE":
echo "-- Note --<br>";
break;
case "TO":
echo "To: ";
break;
case "FROM":
echo "From: ";
break;
case "HEADING":
echo "Heading: ";
break;
case "BODY":
echo "Message: ";
}
}
// Function to use at the end of an element
function stop($parser,$element_name) {
echo "<br>";
}
// Function to use when finding character data
function char($parser,$data) {
echo $data;
}
// Specify element handler
xml_set_element_handler($parser,"start","stop");
// Specify data handler
xml_set_character_data_handler($parser,"char");
// Open XML file
$fp=fopen("note.xml","r");
// Read data
while ($data=fread($fp,4096)) {
xml_parse($parser,$data,feof($fp)) or
die (sprintf("XML Error: %s at line %d",
xml_error_string(xml_get_error_code($parser)),
xml_get_current_line_number($parser)));
}
// Free the XML parser
xml_parser_free($parser);
?>
Example explained:
1 Initialize the XML parser with the xml_parser_create() function
2 Create functions to use with the different event handlers
3 Add the xml_set_element_handler() function to specify which function will be executed
when the parser encounters the opening and closing tags
4 Add the xml_set_character_data_handler() function to specify which function will execute
when the parser encounters character data
5 Parse the file "note.xml" with the xml_parse() function
6 In case of an error, add xml_error_string() function to convert an XML error to a textual
description
7 Call the xml_parser_free() function to release the memory allocated with the
xml_parser_create() function

8 b) SimpleXML: 3M
SimpleXML is an extension that allows us to easily manipulate and get XML data. SimpleXML
provides an easy way of getting an element's name, attributes and textual content if you know the
XML document's structure or layout. SimpleXML turns an XML document into a data structure
you can iterate through like a collection of arrays and objects.
<?php
// Example 14-5-7.php
$books = simpleXML_load_file("books.xml");
foreach($books as $book) {
echo $book->title . " - ";
echo "book_id = $book[book_id]\n";
}
?>
Advantages: 4M
If the file were more complex, the advantages of using SimpleXML to parse the content would be
obvious. The SimpleXML extension does not include any features to manipulate the XML
document in memory, but both extensions have functions that allow for the exchange of documents
between the two standards. Its possible to use the DOM extension to build a document with values
from a database or other source and then convert it to SimpleXML before the document is passed
to another process for further processing. The advantage of the DOM extension is the ability to
add, remove, and change elements and attributes in the object tree.

You might also like