Archive for the ‘PHP cookbook’ Category

Redirecting to a Different Location

Friday, March 14th, 2008

Problem
You want to automatically send a user to a new URL. For example,after successfully
saving form data, you want to redirect a user to a page that confirms the data.

Solution
Before any output is printed,use header() to send a Location header with the new
URL:
header('Location: http://www.example.com/');

Discussion
If you want to pass variables to the new page,you can include them in the query
string of the URL:
header('Location: http://www.example.com/?monkey=turtle');
The URL that you are redirecting a user to is retrieved with GET. You can’t redirect
someone to retrieve a URL via POST. You can,however,send other headers along
with the Location header. This is especially useful with the Window-target header,
which indicates a particular named frame or window in which to load the new URL:
header('Window-target: main');
header('Location: http://www.example.com/');
The redirect URL must include the protocol and hostname; it can’t just be a pathname:
// Good Redirect
header('Location: http://www.example.com/catalog/food/pemmican.php');
// Bad Redirect
header('Location: /catalog/food/pemmican.php');

Deleting Cookies

Thursday, March 13th, 2008

Problem
You want to delete a cookie so a browser doesn’t send it back to the server.

Solution
Call setcookie() with no value for the cookie and an expiration time in the past:

setcookie('flavor','',time()-86400);

Discussion
It’s a good idea to make the expiration time a few hours or an entire day in the past,
in case your server and the user’s computer have unsynchronized clocks. For example,
if your server thinks it’s 3:06 P.M. and a user’s computer thinks it’s 3:02 P.M.,a
cookie with an expiration time of 3:05 P.M. isn’t deleted by that user’s computer
even though the time is in the past for the server.
The call to setcookie() that deletes a cookie has to have the same arguments (except
for value and time) that the call to setcookie() that set the cookie did,so include the
path, domain, and secure flag if necessary.

Reading Cookie Values

Wednesday, March 12th, 2008

Problem
You want to read the value of a cookie that’s been previously set.
Solution
Look in the $_COOKIE superglobal array:

if (isset($_COOKIE['flavor'])) {
print "You ate a $_COOKIE[flavor] cookie.";
}

Discussion
A cookie’s value isn’t available in $_COOKIE during the request in which the cookie is
set. In other words,the setcookie() function doesn’t alter the value of $_COOKIE. On
subsequent requests,however,each cookie is stored in $_COOKIE. If register_globals
is on, cookie values are also assigned to global variables.
When a browser sends a cookie back to the server,it sends only the value. You can’t
access the cookie’s domain,path,expiration time,or secure status through $_COOKIE
because the browser doesn’t send that to the server.
To print the names and values of all cookies sent in a particular request,loop
through the $_COOKIE array:

foreach ($_COOKIE as $cookie_name => $cookie_value) {
print "$cookie_name = $cookie_value<br>";
}

Setting Cookies

Tuesday, March 11th, 2008

Problem
You want to set a cookie.
Solution
Use setcookie():

setcookie('flavor','chocolate chip');

Discussion
Cookies are sent with the HTTP headers,so setcookie() must be called before any
output is generated. You can pass additional arguments to setcookie() to control cookie behavior. The
third argument to setcookie() is an expiration time,expressed as an epoch timestamp.
(more…)

Program: Abusive User Checker

Monday, March 10th, 2008

Shared memory’s speed makes it an ideal way to store data different web server processes need to access frequently when a file or database would be too slow. Example shows the pc_Web_Abuse_Check class,which uses shared memory to track accesses to web pages in order to cut off users that abuse a site by bombarding it with requests.

(more…)

Using HTTP Basic Authentication

Saturday, March 8th, 2008

You want to use PHP to protect parts of your web site with passwords. Instead of
storing the passwords in an external file and letting the web server handle the
authentication, you want the password verification logic to be in a PHP program.

Solution
The $_SERVER[’PHP_AUTH_USER’] and $_SERVER[’PHP_AUTH_PW’] global variables contain
the username and password supplied by the user,if any. To deny access to a
page,send a WWW-Authenticate header identifying the authentication realm as part of
a response with status code 401:

header('WWW-Authenticate: Basic realm="My Website"');
header('HTTP/1.0 401 Unauthorized');
echo "You need to enter a valid username and password.";
exit;

(more…)

Compressing Web Output with gzip

Thursday, March 6th, 2008

You want to send compressed content to browsers that support automatic decompression.

Solution
Add this setting to your php.ini file:

zlib.output_compression=1

Discussion
Browsers tell the server that they can accept compressed responses with the Accept-Encoding header. If a browser sends Accept-Encoding: gzip or Accept-Encoding: deflate,and PHP is built with the zlib extension,the zlib.output_compression configuration directive tells PHP to compress the output with the appropriate algorithm before sending it back to the browser. The browser uncompresses the data before displaying it. You can adjust the compression level with the zlib.output_compression_level configuration directive:

; minimal compression
zlib.output_compression_level=1
; maximal compression
zlib.output_compression_level=9

At higher compression levels,less data needs to be sent from the server to the browser, but more server CPU time must be used to compress the data.

Using a Custom Error Handler

Wednesday, March 5th, 2008

You want to create a custom error handler that lets you control how PHP reports errors.
Solution
To set up your own error function, use set_error_handler():

set_error_handler('pc_error_handler');
function pc_error_handler($errno, $error, $file, $line) {
$message = "[ERROR][$errno][$error][$file:$line]";
error_log($message);
}

Discussion

A custom error handling function can parse errors based on their type and take the appropriate action. See Table 8-2 in Recipe 8.15 for a list of error types. Pass set_error_handler() the name of a function,and PHP forwards all errors to that function. The error handling function can take up to five parameters. The first parameter is the error type,such as 8 for E_NOTICE. The second is the message thrown by the error,such as “Undefined variable: html”. The third and fourth arguments are the name of the file and the line number in which PHP detected the error. The final parameter is an array holding all the variables defined in the current scope and their values.
For example,in this code $html is appended to without first being assigned an initial value: (more…)

Flushing Output to the Browser

Tuesday, March 4th, 2008

You want to force output to be sent to the browser. For example,before doing a
slow database query, you want to give the user a status update.
Solution
Use flush():

print 'Finding identical snowflakes...';
flush();
$sth = $dbh->query('SELECT shape,COUNT(*) AS c FROM snowflakes GROUP BY shape HAVING c > 1');

The flush() function sends all output that PHP has internally buffered to the web
server,but the web server may have internal buffering of its own that delays when
the data reaches the browser. Additionally,some browsers don’t display data immediately
upon receiving it,and some versions of Internet Explorer don’t display a page
until they’ve received at least 256 bytes. To force IE to display content,print blank
spaces at the beginning of the page:

print str_repeat(' ',300);
print 'Finding identical snowflakes...';
flush();
$sth = $dbh->query(
'SELECT shape,COUNT(*) AS c FROM snowflakes GROUP BY shape HAVING c > 1');

See Also documentation on flush()