unit five_lecture notes.doc1

31
WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V UNIT –V Building Web Applications-Cookies-Sessions-Open Source Environment-PHP-MYSQL Building Web Applications A web application is an application that is accessed over a network such as the Internet or an intranet . The term may also mean a computer software application that is hosted in a browser- controlled environment (e.g. a Java applet ) [citation needed ] or coded in a browser-supported language (such as JavaScript , combined with a browser-rendered markup language like HTML ) and reliant on a common web browser to render the application executable . Web applications are popular due to the ubiquity of web browsers, and the convenience of using a web browser as a client , sometimes called a thin client . The ability to update and maintain web applications without distributing and installing software on potentially thousands of client computers is a key reason for their popularity, as is the inherent support for cross-platform compatibility. Common web applications include webmail , online retail sales , online auctions , wikis and many other functions. History In earlier types of cloud computing , each application had its own client program which served as its user interface and had to be separately installed on each user's personal computer . An upgrade to the server part of the application would typically require an upgrade to the clients installed on each user workstation, adding to the support cost and decreasing productivity . In contrast, web applications use web documents written in a standard format such as HTML (and more recently XHTML ), which are supported by a variety of web browsers. Generally, each individual web page is delivered to the client as a static document, but the sequence of pages can provide an

Upload: preethi-bala

Post on 22-Apr-2017

214 views

Category:

Documents


0 download

TRANSCRIPT

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

UNIT –V

Building Web Applications-Cookies-Sessions-Open Source Environment-PHP-MYSQL

Building Web Applications

A web application is an application that is accessed over a network such as the Internet or an intranet. The term may also mean a computer software application that is hosted in a browser-controlled environment (e.g. a Java applet)[citation needed] or coded in a browser-supported language (such as JavaScript, combined with a browser-rendered markup language like HTML) and reliant on a common web browser to render the application executable.

Web applications are popular due to the ubiquity of web browsers, and the convenience of using a web browser as a client, sometimes called a thin client. The ability to update and maintain web applications without distributing and installing software on potentially thousands of client computers is a key reason for their popularity, as is the inherent support for cross-platform compatibility. Common web applications include webmail, online retail sales, online auctions, wikis and many other functions.

History

In earlier types of cloud computing, each application had its own client program which served as its user interface and had to be separately installed on each user's personal computer. An upgrade to the server part of the application would typically require an upgrade to the clients installed on each user workstation, adding to the support cost and decreasing productivity.

In contrast, web applications use web documents written in a standard format such as HTML (and more recently XHTML), which are supported by a variety of web browsers.

Generally, each individual web page is delivered to the client as a static document, but the sequence of pages can provide an interactive experience, as user input is returned through web form elements embedded in the page markup. During the session, the web browser interprets and displays the pages, and acts as the universal client for any web application.

In 1995, Netscape introduced a client-side scripting language called JavaScript, which allowed programmers to add some dynamic elements to the user interface that ran on the client side. Until then, all the data had to be sent to the server for processing, and the results were delivered through static HTML pages sent back to the client

In 1996, Macromedia introduced Flash, a vector animation player that could be added to browsers as a plug-in to embed animations on the web pages. It allowed the use of a scripting language to program interactions on the client side with no need to communicate with the server.

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

In 1999, the "web application" concept was introduced in the Java language in the Servlet Specification version 2.2. [2.1?].[1][2] At that time both JavaScript and XML had already been developed, but Ajax had still not yet been coined and the XMLHttpRequest object had only been recently introduced on Internet Explorer 5 as an ActiveX object.[3]

In 2005, the term Ajax was coined, and applications like Gmail started to make their client sides more and more interactive.

Interface

Webconverger operating system provides an interface for web applications.

Through Java, JavaScript, DHTML, Flash, Silverlight and other technologies, application-specific methods such as drawing on the screen, playing audio, and access to the keyboard and mouse are all possible. Many services have worked to combine all of these into a more familiar interface that adopts the appearance of an operating system. General purpose techniques such as drag and drop are also supported by these technologies. Web developers often use client-side scripting to add functionality, especially to create an interactive experience that does not require page reloading. Recently, technologies have been developed to coordinate client-side scripting with server-side technologies such as PHP. Ajax, a web development technique using a combination of various technologies, is an example of technology which creates a more interactive experience.

Structure

Applications are usually broken into logical chunks called "tiers", where every tier is assigned a role.[4] Traditional applications consist only of 1 tier, which resides on the client machine, but web applications lend themselves to a n-tiered approach by nature.[4] Though many variations are possible, the most common structure is the three-tiered application.[4] In its most common form, the three tiers are called presentation, application and storage, in this order. A web browser is the first tier (presentation), an engine using some dynamic Web content technology (such as ASP, ASP.NET, CGI, ColdFusion, JSP/Java, PHP, Perl, Python, Ruby on Rails or Struts2) is the middle tier (application logic), and a database is the third tier (storage).[4] The web browser sends requests to the middle tier, which services them by making queries and updates against the database and generates a user interface.

For more complex applications, a 3-tier solution may fall short, and you may need a n-tiered approach, where the greatest benefit is breaking the business logic, which resides on the application tier, into a more fine-grained model.[4] Or adding an integration tier that separates the data tier from the rest of tiers by providing an easy-to-use interface to access the data.[4] For example, you would access the client data by calling a "list_clients()" function instead of making a SQL query directly against the client table on the database. That allows you to replace the underlying database without changing the other tiers.[4]

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

There are some who view a web application as a two-tier architecture. This can be a "smart" client that performs all the work and queries a "dumb" server, or a "dumb" client that relies on a "smart" server.[4] The client would handle the presentation tier, the server would have the database (storage tier), and the business logic (application tier) would be on one of them or on both.[4] While this increases the scalability of the applications and separates the display and the database, it still doesn't allow for true specialization of layers, so most applications will outgrow this model.[4]

Business use

An emerging strategy for application software companies is to provide web access to software previously distributed as local applications. Depending on the type of application, it may require the development of an entirely different browser-based interface, or merely adapting an existing application to use different presentation technology. These programs allow the user to pay a monthly or yearly fee for use of a software application without having to install it on a local hard drive. A company which follows this strategy is known as an application service provider (ASP), and ASPs are currently receiving much attention in the software industry.

Writing web applications

There are many web application frameworks which facilitate rapid application development by allowing the programmer to define a high-level description of the program.[5] In addition, there is potential for the development of applications on Internet operating systems, although currently there are not many viable platforms that fit this model.

The use of web application frameworks can often reduce the number of errors in a program, both by making the code simpler, and by allowing one team to concentrate just on the framework. In applications which are exposed to constant hacking attempts on the Internet, security-related problems can be caused by errors in the program. Frameworks can also promote the use of best practices such as GET after POST.

Applications

Browser applications typically include simple office software (word processors, online spreadsheets, and presentation tools), with Google Docs being the most notable example, and can also include more advanced applications such as project management, computer-aided design, video editing and point-of-sale.

Benefits

Web applications do not require any complex "roll out" procedure to deploy in large organizations. A compatible web browser is all that is needed;

Browser applications typically require little or no disk space on the client;

They require no upgrade procedure since all new features are implemented on the server and automatically delivered to the users;

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Web applications integrate easily into other server-side web procedures, such as email and searching.

They also provide cross-platform compatibility in most cases (i.e., Windows, Mac, Linux, etc.) because they operate within a web browser window.

Drawbacks

In practice, web interfaces, compared to thick clients, typically force significant sacrifice to user experience and basic usability.

Web applications absolutely require compatible web browsers. If a browser vendor decides not to implement a certain feature, or abandons a particular platform or operating system version, this may affect a huge number of users;

Standards compliance is an issue with any non-typical office document creator, which causes problems when file sharing and collaboration becomes critical;

Browser applications rely on application files accessed on remote servers through the Internet. Therefore, when connection is interrupted, the application is no longer usable but if it uses HTML5 API's such as Offline Web application caching[7], it can be downloaded and installed locally, for offline use. Google Gears, although no longer in active development, is a good example of a third party plugin for web browsers that provides additional functionality for creating web applications;

Since many web applications are not open source, there is also a loss of flexibility, making users dependent on third-party servers, not allowing customizations on the software and preventing users from running applications offline (in most cases). However, if licensed, proprietary software can be customized and run on the preferred server of the rights owner;

They depend entirely on the availability of the server delivering the application. If a company goes bankrupt and the server is shut down, the users have little recourse. Traditional installed software keeps functioning even after the demise of the company that produced it (though there will be no updates or customer service);

Likewise, the company has much greater control over the software and functionality. They can roll out new features whenever they wish, even if the users would like to wait until the bugs have been worked out before upgrading. The option of simply skipping a weak software version is often not available. The company can foist unwanted features on the users or cut costs by reducing bandwidth. Of course, companies will try to keep the good will of their customers, but the users of web applications have fewer options in such cases unless a competitor steps in and offers a better product and easy migration;

The company can theoretically track anything the users do. This can cause privacy problems.

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Cookies

HTTP is Stateless

Every request for a web page is an independent transaction. Servers don’t remember who requested what when. Ordinarily, this is no problem. If Joe Doakes requests page1.html and then Bertha Bupkis requests that same page ten seconds later, does the server really care? Once you start filling in forms that require you to remember information, though, the statelessness of HTTP is a pain.

Consider this first page of a form, where Joe Doakes enters his name:

Your name:

On the next page, we would like to personalize the response.

Thanks, Joe Doakes!

In short, the server must somehow keep track of information from one page to another. There are lots of ways to do this, but the one we will explore (because it works well with JavaScript) is cookies.

Cookie Format

You set a cookie with statements like this:

document.cookie = "cookieName=cookieData"; // generic formdocument.cookie = "userName=Joe";

document.cookie = "item=toner;" + "expires=Mon, 04 Jan 2009 05:03:05 GMT";document.cookie = "price=34.95;" + "expires=Mon, 04 Jan 2009 05:03:05 GMT";

The cookie stays around until the expiration time. If you don’t set an expiration date, the cookie vanishes as soon as you exit the browser.

The cookie data cannot contain any commas, semicolons, or whitespace. In order to accommodate data that does contain these characters, we will URL-encode the data. That is, we will use the built-in escape() function to encode the data in a form that contains only characters that are allowed in a URL. The button below will call a function that sets a cookie with the value in the form.

Please enter your name:

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

<form name="theForm" action="#">Please enter your name:<input type="text" name="yourName" /><input type="button" value="Set Cookie" onClick="setCookie();"></form>

function setCookie(){ var response = document.theForm.yourName.value; if (response == "") { response = "Mystery Guest"; } document.cookie = "yourName=" + escape(response);}

Sessions

There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can't easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?

There are three typical solutions to this problem.

1. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled:

o Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all),

o Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and

o Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).

2. URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don't support cookies or where the user has disabled cookies.

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.

3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

Servlets provide an outstanding technical solution: the HttpSession API. This is a high-level interface built on top of cookies or URL-rewriting. In fact, on many servers, they use cookies if the browser supports them, but automatically revert to URL-rewriting when cookies are unsupported or explicitly disabled. But the servlet author doesn't need to bother with many of the details, doesn't have to explicitly manipulate cookies or information appended to the URL, and is automatically given a convenient place to store data that is associated with each session.

2. The Session Tracking API

Using sessions in servlets is quite straightforward, and involves looking up the session object associated with the current request, creating a new session object when necessary, looking up information associated with a session, storing information in a session, and discarding completed or abandoned sessions.

2.1 Looking up the HttpSession object associated with the current request.

This is done by calling the getSession method of HttpServletRequest. If this returns null, you can create a new session, but this is so commonly done that there is an option to automatically create a new session if there isn't one already. Just pass true to getSession. Thus, your first step usually looks like this: HttpSession session = request.getSession(true);

2.2 Looking up Information Associated with a Session.

HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the-scenes mechanism like cookies or URL-rewriting. These session objects have a builtin data structure that let you store any number of keys and associated values. In version 2.1 and earlier of the servlet API, you use getValue("key") to look up a previously stored value. The return type is Object, so you have to do a typecast to whatever more specific type of data was associated with that key in the session. The return value is null if there is no such attribute. In version 2.2, getValue is deprecated in favor of getAttribute, both because of the better naming match with setAttribute (the match for getValue is putValue, not setValue), and because setAttribute lets you use an attached HttpSessionBindingListener to monitor values, while

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

putValue doesn't. Nevertheless, since few commercial servlet engines yet support version 2.2, I'll use getValue in my examples. Here's one representative example, assuming ShoppingCart is some class you've defined yourself that stores information on items being purchased. HttpSession session = request.getSession(true); ShoppingCart previousItems = (ShoppingCart)session.getValue("previousItems"); if (previousItems != null) { doSomethingWith(previousItems); } else { previousItems = new ShoppingCart(...); doSomethingElseWith(previousItems); }In most cases, you have a specific attribute name in mind, and want to find the value (if any) already associated with it. However, you can also discover all the attribute names in a given session by calling getValueNames, which returns a String array. In version 2.2, use getAttributeNames, which has a better name and which is more consistent in that it returns an Enumeration, just like the getHeaders and getParameterNames methods of HttpServletRequest.

Although the data that was explicitly associated with a session is the part you care most about, there are some other pieces of information that are sometimes useful as well.

getId. This method returns the unique identifier generated for each session. It is sometimes used as the key name when there is only a single value associated with a session, or when logging information about previous sessions.

isNew. This returns true if the client (browser) has never seen the session, usually because it was just created rather than being referenced by an incoming client request. It returns false for preexisting sessions.

getCreationTime. This returns the time, in milliseconds since the epoch, at which the session was made. To get a value useful for printing out, pass the value to the Date constructor or the setTimeInMillis method of GregorianCalendar.

getLastAccessedTime. This returns the time, in milliseconds since the epoch, at which the session was last sent from the client.

getMaxInactiveInterval. This returns the amount of time, in seconds, that a session should go without access before being automatically invalidated. A negative value indicates that the session should never timeout.

2.3 Associating Information with a Session

As discussed in the previous section, you read information associated with a session by using getValue (or getAttribute in version 2.2 of the servlet spec). To specify information, you use putValue (or setAttribute in version 2.2), supplying a key and a value. Note that putValue replaces any previous values. Sometimes that's what you want (as with the referringPage entry in the example below), but other times you want to retrieve a previous value and augment it (as with the previousItems entry below). Here's an example:

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

HttpSession session = request.getSession(true); session.putValue("referringPage", request.getHeader("Referer"));

ShoppingCart previousItems = (ShoppingCart)session.getValue("previousItems"); if (previousItems == null) { previousItems = new ShoppingCart(...); } String itemID = request.getParameter("itemID"); previousItems.addEntry(Catalog.getEntry(itemID)); // You still have to do putValue, not just modify the cart, since // the cart may be new and thus not already stored in the session. session.putValue("previousItems", previousItems);

3. Example: Showing Session Information

Here is a simple example that generates a Web page showing some information about the current session. You can also download the source or try it on-line. package hall;

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.net.*;import java.util.*;

/** Simple example of session tracking. See the shopping * cart example for a more detailed one. * <P> * Part of tutorial on servlets and JSP that appears at * http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/ * 1999 Marty Hall; may be freely used or adapted. */

public class ShowSession extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Searching the Web"; String heading; Integer accessCount = new Integer(0);; if (session.isNew()) { heading = "Welcome, Newcomer";

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

} else { heading = "Welcome Back"; Integer oldAccessCount = // Use getAttribute, not getValue, in version // 2.2 of servlet API. (Integer)session.getValue("accessCount"); if (oldAccessCount != null) { accessCount = new Integer(oldAccessCount.intValue() + 1); } } // Use putAttribute in version 2.2 of servlet API. session.putValue("accessCount", accessCount); out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" + "<H2>Information on Your Session:</H2>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + " <TH>Info Type<TH>Value\n" + "<TR>\n" + " <TD>ID\n" + " <TD>" + session.getId() + "\n" + "<TR>\n" + " <TD>Creation Time\n" + " <TD>" + new Date(session.getCreationTime()) + "\n" + "<TR>\n" + " <TD>Time of Last Access\n" + " <TD>" + new Date(session.getLastAccessedTime()) + "\n" + "<TR>\n" + " <TD>Number of Previous Accesses\n" + " <TD>" + accessCount + "\n" + "</TABLE>\n" + "</BODY></HTML>");

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Here's a typical result, shown after visiting the page several without quitting the browser in between:

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

PHP

PHP stands for PHP: Hypertext PreprocessorPHP is a server-side scripting language, like ASPPHP scripts are executed on the serverPHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)PHP is an open source software (OSS)This means its free to use and isn’t being controlled by a single entity.It is being developed by a group of developersPHP syntax resembles that of JavaScript and ActionScript in different ways.PHP is free to download and use.

PHP files may contain text, HTML tags and scripts.PHP files are returned to the browser as plain HTML.PHP files have a file extension of ".php", ".php3", or ".phtml".PHP can be written in any text editor.PHP script will be located inside special tags, much like JavaScript

e.g. <?php //php script here ?>

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

PHP code can be located any where in the page.PHP is case sensitive.Every variable in PHP will have the $ symbol as a prefix

e.g. $myName =“John”;

Every line of code MUST be terminated with a ; symbol.

PHP runs on different platforms (Windows, Linux, Unix, etc.)PHP is compatible with almost all servers used today (Apache, IIS, etc.)PHP is FREE to download from the official PHP resource: www.php.netPHP is easy to learn and runs efficiently on the server side

Basic PHP Syntax

You cannot view the PHP source code by selecting "View source" in the browser - youwill only see the output from the PHP file, which is plain HTML.This is because the scripts are executed on the server before the result is sent backto the browser.A PHP scripting block always starts with <?php and ends with ?>. A PHP scriptingblock can be placed anywhere in the document.On servers with shorthand support enabled you can start a scripting block with <?and end with ?>.However, for maximum compatibility, we recommend that you use the standard form(<?php) rather than the shorthand form.<?php?>

A PHP file normally contains HTML tags, just like an HTML file, and some PHPscripting code.Below, we have an example of a simple PHP script which sends the text "Hello World"to the browser:

<html><body><?phpecho "Hello World";?></body></html>Each code line in PHP must end with a semicolon. The semicolon is a separator andis used to distinguish one set of instructions from another.There are two basic statements to output text with PHP: echo and print. In theexample above we have used the echo statement to output the text "Hello World".

In PHP, we use // to make a single-line comment or /* and */ to make a large comment

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

block.

Comments In PHP

<html><body><?php//This is a comment/*This isa commentblock*/?></body></html>

PHP Variables

Variables are used for storing a values, like text strings, numbers or arrays.When a variable is set it can be used over and over again in your scriptAll variables in PHP start with a $ sign symbol.The correct way of setting a variable in PHP:$var_name = value;

New PHP programmers often forget the $ sign at the beginning of the variable. In thatcase it will not work.Let's try creating a variable with a string, and a variable with a number:PHP Variables<?php$txt = "Hello World!";$number = 16;?>

PHP is a Loosely Typed Language

In PHP a variable does not need to be declared before being set.In the previous example, you see that you do not have to tell PHP which data type thevariable is.PHP automatically converts the variable to the correct data type, depending on howthey are set.In a strongly typed programming language, you have to declare (define) the type andname of the variable before using it.In PHP the variable is declared automatically when you use it.

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Variable Naming Rules

A variable name must start with a letter or an underscore "_"A variable name can only contain alpha-numeric characters and underscores(a-Z, 0-9, and _ )A variable name should not contain spaces. If a variable name is more thanone word, it should be separated with underscore ($my_string), or withcapitalization ($myString)

Strings In PHP

String variables are used for values that contains character strings.We are going to look at some of the most common functions and operators used tomanipulate strings in PHP.After we create a string we can manipulate it. A string can be used directly in afunction or it can be stored in a variable.Below, the PHP script assigns the string "Hello World" to a string variable called $txt:Strings In PHP<?php$txt="Hello World";echo $txt;?>

The output of the code will be:Strings In PHPHello World

The Concatenation Operator

There is only one string operator in PHP.The concatenation operator (.) is used to put two string values together.To concatenate two variables together, use the dot (.) operator:

<?php$txt1="Hello World";$txt2="1234";echo $txt1 . " " . $txt2;?>

If we look at the code above you see that we used the concatenation operator twotimes. This is because we had to insert a third string.Between the two string variables we added a string with a single character, an emptyspace, to separate the two variables.

The output of the code will be:

Hello World 1234

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Using the strlen() function

The strlen() function is used to find the length of a string.Let's find the length of our string "Hello world!":Using the strlen() function<?phpecho strlen("Hello world!");?>

The output of the code above will be:12

The length of a string is often used in loops or other functions, when it is important toknow when the string ends. (i.e. in a loop, we would want to stop the loop after thelast character in the string)

The strpos() function is used to search for a string or character within a string.If a match is found in the string, this function will return the position of the first match.If no match is found, it will return FALSE.Let's see if we can find the string "world" in our string:

<?phpecho strpos("Hello world!","world");?>The output of the code above will be:6

As you see the position of the string "world" in our string is position 6. The reason thatit is 6, and not 7, is that the first position in the string is 0, and not 1.

MySQL

MySQL is a small database serverMySQL is ideal for small and medium applicationsMySQL supports standard SQLMySQL compiles on a number of platformsMySQL is free to download and usePHP + MySQLPHP combined with MySQL is cross-platform(means that you can develop in Windows and serve on a Unix platform).

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Building Web Content with PHP and MySQL

<html>

<body>

<table border=1>

<tr> <?php //start of a table row ?>

<th>Column 1</th><th>Column 2</th><th>Column 3</th> <?php //the names for each column ?>

</tr>

<td>entry1</td><td>entry2</td><td>entry3</td><?php // a row of data ?>

<./tr>

<tr>

<td>entry4</td><td>entry5</td><td>entry6</td>

</tr>

</table>

</body>

</html>

Renders as:

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Using MySQL inside PHP

$is_connected = @mysql_connect("localhost", "guest", "guestpwd");

we use a MySQL specific PHP command. When programmatically accessing a database, there are two main approaches – you can call commands that assume a specific database to interface with, or you can call generalized database commands that get passed to a middle-level driver that translate them to the commands for a specific database. The former approach can make things a little simpler, the latter approach allows greater flexibility to easily switch a database from a MySQL database to, for example, Postgress. We are going to use the MySQL-specific approach. Note: if you don’t have “guest” on

in MySQL run

GRANT ALL ON trii.* TO 'guest'@'localhost' IDENTIFIED BY 'guestpwd';

The next thing to notice is the variable assigned the return value of mysqli_connect. This variable will be either a numeric id for the connection or false depending on whether or not the program connects to MySQL. Connecting to a database is not guaranteed to work. The connection could fail if the database

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

server is down, or if the database is on another machine and the network is down, etc. Now we can check $is_connected to make sure everything is running smoothly.

The last thing new about this line is the’@’ symbol. This symbol goes in front of a function to indicate we want to suppress the default way PHP will handle an error. If we are ok with the standard PHP error handling we could have just written:

$is_connected = mysql_connect("localhost", "guest", "guestpwd");

However, it’s a good idea to do your own error handling. Sometimes your users aren’t going to be computer-savvy to make sense of the error message. Sometimes your users might be too savvy and the default error message might tell them more than you want about your database.

When we’re doing our own error handling, you might notice the new function die(). Don’t let its terrifying name scare you off – die is a useful function. It will display whatever string you pass it, and then it will cause the server to ignore all remaining PHP code.

Selecting a Database

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Now, you want to select the trii database. Notice once again we repeat the process of making a query, checking to see that it worked, and handling the error if it didn’t.Note: If you don’t have trii built, from he password your MySQL, on the command line run

mysql -u root < trii.sqlmysql -u root < trii.sql

Running Queries in PHPNow that we’ve connected to the database, let’s do something useful. Say we want to get the gene_id, name and Entrez id from the gene table in the trii database, and we want to sort the results by their name value. In MySQL, we could do this with the query:

select gene_id, name, locuslink from gene order by name;

But, if we want PHP to use the results, we need to embed this query within PHP’s MySQL framework. We create a string with the query we want to make, and then pass this string to mysql_query

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

A typical mysql query run through PHP. Here MySQL doesn’t return anything from the query so all we need to do is check that the result isn’t false, which would indicate an error.

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Populating an SQL Table with PHP

This code snippet from populate_table.php is part of a program that populates the deadwood table with the values in a tab delimited file. In the foreach loop, each line is accessed as a single string. It is cleaned by htmlspecialchars, and then split with the explode function. The rest is just a standard MySQL query. Remember to include the single quotes around each value (e.g. ‘$line_array[0]’) when the value is a string, as MySQL requires it. You can imagine doing more complicated things with your PHP code here, such as processing your values with php functions, or populating different tables with different parts of the line (e.g. putting line_array[2] and line_array[3] into a historical_figures table and the rest in a tv_show_details table)

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Displaying an SQL Table as an HTML Table

This code snippet from display.php performs a query that returns a result we want to process even if the result is correct. We use a while loop to keep assigning $row the value from mysql_fetch_array, and accessing the $row value matching the field name which is its key. We put each value into an htlm table.

WEBTECHNOLOGY -241208 Lecture Notes - UNIT-V

Security Notes

PHP allows you to write projects quickly.

• Roughly 67% of the vulnerabilities affected Web servers, Web applications and Web browsers.

• Applications written in PHP comprise roughly 30% of all vulnerabilities.

• Roughly 63% of the Web application vulnerabilities can be accounted

for by 4 vulnerability classes: remote file inclusion, SQL injection,

cross-site scripting, and directory traversal.

* Vulnerabilities within the PHP programming language versions 4 and 5 comprised 3% of total

vulnerabilities