[Zend PHP5 Cerification] Lectures -- 5. Web Programming, Web Features

Forms
.GET vs POST
. Form Tokens
. Default Values
. Re-populatingdata

 

 

.superglobalarray

$_GET[]
$_POST[]

WhenYou Don’t Know How Data Is Sent
$_REQUEST[]
filledin using data from different sources in an order specified by asetting in your php.ini(usually, EGPCS, meaning Environment, Get,Post, Cookie and Built-in variableS. Note that $_REQUEST onlycontains cookie, GET and POST information).

The problem withusing this approach is that, technically, you don’t know where thedata comes from. This is a potentially major security issue that youshould be fully aware of. This problemis discussed in more detail inthe Security chapter.

You can create arrays by using arraynotation...
http://example.org/index.php?list=user&order[by]=column&order[dir]=asc
Thereis nothing that stops you from creating URLs that already containquery data—there is no special trick to it, other than the datamust be encoded using a particular mechanism that, in PHP, isprovided by the:

urlencode()

ThePHP interpreter will automatically decode all incoming data for us,so there is no need to execute urldecode() on anything extracted from$_GET.

ManagingFile Uploads 

A filecan be uploaded through a “multi-part” HTTP POST transaction.From the perspective of building your file upload form, this simplymeans that you need to declare it in a slightly different way.

 <formenctype="multipart/form-data" action="index.php"method="post">
<input type="hidden"name="MAX_FILE_SIZE" value="50000" />
<inputname="filedata" type="file" />
<inputtype="submit" value="Send file" />
</form>

Asyou can see, the MAX_FILE_SIZE value is used to define the maximumfile size allowed (in this case, 50,000 bytes); note, however, thatthis restriction is almost entirely meaningless, since it sits on theclient side—since any moderately crafty attacker will be able toset this parameter to an arbitrary value, you can’t count on itpreventing any attempt to overwhelm your system by sending files thatare so large as to deplete its resources.

Youcan limit the amount of data uploaded by a POST operation bymodifying a number of configuration directives, such aspost_max_size, max_input_time and upload_max_filesize.

 Oncea file is uploaded to the server, PHP stores it in a temporarylocation and makes it available to the script that was called by thePOST transaction. It is up to the script to move the file to a safelocation if it so chooses—the temporary copy is automaticallydestroyed when the scriptends.

$_FILES[]

$_FILES['name']
$_FILES['type']
$_FILES['size']
$_FILES['tmp_name']
$_FILES['error']            The error code associated with this file. A value of UPLOAD_ERR_OKindicates a successful transfer, while any other error indicates thatsomething went wrong.

is_uploaded_file()

move_uploaded_file() a call to this function also checkswhether the source file is a valid upload file, so there is no needto call is_uploaded_file() first.

One of the most commonmistakes that developers make when dealing with uploaded files isusing the name element of the file data array as the destination whenmoving it from its temporary location. Because this piece ofinformation is passed by the client, doing so opens up a potentiallycatastrophic security problem in your code. You should, instead,either generate your own file names, or make sure that you filter theinput data properly before using it!

HTTPHeaders
Simple strings in theform key: value, terminated by a newline character. The headers areseparated by the content by an extra newline.

header()
Setcookies manually, using the RFC for the appropriate headers.


theheader() must be called before any other output, including anywhitespace characters outside of PHP tags, as well as all HTML dataand PHP output. If you fail to abide by this rule, two things willhappen: your header will have no effect, and PHP may output anerror.

Note that you may be able to output a header even afteryou have output some data if output buffering is on. Doing so,however, puts your code at the mercy of what is essentially atransparent feature that can be turned on and off at any time and is,therefore, a bad coding practice.

Header();redirects
.Do they work?

Redirection
header("Location:http://phparch.com");
vs
header("Location:
http://phparch.com");
exit();


Tostop browsers from emitting “Do you wish to re-post this form”messages when clicking back after submitting a form, you can use aheader redirection to forward the user to the results page afterprocessing the form.

Otherarbitrary headers
.Headerinjection attacks
.Caching

NoCaching:
               header("Cache-Control:no-cache, must-revalidate");
               header("Expires: Thu, 31May 1984 04:35:00 GMT");
Setexpires in the future:
               $date =gmdate("D, j M Y H:i:s", time() + 2592000); // 30 Days fromnow
               header("Expires: " . $data . " UTC");
              header("Cache-Control: Public");
               header("Pragma:Public");


.Content-Type
.MetaInformation

 

Compression
HTTPsupports the transparent compression and decompression of data intransit during a transaction using the gzip algorithm. Compressionwill make a considerable impact on bandwidth usage—as much as a 90%decrease in file size. However, because it is performed on the fly,it uses up many more resources than a typical request. 

 Thelevel of compression is configurable, with 1 being the leastcompression (thus requiring the least amount of CPU usage) and 9being the most compression (and highest CPU usage). The default is6. 

Turningon compression for any given page is easy, and because the browser’sAccept headers are taken into account, the page is automaticallycompressed for only those users whose browsers can handle thedecompression process:

ob_start("ob_gzhandler");

Placingthis line of code at the top of a page will invoke PHP’s outputbuffering mechanism, and cause it to transparently compress thescript’s output.

You can also enable compression on asite-wide basis by changing a few configuration directives in yourphp.ini file.

zlib.output_compression =on
zlib.output_compression_level = 9

Notice how thisapproach lets you set the compression level. Since these settings canbe turned on and off without changing your code, this is best way ofimplementing compression within your application.

Cookies

.Canbe deleted, manipulated, copied.
.Behavioris inconsistent.


Cookiesallow your applications to store a small amount of textual data(typically, 4-6kB) on a Web client.
There are a number of possibleuses for cookies, although their most common one is maintaining
sessionstate.

Cookies are typically set by the server using aresponse header, and subsequently made available by the client as arequest header.

cookies should always be treated as “tainted”until proven otherwise.

setcookie()
Wrapsthe Header function, sets default values when nothing ispassed.

Should you wish to make a cookie persist betweenbrowser sessions, you will need to provide an expiration date.Expiration dates are provided to setcookie() in the UNIX timestampformat(the number of seconds that have passed since January 1,1970).Remember that a user or their browser settings can remove acookie at any time—therefore, it is unwise to rely on expirationdates too much.

setcookie("hide_menu", "1",time() + 86400);

three more arguments:
path, domain,secure


$_COOKIE[]

Cookievalues must be scalar.

The amount of storage available isseverely limited—therefore, you should keep the amount of data youstore in cookies to a minimum, and use sessions instead.
Rememberthat setting cookies is a two-stage process: first, you send thecookie to the client, which will then send it back to you at the nextrequest. Therefore, the $_COOKIE array will not be populated with newinformation until the next request comes along.

reset thecookie
There is no way to “delete” a cookie—primarilybecause you really have no control over how cookies are stored andmanaged on the client side. You can, however, call setcookie with anempty string.


Sessions

Sessionsare maintained by passing a unique session identifier betweenrequests—typically in a cookie, although it can also be passed informs and GET query arguments.
.Sessions, The safer way tostate.
.Use a cookie that contains a Session ID.
.That SessionID corresponds with a local(ish) data store that contains the user’sinformation.
.The Session ID is the only data that is transmittedto a client, and is also the only thing that identifies them.


PHPhandles sessions transparently through a combination of cookies andURL rewriting, when session.use_trans_sid is turned on in php.ini (itis off by default in PHP5) by generating a unique session ID andusing it track a local data store (by default, a file in the system’stemporary directory) where session data is saved at the end of everyrequest.

Sessions are started in one of two ways. You caneither set PHP to start a new session automatically whenever arequest is received by changing the session.auto_start configurationsetting in your php.ini file. Or explicitly call session_start()at the beginning of each script.

When sessions are startedautomatically, the session is started before your scripts areexecuted; this denies you the opportunity to load your classes beforeyour session data is retrieved, and makes storing objects in thesession impossible.In addition, session_start() must be called beforeany output is sent to the browser, because it will try to set acookie by sending a response header.

In the interest ofsecurity, it is a good idea to follow your call to session_start()with a call to session_regenerate_id() whenever you change a user’sprivileges to prevent “session fixation”attacks.

$_SESSION[]

SessionHijacking and Session Fixation

Conclusion:
Data comes infrom GET or POST, frequently from forms, don’t trust it.
Cookiesare a client side data store.
Sessions use cookies to offer alocalish datastore.
Header allows us to send meta information tothe client.

posted @ 2010-06-29 17:26  DavidHHuan  阅读(452)  评论(0编辑  收藏  举报