Web Server Programming phần 5 pptx

63 308 0
Web Server Programming phần 5 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

ImageString ($image, 2, $x1, $y-10, $fullname, $text_color); if($value==0) ImageString($image, 2, $x2, $y-10, "Who?", $text_color); else { $scaled = ($value*600)/$max; $scaled = (integer) $scaled; imagefilledrectangle($image, $x2, $y-12, $x2+$scaled, $y+2, $fill_color); } ImageLine($image, 0, $y+4, $imagewidth, $y+4, $black); $y+=20; } // Save the image to file imagepng($image,$tempfile); imagedestroy($image); } 6.8 State Section 6.4 contained an example illustrating how the hiding of previously submitted data in subsequently generated dynamic form pages can preserve client state. That scheme works in part, but it is only r eally useful if you are working through a fixed sequence of forms, all of which must be completed in a specific order. There are many other situations where it is useful to maintain some representation o f client state, even though the client is going to be moving around, following different links to various parts of your web site. Consider for instance a web site where you want to include advertisements in the banner portion of the pages that you return, most of these pag es being essentially static in forma- tion. Your client will be following arbitrary links amongst your pages, but you would still like to save ‘client state’ – if simp ly somethin g like a reco rd of the advertisements that th e client has already seen, so that you can show other products. But you don’t have any forms, and there are no form submission actions that you could rely on to return hidden field data. ‘Persistent state client side cookies’ are the basis of an alternative mechanism for pre - serving state. ‘Cookies’ are: ● Small blocks of data created in the server ● Sent to the client in the HTTP header portion of a response ● Saved by the client’s browser ● Returned to your server in the HTTP header portion of subsequent requests 238 PHP4 The rules for cookies permit a server to create up to twenty distinct cookies associated with a particular resource, with each individual cookie having up to 4 kbyte of data. Each cookie can have: ● Data: The data take the form of name/value pair(s). ● An expiry date: This can be a date in the past, meaning that the cookie should be d eleted immediately from the browser’s records; the current date, meaning that the cookie is to be deleted when the client terminates execution o f the browser program; or a date in the future ( supposedly not more than one year into the future), which means that the browser should keep the cookie for future reference. ● A domain: This should identify the domain where the cookie originated. For example, the cookie might specify bigcompany.com. Such a cookie can be returned to any machine in that domain, e.g. www1.bigcompany.com or www2.bigcompany.com. ● Optional path data: The site for bigcompany.com might include separate file hierarchies for the ‘marketing’ and ‘manufacturing’ divisions; both might use cookies to record data about their clients. In such a situation, it might be worth setting ‘path’controls so that cookies set by scripts in the ‘marketing’ hierarchy are only returned when the client submits GET/POST requests for other marketing resources. Cookies are used in two main ways. A cookie can be a data carrier. A script that has extracted data can store these in a cookie that g ets returned with a response page. The cookie data are returned in the next request; they can be picked up by the next script and processed. This ap pr o ach is similar to using hidden fields to hold previously su b mitted data. The second style of use has the cookie merely as an identifier; all application data are stored on the server. The identifier’s value – a carefully constructed string with a randomized component – is allo - cated by the first processing script and returned as a cookie with the script’s response page. This identifier cookie now labels your client. It can serve as a primary key for database records, or as a part of a file identifier. The identifier is returned to your server each time the client makes a new request. Processing scripts that extract data from later submissions can associate these data with the identifier in the returned cookie. Data can be added to database tables or files (or, in some situations, can be saved in memory records managed by the web server). Obviously, the identifier style is safer (data are not repeatedly transferred over th e net, so there is less r isk of exposure, and data are not returned to clients, so reducing the potential for adjustment of values by hackers). However, as illustrated by the first o f our two cookie examples, there are situations where the cookie as a data carrier is quite adequate. The first cookie example involves a company that wants to advertise its wares on the main welcome page of its web site. This main p age is composed as a frameset; o ne frame has contents generated by a little PHP script that selects a product to advertise. Each time a customer returns to this main page, he or she should see a different product advertised in the advertisement frame. The frameset for the main page is: State 239 <html><head><title>Portal</title></head> <frameset cols="240,*"> <frame src="advert.php"> <frame src="mainframe.html" scrolling="auto"> </frameset> </html> with the advert.php script being used to generate the contents of the frame in the left column. The example code is considerably simplified – products are defined as records in an array rather than being read from disk, and they are advertised in sequence (working cycli - cally once a customer has seen already products once), so the last advertisement number is the only data that has to be stored. This information is saved as a cookie – ‘ timtam=number’. If the advertisements were shown in a more randomized order, you could have a cookie value as a string like number#number#number, with the numbers iden - tifying those advertisements already shown. The record of advertisements seen is to last about a week, so the cookie will be set with a specified expiry date. The starting point in the collection of products is picked randomly for new clients. The script advert.php is: <? // Define data for products, in a real system would read // this information from a database. $products = array( array (name=>"chair", src=>"images/chair.jpg", description=>"Ergonomic chair"), ); // Processing code starts here: $numproducts = count($products); srand((double)microtime()*100000); $choice = 0; // Did the client return our "timtam" cookie? // If it was returned, client has already seen some adverts. // so take the next in sequence. // If the cookie was not returned, this is a new client, pick // randomly a starting advert. $mycookie = $HTTP_COOKIE_VARS["timtam"]; if(!isset($mycookie)) { $choice = rand(0, $numproducts); } else { 240 PHP4 $choice = $mycookie; $choice++; if($choice==$numproducts) $choice=0; } // set the cookie for next time $howlong=7*24*3600; setcookie("timtam",$choice, time() + $howlong); $item = $products[$choice]; $description = $item["description"]; $source = $item["src"]; // Generate HTML page that will be placed in the // advert frame of the frameset. print <<<HERE <html><head></head><body bgcolor=#dddddd> <h1>Buy now</h1> <p>See our detailed product catalog for wonderful items such as these! <h2>$description</h2> <img src=$source> <br> <a href=catalog.html target=CATALOG>Our catalog</a> </body></html> HERE; ?> The setcookie function must be called before any call to header or any output of text. Its arguments are: name, value, expiry time, optional path, optional domain, and ‘requires secure connection’ (you can limit cookies so they are only set if using a SSL network con - nection). The expiry time can be set by adding an offset to the current time – here the offset represents one week into the future (+ 7 * 24 * 3600 seconds). If the domain argu - ment is not given, the hostname is used. It would not matter if this cookie was viewed inappropriately – so if the last advertise - ment seen was #27, do what you like with that information. Nor would it matter if a hacker changed the value, they would simply change the sequence in which they saw the prod - ucts. But more generally, it is dangerous to store data on the client. You should never store a value that you have computed from input data that have been discarded, and you should always validate any returned values before using them in later scripts. The second example uses a cookie to store only a session key. Data relating to a client’s session are held in the server; in this example, the data are held in a file whose name matches the session key. The example is a trivialized shopping site where the data that are to be stored are the contents of a ‘shopping cart’. Apparently, there are hackers with nothing better to do than try usurping shopping ses - sions at small web sites. They do this by guessing the sequence used to generate session State 241 keys and creating their own cookie with a session key that they have guessed as being that in use by some other customer. If they guess correctly, they can confuse the server by joining an ongoing session and changing the contents of the shopping cart (imagine the fun that you can have doing things like changing some child’s order for Harry Potter and the Chamber of Secrets into an order for Proust’s Remembrance of Times Past). To prevent this, the mechanism used to generate session keys has to incorporate a significant random element. There are now various standard key-generation mechanisms; these should be used in preference to ad hoc schemes. The example is a site for acme.com.bv – an imaginary company that sells computers, office furniture and computer books. Acme’s web-site comprises the following PHP scripts and static pages: ● Welcome.php This is the entry point to the site with links to the main product pages; it also allocates the session key. ● Furniture.php, Books.php, Computer.php These pages are simple form pages used to order products; in the example, it is all hard- coded; a real system would generate these pages from data in a database. ● Purchases.php Records an order submitted from one of the form pages; the order is append ed to the ses- sion file. (Orders cannot be rescinded.) Provides links back to other order forms or on to the checkout processing stage. ● Checkout.php Essentially just a form requesting the name and address of the customer. ● Final.php This script simply lists the d ata su bmitted; a real script would add th e order to a tab le in a database. ● getwithit.html Most of the scripts incorporate a check for the cookie set on the Welcome page. If the cookie is not set, then either the client is running with cookies disabled in their browser or they have managed to jump past the welcome page. This static page asks for cookies to be enabled and provides a link to the welcome page. ● Session file This is a text file generated to hold r ecords of all orders submitted via the for ms pages. (Some of these scripts are not shown below; those omitted are essentially trivial and are left as ‘an exercise for the reader’.) Several of the scripts require the same code fragments – specifically the code that checks for the presence of a cookie and diverts the user to the getwithit.html page if no cookie is found. PHP supports a form of file includes; the required code fragment can be included in all pages that need it. The Welcome.php script is little more than a static page with links to the main shopping pages. The scripting code that it contains is that n eeded to allocate a session identifier. The 242 PHP4 mechanism used is that recommended in the PHP manual – basically you generate a random number based on the current time, but this is not in itself sufficiently secure, so you use the MD5 hashing algorithm to mix up the bits of this random string. This approach is standard; it is considered to produce keys that are sufficiently opaque as to deter the average hacker. The code for this script is: <? $existingSession=$HTTP_COOKIE_VARS["SessionData"]; if(!isset($existingSession)){ srand((double)microtime()*100000); $token = md5(uniqid(rand())); setcookie("SessionData",$token,0); } ?> <html><head><title>Welcome to our world</title></head> <body bgcolor=white><h1>Welcome</h1> We always like customers. Bring your friends along. <p>Our departments: <ul> <li><a href=furniture.php>Furniture</a> <li><a href=computers.php>Computers</a> <li><a href=books.php>Books</a> </ul></body></html> The cookie is set as a ‘session cookie’ (timeout of zero); it will disappear from the cli- ent’s browser when the browser is terminated. (The name ‘ SessionData’ might seem rather unsafe – likely to clash with the same name used by an other site. But there is actu- ally no problem; the browser identifies the cookies by the domain as well as the name. So, acme.com.bv will only receive SessionData cookies that it has set itself.) The code fragment that checks for the cookie can be held in a separate file – chkrdir.inc: <? $existingSession=$HTTP_COOKIE_VARS["SessionData"]; if(!isset($existingSession)){ header("Location: getwithit.html"); exit(); } ?> If the cookie is not found, this sends an HTTP-style redirection order back to the cli - ent’s browser. This response has just header data, the important part being the ‘Location’ directive that tells the browser what page it really is to fetch. The file getwithit.html is a static text page; the contents explain how a cookie is a harmless session tag, suggest that the user enable cookies, and provide a link back to the Welcome page. Other scripts in this State 243 web should all start by including this chkrdir.inc fragment. (You don’t have to use the suffix ‘ .inc – include file. If you do use it, you should be aware that if someone can guess the names of your .inc files then they can download your code – by default, both web server and b rowser will treat these as text files. You might want to add a security control to your httpd.conf file that prohibits client access to all .inc files.) The scripts that generate the forms for purchasing goods are simplified versions of those needed in a real site – the form is really just a static HTML table. Th is form can be submitted; submission invokes the purchase.php script. Alternatively, the user may chose to follow a link to a different order form or the checkout desk. These forms all allow multiple items to be purchased, so the input field associated with purchases is an array; the values for individual inputs are unique identifiers such as ISBNs for books and product codes for the furniture.php page. <? include("chkrdir.inc"); ?> <html><head><title>Books</title> </head><body bgcolor=white> <h1 align=center>Buy a book</h1> <form action=purchase.php method=post> <table align=center border=2> <caption>Available books</caption> <tr> <td> <input type=checkbox name="books[]" value=ISBN:078972310> </td> <td> Don't Make Me Think! S. Krug, R. Black; This is the book you need if you want to design great web pages. </td> <td> $24 </td> </tr> // and a few more books <tr> <td align=center colspan=3> <input type=submit value="Buy Books"> </td> </tr></table></form><br><hr><ul> <li><a href=furniture.php>Furniture</a> <li><a href=computers.php>Computers</a> <li><a href=checkout.php>Checkout</a> </ul></body></html> 244 PHP4 The purchases.php script must start by confirming the presence of the SessionData cookie; if the cookie is found, the checking code saves the value – the session identifier – in a global PHP variable. The purchases script next checks for posted order data – com - puters, books or furniture, depending on the f orm page used to submit the data. If data are received, they will be as an array of product codes. The script appends these to a file. The file is named from the session identifier; it is opened in append mode (which creates the file if it does not already exist). The data values (product codes) are urlencoded before being written (substitution of space by + ; other non-alphabetic characters by %xx escapes). This is not essential in this example, but sometimes helps, as session data might include multi-line text inputs from an H TTP form’s text-area. If the data are urlencoded they can be more easily written and read as sing le one-line transfers. <? include("chkrdir.inc"); // chkrdir.inc will either // set global variable $existingSession to our sessionkey // or, if no session key found, redirect the user. function recordorder($item) { global $fp; $coded = urlencode($item) . "\n"; fwrite($fp,$coded); } function process($data) { if(!isset($data)) return; if(!is_array($data)) return; if(empty($data)) return; foreach($data as $val) recordorder($val); } $computers = $HTTP_POST_VARS["computers"]; $books = $HTTP_POST_VARS["books"]; $furniture = $HTTP_POST_VARS["furniture"]; // Create file name based on session, open in append mode $filename = "./orders/" . $existingSession; $fp = fopen($filename, "a"); // Process any data received from a form process($computers); process($books); process($furniture); fclose($fp); ?> <html><head><title>Continue shopping or checkout</title></head> <body bgcolor=white><h2>Order recorded</h2><p> You may continue shopping or proceed to checkout. State 245 <ul> <li><a href="computers.php">Computers</a> <li><a href="checkout.php">Checkout</a> </ul><hr> <p>Want to work for us? <p><a href=jobs.html>Visit our vacancies page</a> </body></html> A fairly high proportion of visitors to commercial web sites start filling a shopping basket with speculative purchases but n ever proceed to final checkout. The result is a lot of abandoned session files. If you are running a site like this, you will need a regular chron job that sweeps through your orders directory deleting all files that haven’t been used for six hours or so. Cookies are the most convenient of the mechanisms for preserving client state. Unfor - tunately, they cannot be relied on. The user of a browser can at any time choose to delete all existing cookies. Many users run their browsers with support for cookies disabled (estimates of cookie-less customers go as high as 20 per cent). Commercial sites that wish to handle cookie-less customers require an alternative approach to saving state. You cannot use hidden fields in forms because these are not sufficiently flexible. You cannot place cookies on the client browser, because your client is paranoid. But somehow, you must place at least a session key in the response pages that you send, and have some reliable mechanism fo r getting the browser to return th is session key. What data always pass back and forth between client and web server? Really, the only data that are always passed are the URLs for the pages in your <a href= > links and <form action= > tags. If you are going to hide a session key somewhere, it is going to have to be inside these U RLs. This is the basis of the ‘URL rewriting’ scheme fo r main- taining client state. URL rewriting is a relatively tedious operatio n; you must change every link that occurs anywhere in a page that you return to a client. Each URL is modified by the inclusion of the session key. With URL rewriting, client state is again preserved on the server host, either in database tables or session files. The session key relates the client to the saved da ta. This key is just an alphanumeric string like the value for a SessionData cookie. The string gets embedded in the URLs. There are a variety of ways that you can do this embedding; it depends on how you intend to remove the session key when processing a request returned by the client. The simplest approach is to append the session key as a query string to every URL. So where your original page was: <ul> <li><a href="computers.php">Computers</a> <li><a href="checkout.php">Checkout</a> </ul><hr> 246 PHP4 you will n eed something like: $tag = "?SessionData=" . $token; ?> <html><head> </head> <body> <ul> <li><a href=computers.php<? print $tag ?> >Computers</a> <li><a href=books.php<? print $tag ?> >Books</a> <li><a href=furniture.php<? print $tag ?> >Furniture</a> <br> <li><a href=checkout.php<? print $tag ?> >Checkout</a> </ul> which will produce an HTML link like: <li><a href=computers.php?SessionData=b492ea45b089c1143754180d7107291c> Computers</a> The browser would record this information in the ‘query string’ (you can have a query string even when you are ‘posting’ data) from where it could be accessed by your program: <? unset($token); $qstr=$HTTP_SERVER_VARS['QUERY_STRING']; if(preg_match( "/SessionData=([0123456789abcdef]{32})/",$qstr,$matches)) { $token = $matches[1]; } if(!isset($token)){ srand((double)microtime()*100000); $token = md5(uniqid(rand())); } $tag = "?SessionData=" . $token; The code is using a Perl-style regular expression match on the query string. The expres - sion specifies a sequence of exactly 32 hexadecimal digits following the string SessionData=; these are in parenthesized match group. (The preg_match function stores details of its matches in the $matches array: match[0] holds the entire string matched, match[1] holds the first selected component, etc.) State 247 [...]... javac SqrtServlet.java Finally, you must create the file tomcat/webapps/demo /WEB- INF /web. xml This should contain the following deployment description: 268 Java Servlets myservlet SqrtServlet... current Web Research and report on this topic This page intentionally left blank 7 Java Servlets This chapter introduces ‘servlets’ Servlets form the basis of Java web server technologies You can write your own servlets to handle web requests, or you can use Java Server Pages that are converted automatically into servlets These servlet examples begin the move to more elaborate web sites Simple web applications... this demo directory, create a file ‘formpage.html’ with the static HTML web page listed above The main directory associated with a web application, tomcat/webapps/demo in this example, must contain a WEB- INF subdirectory This WEB- INF subdirectory holds: G web. xml This file contains a specification of deployment parameters for the web application G lib This optional subdirectory contains any special libraries... CHAR(9) NOT NULL, VARCHAR(16) NOT NULL, number(4), number(4), number(4), 250 PHP4 mark3 number(4), mark4 number(4), mark5 number(4), CONSTRAINT identifier_pkey PRIMARY KEY(identifier) ); INSERT INTO MarksFile VALUES ('u987 654 32', 'r6Yj*8', 1, 6, 5, 7, -1, -1 ); INSERT INTO MarksFile VALUES ('u984 456 62', 'tE38-hhhg', 2, 5, 9, 6, 15, -1 ); This table should be defined along with at least thirty invented... tomcat/conf /server. xml configuration file (the ‘Connectors’ section at the end of the file) Use of a single shared Tomcat system leads to other problems, such as problems over file permissions and with the server itself (sometimes, the server will have to be restarted after a new web application is installed in the webapps directory; this is very inconvenient when many students must share a single server) ... that are defined for a specific web application The java source files can be included but are not required (During development, you would normally include the java source files; when the application was completed, you would move the source to some other location.) For this example, you need to create the directories tomcat/webapps/demo /WEB- INF and tomcat/webapps/demo /WEB- INF/classes The Java code shown... different classes of user 7.1 Servlet overview Servlets (server- side applications) were conceived as a Java-based alternative to CGI scripting Basically, a servlet was to be an instance of a class that could handle HTTP ‘get’ and ‘post’ requests A web server that supported servlets was to be similar to Apache combined with mod-Perl or mod-PHP The standard web server would handle requests for static pages and... ServletContext object for each separate web application ( webapps war file or expanded webapps subdirectory) All the servlets and JSPs that are defined in a web application share the same context object A servlet can obtain a reference to its ServletContext through the GenericServlet.getServletContext method The ServletContext object provides access to information like the server software identifier, and has... action by the web server You can, for example, have something like the following in your script file: http://www.acme.com.bv/ . number(4), mark4 number(4), mark5 number(4), CONSTRAINT identifier_pkey PRIMARY KEY(identifier) ); INSERT INTO MarksFile VALUES ('u987 654 32', 'r6Yj*8', 1, 6, 5, 7, -1, -1 ); INSERT. 'r6Yj*8', 1, 6, 5, 7, -1, -1 ); INSERT INTO MarksFile VALUES ('u984 456 62', 'tE38-hhhg', 2, 5, 9, 6, 15, -1 ); This table should be defined along with at least thirty invented. the current database system and want a web- based interface. The following specification is provided: The system is to be accessed via a web page (or group of web pages) that allow submis - sion

Ngày đăng: 14/08/2014, 12:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan