Anything 2 Share All - Tips Make money online-Phim-video clip-wallpage-software-picture!

Share for all tip, tut, free picture, film, video clip, wallpage, software, etc...

Core PHP Programming - Part II: Functional Reference

Chapter 8. Browser I/O
Topics in This Chapter
If you are experienced in traditional application development, you may be challenged by the unique characteristics of a stateless operating environment. Your script can't sit in a loop and get input from the user until the quit button is clicked. Although there are ways to force the preservation of state—that is, a collection of variables for each user—I encourage you to work within PHP's world. You may come to find what at first were limitations are refreshing opportunities.
8.1 Pregenerated Variables
Before executing a script, PHP creates a set of variables available in a superglobal namespace. They are available inside functions and classes without any extra declaration.

_COOKIE
The _COOKIE variable is an array of cookies sent from the browser to the server. The keys in the array are names of cookies.

_ENV
The _ENV variable is an array of environment variables that existed when the script began. The keys in the array are the names of the environment variables.

_FILES
The _FILES array (Table 8.1) contains information about uploaded files. The keys to the array are the names of the form variables. Each value is an array of information about each file. See Chapter 7 for a discussion of file uploads.
Table 8.1. Elements of _FILES Array
Element
Description
error
The error message, if any, associated with the uploaded file.
name
The name of the uploaded file as supplied by the uploading browser.
size
The size in bytes of the uploaded file.
tmp_name
The path in the local file system to the uploaded file.
type
The MIME type of the uploaded file, provided by the browser.

_GET
The _GET array contains values for all fields passed using the GET method. Keys in this array are the names of the variables passed in the request.

GLOBALS
The GLOBALS array contains every variable in the global scope.

php_errormsg
This variable holds a string describing the last error if track_errors is turned on. It's overwritten with each error.

_POST
The _POST array contains values for all fields passed using the POST method. Keys in this array are the names of the variables passed in the request.

_REQUEST
The _REQUEST array combines the contents of _GET, _POST, _COOKIES, and _FILES. In the case of variables with identical names, PHP overwrites entries according to the variables_order directive in php.ini.

_SERVER
The _SERVER array contains information describing the server and its environment. The following list of elements may appear in the _SERVER array, depending on the Web server or if the script is run from a shell.

argc
If run from the command line, PHP will place an integer in this variable representing the number of arguments passed.

argv
If run from the command line, PHP will set this variable with an array. Each element of the array represents one argument passed. When running within a Web server, PHP places the query string in this variable.

DOCUMENT_ROOT
This value contains the path to document root. A typical value for Apache is /usr/local/apache/htdocs.

GATEWAY_INTERFACE
This value describes the version of the Common Gateway Interface (CGI) used by the Web server.

HTTP_ACCEPT
This value mirrors the Accept header sent by the Web server. It is a comma-delimited list of MIME types.

HTTP_ACCEPT_CHARSET
This value mirrors the Accept-Charset header sent by the Web server.

HTTP_ACCEPT_ENCODING
This value mirrors the Accept-Encoding header sent by the Web server.

HTTP_ACCEPT_LANGUAGE
This value mirrors the Accept-Language header sent by the Web server.

HTTP_CONNECTION
This value mirrors the Connection header sent by the Web server.

HTTP_HOST
This value mirrors the Host header sent by the Web server.

HTTP_REFERER
This value mirrors the Referer header sent by the browser.

HTTP_USER_AGENT
This value mirrors the User-Agent header sent by the browser.

PATH_TRANSLATED
This value is the path to the requested PHP script.

PHP_AUTH_PW
This value is the password sent by the browser.

PHP_AUTH_TYPE
This value describes the authentication type.

PHP_AUTH_USER
This value is the user name sent by the browser.

PHP_SELF
This value is the path to the requested script relative to the document root.

QUERY_STRING
This value is the complete query string.

REMOTE_ADDR
This value is the IP address of the browser.

REMOTE_PORT
This value is the port on the browser's machine used for receiving data from the server.

REQUEST_METHOD
This value describes the method used in the request by the browser. It may contain GET, HEAD, POST, or PUT.

REQUEST_URI
This value is the Universal Resource Identifier (URI) requested by the browser. Of the information that appears in a browser's location box, it excludes only the transport protocol and server name.

SCRIPT_FILENAME
This value is the path in the server's local filesystem to the requested script.

SCRIPT_NAME
This value is the external path to the requested script.

SERVER_ADMIN
This value is the email address of the Web server's administrator.

SERVER_NAME
This value is the domain name of the server.

SERVER_PORT
This value is the port on which the server listens for requests.

SERVER_PROTOCOL
This value contains a description of the version of HTTP used by the server.

SERVER_SIGNATURE
 
This value is a description of the server.

SERVER_SOFTWARE
This value describes the Web server software.

_SESSION
The _SESSION array contains variables placed in PHP's built-in sessions.
8.2 Pregenerated Constants

DEFAULT_INCLUDE_PATH
This constant contains the paths used by include, include_once, require, and require_once.

__CLASS__
This constant returns the name of the class in which the executing code is. It is an empty string when used outside a class.

E_ALL
This constant represents error messages of all levels.

E_COMPILE_ERROR
This constant represents an error encountered when the Zend Engine attempts to compile the page.

E_COMPILE_WARNING
This constant represents a problem encountered by the Zend Engine that doesn't halt compilation.

E_CORE_ERROR
This constant represents an error generated by PHP's core.

E_CORE_WARNING
This constant represents a warning generated by PHP's core.

E_ERROR
This constant represents an error encountered by a PHP function that halts execution.

E_NOTICE
This constant represents a possible error condition reported by a function.

E_PARSE
This constant represents an error generated by PHP's parser.

E_USER_ERROR
This constant represents an error generated by trigger_error.

E_USER_NOTICE
This constant represents a notice generated by trigger_error.

E_USER_WARNING
This constant represents a warning generated by trigger_error.

E_WARNING
This constant represents a warning generated by a PHP function. Warnings don't halt script execution.

__FILE__
This constant holds the full path to the executing script.

__FUNCTION__
This constant holds the name of the function in which it is viewed.

__LINE__
This constant holds the line number in the executing script.

PEAR_EXTENSION_DIR
This constant holds the path where loadable extensions are kept according to PEAR. By default, PEAR sets this to PHP_EXTENSION_DIR, but it may be overridden.

PEAR_INSTALL_DIR
This constant holds the path to the PEAR library, which is usually /usr/local/lib/php.

PHP_BINDIR
This constant holds the path to the PHP command-line executable.

PHP_CONFIG_FILE_PATH
This constant holds the path to the configuration file, php.ini.

PHP_DATADIR
This constant holds a path to a directory for read-only architecture independent data files used by PHP. A typical value for this constant is /usr/local/share. At the time of writing, PHP's core doesn't use this constant.

PHP_EXTENSION_DIR
This constant holds the default path to loadable extensions.

PHP_LIBDIR
This constant holds the path to PHP's library of code. In addition to PEAR, there are several other general-purpose functions and classes for your use.

PHP_LOCALSTATEDIR
This constant holds a path to data files that PHP may need to modify while running. It's usually set to /usr/local/var.

PHP_OS
This constant holds a string describing the operating system. It's no more descriptive than "Linux."

PHP_OUTPUT_HANDLER_CONT
This constant is used as a flag for the status value returned by ob_get_status. If this bit is set, output buffering has begun and the buffer has been flushed.

PHP_OUTPUT_HANDLER_END
This constant is used as a flag for the status value returned by ob_get_status. If this bit is set, output buffering has ended.

PHP_OUTPUT_HANDLER_START
This constant is used as a flag for the status value returned by ob_get_status. If this bit is set, output buffering has begun.

PHP_SYSCONFDIR
This constant holds the path to files that pertain to the configuration of the server.

PHP_VERSION
This constant holds a string representing the version of PHP. This is the same value returned by php_version. It's common to treat this value as a double in order to enforce a certain version of PHP in a script. See Listing 8.1.
Listing 8.1 Example of testing PHP's version
<?php
if(PHP_VERSION < 5.0)
{
print('This script requires PHP 5 or better.');
exit();
}
?>


8.3 Sending Text to the Browser


Any text outside PHP tags is automatically sent to the browser. This is as you would expect. Chapter 26 deals with the decision to send text via a PHP function. PHP offers three functions that simply send text to the browser: echo, print, and printf.





echo string first, string second, …, string last


The echo function (Listing 8.2) sends any number of parameters, separated by commas, to the browser. Each will be converted to a string and printed with no space between them. Unlike most other PHP functions, the echo function does not require parentheses. In fact, echo is more of a statement than a function.


Listing 8.2 echo


<?php
echo "First string", 2, 3.4, "last string";
?>



flush()


As text is sent to the browser via functions like print and echo, it may be stored in a memory buffer and written out only when the buffer fills. The flush function (Listing 8.3) attempts to force the buffer to be dumped to the browser immediately. Since the Web server ultimately controls communication with the browser, the flush may not be effective.


PHP provides another layer of output buffering, as described later in this chapter.


Listing 8.3 flush


<?php
//simulate long calculation
//flush output buffer with each step
for($n=0; $n<5; $n++)
{
print("Calculating...<br>\n");
flush();
sleep(3);
}
print("Finished!<br>\n");
?>



print(string output)


The output argument of print (Listing 8.4) is sent to the browser. Like echo, print does not require parentheses.


Listing 8.4 print


<?php
print("hello world!<br>\n");
?>



printf(string format, …)


The printf function (Listing 8.5) converts and outputs arguments to the browser based on a format string. The format string contains codes, listed in Table 8.2, for different data types. These codes begin with a percentage sign, %, and end with a letter that determines the type of data. The codes match up with a list of values that follow the format string in the argument list. Any text outside these codes will be sent unchanged to the browser.


Listing 8.5 printf


<?php
printf("%-10s %5d %05.5f <br>\n", "a string", 10, 3.14);
?>



Table 8.2. printf Type Specifiers


Type Specifier


Description


d


Integer, decimal notation.


o


Integer, octal notation.


x, X


Integer, hexadecimal notation. x will use lowercase letters; X will use uppercase letters.


b


Integer, binary notation.


c


Character specified by integer ASCII code. See Appendix B for a complete list of ASCII codes.


s


String.


f


Double.


e


Double, using scientific notation such as 1.2e3.


%


Print a percentage sign. This does not require a matching argument.


You also have the option of placing characters between the % and the type specifier that control how the data is formatted. Immediately following the % you may place any number of flags. These flags control padding and alignment. They are listed in Table 8.3.





Table 8.3. printf Flags


Flag


Description


-


Align text to the left.


space


Pad output with spaces. This is the default padding character.


0


Pad output with zeros.


' plus any character


Pad output with the character.


After any flags, you may specify a minimum field length. The converted output will be printed in a field at least this wide, longer if necessary. If the output is shorter than the minimum width, it will be padded with a character, a space by default. The padding will normally be placed to the left but, if the - flag is present, padding will be to the right.


Next, you may specify a precision. It must start with a period to separate it from the minimum field length. For strings, the precision is taken to mean a maximum field length. For doubles, the precision is the number of digits that appear after the decimal point. Precision has no meaning for integers.





vprintf(string format, array values)


The vprintf function operates similarly to printf, except that values for format codes are passed in an array.


8.4 Output Buffering


The output buffering commands add a layer of buffering controlled by PHP in addition to whatever buffering the Web server uses. Some performance penalty may be incurred by adding another layer of buffering, but you may decide the greater control you have is worth the price.


When ob_start is called, all output by functions such as print and echo is held back in a buffer, a large area of memory. The contents of the buffer may be sent to the browser using ob_end_flush, or it may be thrown away using ob_end_clean. As you recall from Chapter 7, headers cannot be sent after the first content is sent. Therefore, these functions allow you to avoid errors created by sending headers after content.





ob_clean()


This function erases the contents of the output buffer but does not end output buffering. Following content will accumulate in the buffer.





ob_end_clean()


The ob_end_clean function halts output buffering and eliminates the contents of the buffer. Nothing is sent to the browser.





ob_end_flush()


The ob_end_flush function halts output buffering and sends the contents of the buffer to the browser.





ob_flush()


The ob_flush function sends the contents of the buffer to the browser and erases the buffer.





string ob_get_clean()


The ob_get_clean function returns the contents of the buffer and then empties the buffer. This is exactly what you'd get if you called ob_getcontents and then ob_clean.





string ob_get_flush()


The ob_get_flush function returns the contents of the buffer, sends the buffer out the browser, and then empties the buffer. This is exactly what you'd get if you called ob_getcontents and then ob_flush.





string ob_get_contents()


The ob_get_contents function returns the contents of the output buffer.





integer ob_get_length()


This function returns the number of bytes in the output buffer.





integer ob_get_level()


The ob_get_level function returns the level of output buffer nesting. Each call to ob_start begins a new output buffer nested in the outer output buffer. Outside any call to ob_start, this function returns 1.





array ob_get_status(boolean full)


The ob_get_status function returns an array describing the current output buffering status. By default, it returns an associative array with the following elements: level, type, status, name, del. If the full argument is set to TRUE, the return value is an array indexed by nesting level. At the time of writing, this function was still in an experimental stage.





ob_gzhandler(string buffer, integer mode)


The ob_gzhandler function returns the given buffer after compressing it with the gzip algorithm. It's meant to be used as a handler for ob_start.





ob_iconv_handler(string buffer, integer mode)


The ob_iconv_handler function converts text from internal to external character encoding. It's meant to be used as a handler for ob_start. This handler becomes available with the iconv extension.


You can set the character set used by this handler with iconv_set_encoding. You can get the current character set with iconv_get_encoding. You can encode individual strings with iconv.





ob_implicit_flush(boolean on)


This ob_implicit_flush function causes PHP to flush the buffer after every instruction that creates output.





array ob_list_handlers()


The ob_list_handlers function returns an array of handlers available.





ob_start(string callback)


The ob_start function (Listing 8.6) begins output buffering. All text sent by print and similar functions is saved in a buffer. It will not be sent to the browser until ob_end_flush is called. The buffer will also be flushed when the script ends.


The optional callback argument allows you pass all output through your own function. The function should accept a string and return a string.


Listing 8.6 ob_start


<?php
//begin output buffering
ob_start();
?>
<html>
<head>
<title>ob_start</title>
</head>
<body>
<?php
print("At this point ");
print(strlen(ob_get_contents()));
print(" characters are in the buffer.<br>\n");
?>
</body>
</html>
<?php
//add a test header
header("X-note: COREPHP");

//dump the contents
ob_end_flush();
?>




8.5 Session Handling


The functions in this section work with the session-handling capabilities of PHP. This functionality takes some inspiration from session handling in other technologies, such as Microsoft ASP and PHPLIB. The original vision was one of global variables registered as part of a session that persist with each page load. PHP has moved away from global variables created by the core, and I find it prudent to present these functions in that spirit. I recommend the use of _SESSION rather than turning on register_globals. This leads you toward compact, simple code. Chapter 7 discusses the purpose and use of sessions.


Sessions are managed by passing a cookie with a unique value between the server and the browser. This cookie indexes an entry in a systemwide session cache. All values in _SESSION are written into the cache when a script completes. PHP restores the contents of _SESSION on the next request. You may start a session manually with session_start, or you can configure PHP to automatically start sessions with the session.auto_start directive in php.ini.


Listing 8.7 creates a session and initializes it with three variables. The script increments a counter with each request, which proves that PHP is keeping the counter value in the session and updating after the script finishes.


Listing 8.7 Session variables


<?php
//start session
session_start();

//initialize a set of session variables
if(!isset($_SESSION['a']))
{
print("Initializing Session<br>");

$_SESSION['a'] = 'Session Var A';
$_SESSION['b'] = 123.45;
$_SESSION['c'] = 0;
}

//update session with access count
$_SESSION['c']++;

print("Access count: " . $_SESSION['c'] . "<br>");

print("Session Dump: " . session_encode() . "<br>");
?>


As sessions use cookies, keep in mind that cookies are matched to specific domains. You may find that sessions created for www1.yourdomain.com are lost when a browser moves to www2.yourdomain.com. You can cope with this in many cases by editing php.ini or using session_set_cookie_params.





boolean output_add_rewrite_var(string name, string value)


The output_add_rewrite_var function adds a variable and its value to the registry of variables added to all URLs. The session handler uses this functionality to add the session identifier to anchor tags you send to the browser.





boolean output_reset_rewrite_vars()


The output_reset_rewrite_vars function erases the registry of variables added to all URLs.





integer session_cache_expire(integer minutes)


The session_cache_expire function returns the number of minutes a session is allowed to remain idle before it expires and the system removes it. Optionally, you may provide a new expiration value. By default, sessions expire after 180 minutes.





string session_cache_limiter(string limiter)


The session_cache_limiter function returns the method for limiting caching of generated pages by browsers. The optional argument allows you to change the limiter. By default, the session system uses the nocache setting, which prevents most browsers from keeping a page in the cache.


PHP's sessions handling assumes that pages requiring session identifiers will contain data that immediately expires. It's a reasonable assumption, but it's not always true. This function allows you to override the setting in php.ini. Table 8.4 shows the four choices for limiters and the HTTP headers they produce. November 19, 1981, is simply a date in the past that forces browsers to keep a page out the cache; 10800 is the number of seconds in 180 minutes and may vary depending on the value set with session_cache_expire. The expiration time given by the public limiter is the current time.





Table 8.4. Session Cache Limiters


Limiter


HTTP Headers Sent


nocache





[View full width]


Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
graphics/ccc.gif, post-check=0, pre-check=0
Pragma: no-cache


private


Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=10800, pre-check=10800


private_no_expire


Cache-Control: private, max-age=10800, pre-check=10800


public


Expires: Mon, 23 Jun 2003 19:32:00 GMT
Cache-Control: public, max-age=10800


Refer to the HTTP/1.1 specification <http://www.w3.org/Protocols/rfc2068/rfc2068> to better understand the headers in Table 8.4.





boolean session_decode(string code)


Use session_decode to read encoded session data and set the values of global variables in the session. This happens automatically when you start a session with session_start.





boolean session_destroy()


The session_destroy function eliminates all the data stored in the session. It does not destroy any global variables associated with the session, however.





string session_encode()


The session_encode function returns a string that contains encoded information about the current session.





array session_get_cookie_params()


The session_get_cookie_params function returns an array describing the session's cookie. The returned array contains the following keys: domain, lifetime, path, secure.





string session_id(string id)


Use session_id to get the value of the session identifier. If you wish to change the session identifier, supply the optional id argument. If you do, take care to do so before calling session_start. The default session handler accepts only letters and numbers in session identifiers.





boolean session_is_registered(string name)


The session_is_registered function returns TRUE if the specified variable is registered with the session. Note that this function expects the name of the variable, not the variable itself. Instead of using this function, check for an entry in _SESSION.





string session_module_name(string name)


The session_module_name function returns the name of the module that handles session duties. This is the same value set by the session.save_handler directive inside php.ini. You can change the module name if you supply the optional name argument. The default module is named files. If you compile PHP using the --with-mm configuration, you can set the session module to mm. This module uses shared memory for storing sessions.


If you wish to implement your own handler in PHP, see the session_set_save_handler function.





string session_name(string name)


The session_name function returns the current name for the session variable. The session may be renamed with the optional name argument. This name is used as the name of the cookie that contains the session identifier. It's also used for the back-up GET variable. If you wish to override the name of the session defined in php.ini, you must do so prior to registering any variables or starting the session.





session_readonly()


This function reads in the session data without locking it against writing from other processes.





boolean session_regenerate_id()


The session_regenerate_id function makes a new session identifier for the current session.





boolean session_register(…)


The session_register function accepts any number of arguments, each of which may be a string or an array. Each argument names a global variable that will be attached to the session. Arrays passed as arguments will be traversed for elements. You can even pass multidimensional arrays. Each registered variable that is set when the script ends will be serialized and written into the session information. When the user returns with a later request, the variables will be restored.


Note that this function expects the name of the variable as a string, not the variable itself. Because this function works on global variables, it isn't as interesting as it once was. You are encouraged to set values in _SESSION directly.





string session_save_path(string path)


The session_save_path function returns the path in the file system used to save serialized session information. This is /tmp by default. The optional path argument will change the path. Keep in mind that the permissions for this directory must include read/write access for the Web server.





session_set_cookie_params(integer lifetime, string path, string domain, bool secure)


The session_set_cookie_params function sets the four parameters used for session cookies. You are required to supply the lifetime only.





session_set_save_handler(string open, string close, string read, string write, string destroy, string garbage)


The session_set_save_handler function allows you to implement an alternative method for handling sessions. Each argument is the name of a function for handling a certain aspect of the session-handling process. See Table 8.5. You can implement these as standalone functions or as class methods. If you choose the latter, as I have in Listing 8.8, you must pass the method names as two-element arrays. The first element should reference an object or class. The second element names the method. If you wish to use static methods, pass the name of the class. If you wish to use an object, pass the reference to the object as the first element, as I have done below.





Table 8.5. Functions for Use with session_set_save_handler


Function


Arguments


Description


open


string path, string name


Begins the session.


close


none


Ends the session.


read


string id


Returns the encoded session data.


write


string id, data


Writes encoded session data.


destroy


none


Removes session from data store.


garbage


integer lifetime


Cleans up stale sessions.


Listing 8.8 Session save handler


<?php
class mySession
{
//prefix with which to mark session files
var $mark;

//path for storing session files
var $path;

//name of session cookie
var $name;


function mySession($mark='mySession_')
{
$this->mark = $mark;
}

function getFilePath($id)
{
return($this->path . '/' . $this->mark . $id);
}

function open($path, $name)
{
$this->path = $path;
$this->name = $name;

return(TRUE);
}

function close()
{
return(TRUE);
}

function read($id)
{
if($fp = @fopen(getFilePath($id), "r"))
{
return(fread($fp,
filesize($this->getFilePath($id))));
}
else
{
return("");
}
}

function write($id, $data)
{
if($fp = @fopen($this->getFilePath($id), "w"))
{
return(fwrite($fp, $data));
}
else
{
return(FALSE);
}
}

function destroy($id)
{
return(@unlink($this->getFilePath($id)));
}

function garbage($lifetime)
{
$d = dir($this->path);

while($f = $d->read())
{
//file begins with mark and it's too old
if((strpos($f, $this->mark) == 0) AND
(time() > (fileatime($f) + $lifetime)))
{
unlink("$this->path/$f");
}

}
$d->close();
return(TRUE);
}
}

$s = new mySession();

session_set_save_handler(
array($s, 'open'),
array($s, 'close'),
array($s, 'read'),
array($s, 'write'),
array($s, 'destroy'),
array($s, 'garbage')
);

//start session
session_start();

//initialize a set of session variables
if(!isset($_SESSION['a']))
{
print("Initializing Session<br>");

$_SESSION['a'] = 'Session Var A';
$_SESSION['b'] = 123.45;
$_SESSION['c'] = 0;
}

//update session with access count
$_SESSION['c']++;

print("Access count: " . $_SESSION['c'] . "<br>");

print("Session Dump: " . session_encode() . "<br>");
?>



boolean session_start()


Use session_start to activate a session. If no session exists, one will be created. Since this involves sending a cookie, you must call session_start before sending any text to the browser. You can avoid using this function by configuring PHP to automatically start sessions with each request. This is done with the session.auto_start directive in php.ini. Once you start a session, the contents of the _SESSION array are preserved for the session user.





boolean session_unregister(string name)


Use session_unregister to remove a global variable from the session. It will not be saved with the session when the script ends. Instead of using this function, remove the appropriate entry from the _SESSION array.





session_unset()


The session_unset function clears all session variables from _SESSION.





session_write_close()


This function immediately writes the session to save handler. Ordinarily, PHP will write session variables when output to the browser finishes, making this function unnecessary. If you have simultaneous connections using the same session, as you would with an HTML frameset, you may improve throughput by closing sessions manually. Otherwise, each request will block until the locks on the session are released. This has the visual affect of loading each frame, one at a time.


8.6 HTTP Headers


HTTP headers are special commands sent between the browser and Web server before the browser receives any content. Some of the headers let the server know which file the browser wants. Others may instruct the browser about the type of file it will soon send. To learn more about headers, refer to the HTTP specification, originally described in RFC 1945 and currently described in RFC 2616. It and other documents may be found at the W3C site, which has a section devoted to the HTTP protocol <http://www.w3.org/Protocols/>. For an overview of how headers work with PHP, turn back to Chapter 7.





boolean header(string http_header, boolean replace, integer response)


The header function (Listing 8.9) sends an HTTP header to the browser. Unless you use the output buffering described earlier in this chapter, header must be called before any output is sent to the browser. You may wish to turn back to the description of HTTP connections in Chapter 7. Many different kinds of headers may be sent. Perhaps the most common is a location header, which redirects the browser to another URI.


Each time you call header, the HTTP is added to a list that's dumped to the browser when the first output is sent to the browser. The headers are sent in the same order you created them. Setting a header a second time will replace the previous value unless you set the optional second argument to FALSE, in which case PHP will send both headers.


The optional third argument sets the HTTP response code returned by the server.


PHP treats two header cases specially. The first is when you send the response header. This is the first line returned by a Web server. PHP detects this by looking for HTTP/ at the beginning of the string you pass to header. PHP will always send this header first.


The other special case concerns the Location header. PHP will change the response code to 302 to match Location headers unless you set the response header manually to a value that begins with 3.


Headers are also used to send cookies, but PHP's setcookie function is better suited for this purpose.


One common trick the header function provides is sending a user to another page, as demonstrated in the example below. Another is to force the browser to either download the file or display it in an OLE container. This is done by setting the Content-type header, which PHP defaults to text/html. Sending a value of application/octet-stream will cause most browsers to prompt the user for where to save the file. You can also use other MIME types to get the browser to run a helper application. For example, if you use application/ vnd.ms-excel, a Windows machine with Microsoft Excel installed will launch Excel in an OLE container inside the browser window. In this case you don't need to send an actual Excel file. A simple tab-delimited file will be interpreted correctly.


Listing 8.9 header


<?php
// redirect request to another address
header("Location: http://www.leonatkinson.com/");
?>



boolean setcookie(string name, string value, integer expire, string path, string domain, integer secure)


Use setcookie (Listing 8.10) to set a cookie to the browser. Cookies are sent as headers during an HTTP connection. Since cookie headers are more complex than other headers, it is nice to have a function specifically for sending cookies. Keep in mind that all headers must be sent prior to any content. Also, calling setcookie does not create a PHP variable until the cookie is set back by the browser on the next page load.


If setcookie is called with only the name argument, the cookie will be deleted from the browser's cookie database. Otherwise, a cookie will be created on the client browser with the name and value given.


The optional expire argument sets a time when the cookie will automatically be deleted by the browser. This takes the form of seconds since January 1, 1970. PHP converts this into Greenwich Mean Time and the proper form for the Set-Cookie header. If the expire argument is omitted, the browser will delete the cookie when the session ends. Usually, this means when the browser application is shut down.


The path and domain arguments are used by the browser to determine whether to send the cookie. The hostname of the Web server is compared to the domain. If it is left empty, the complete hostname of the server setting the cookie is used. The path is matched against the beginning of the path on the server to the document. The cookie specification requires that domains contain two periods. This is to prevent scripts that get sent to every top-level domain (.com, .edu, .net). It also prevents a domain value of leonatkinson.com. Just remember to add a leading dot.


The secure argument is used to tell the browser to send the cookie only over secure connections that use Secure Socket Layers. Use a value of 1 to denote a secure cookie.


Like other headers, those created by the setcookie function are pushed onto a stack, which causes them to be sent in reverse order. If you set the same cookie more than once, the first call to setcookie will be executed last. Most likely, this isn't what you intend. Keep track of the value you intend to set as the value of the cookie, and call setcookie once.


Netscape, which developed cookies, offers more information about them in a document titled "Persistent Client State: HTTP Cookies." Its URL is <http://developer.netscape.com/docs/manuals/communicator/jsguide4/cookies.htm>.


How do you know if a browser accepts your cookie? The only way is to send one and test that it is returned on the next page request.


Listing 8.10 setcookie


<?php
/*
** mark this site as being visited
** for the next 24 hours
*/
setcookie("HasVisitedLast24Hours", "Yes", time()+86400);
?>

0 comments:

Post a Comment

Thank you for reading this article. Do you have suggestions or how to do better, please leave a few words to share with everyone. Please note you, these comments are not calculated suggestions or help build each other progress will be deleted without notice. In addition, you necessarily have a Google account, or networks are listed below (including OpenID) will be a review. The comment is absolutely not carry political content, reactionary, chửi pool, for that reason, you must have one of the accounts in question.Sorry for the inconvenience. Wish love your home more and more visitors. Content type in Vietnamese will be marked with clear easy to account for more than sympathy.

Donation

Search By Your Customize

Custom Search

Subscription

Enter your email address:

Delivered by FeedBurner

Labels

Sponsored Links

Asd by any program
Free Website Hosting affiliate_link adf.ly - shorten links and earn money!