1. Trang chủ
  2. » Công Nghệ Thông Tin

Secure PHP Development- P151 pptx

5 148 0
Tài liệu đã được kiểm tra trùng lặp

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 5
Dung lượng 106,51 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Caching PHP contents using the jpcache cache The jpcachepackage is a lightweight page caching solution for PHP that reduces server load as PHP-generated pages are cached on the file syst

Trang 1

Listing 21-5 shows a simple script that enables output buffering using the

ob_start()function, but it also enables gzip-based compression by providing the

ob_gzhandlerparameter to the ob_start() function

Listing 21-5: compress.php

<?php define(MAX, 100);

ob_start(“ob_gzhandler”);

$output = ‘’;

for($i=0;$i<=MAX;$i++) {

$output = “This is line $i <br>”;

} echo $output;

?>

The following code highlights the extra HTTP headers that are sent when com-pression is enabled:

lynx -head -dump http://www.evoknow.com/ch21/gzip/compress.php HTTP/1.1 200 OK

Server: Apache/2.0.43 (Unix) PHP/4.1.2 Date: Sat, 07 Dec 2002 20:50:47 GMT Connection: close

Content-Encoding: gzip Content-Length: 270 Content-Type: text/html Vary: Accept-Encoding X-Powered-By: PHP/4.1.2

The same script without compression enabled sends the following headers:

lynx -head -dump http://www.evoknow.com/ch21/gzip/compress.php HTTP/1.1 200 OK

Server: Apache/2.0.43 (Unix) PHP/4.1.2 Date: Sat, 07 Dec 2002 20:52:20 GMT Connection: close

Content-Type: text/html X-Powered-By: PHP/4.1.2

Trang 2

Keep in mind that GZIP is only one practical option in improving your code.

Also, the overhead in calling the ZIP function, hit on server RAM, etc., must be carefully weighed.

Caching Your PHP Applications

Using the benchmark and compression techniques described in this chapter, you can identify slow code and rewrite it to execute faster if possible However, another

popular method of enhancing the end user’s experience of “speed” is to use caching

techniques By caching the output of your PHP application or caching the genera-tion of PHP opcode, you can achieve higher performance The following secgenera-tions discuss these caching techniques in detail

Caching PHP contents using the jpcache cache

The jpcachepackage is a lightweight page caching solution for PHP that reduces server load as PHP-generated pages are cached on the file system or database It also uses compression (GZIP content-encoding) and ETag-headers, which can result

in approximately 80 percent bandwidth savings

When a jpcache-enabled page is requested for the first time, it is run as usual and the generated content is cached in a file or database per the jpcache configura-tion The cached data is transmitted for any subsequent requests for a configurable amount of time This means that pages that do not change often on your site can use this caching technique to reduce server load by avoiding running the same script for each request

Configuring jpcache

Download the latest jpcache package from http://www.jpcache.com/ Once downloaded, extract the package under your Web server’s document tree Here is how you configure jpcache for database-based caching:

Although you can configure jpcache for file-based caching, file-based caching requires a centralized file system (using NFS or SAMBA) when multi-ple Web servers are serving your contents in a Web server farm Again, remember the tradeoffs associated with various solutions For example, although NFS and SAMBA improve caching, their overhead also contributes

to slower system functionality.

Trang 3

1 Edit the jpcache.php file to change the $includedirvariable to point to the directory in which you have installed jpcache In the following example,

$includedirpoints to the %DocumentRoot%/ch21/cache/jpcache/ path

// Set the includedir to the jpcache-directory // ORIG: $includedir = “/path/to/jpcache-files”;

$includedir = $_SERVER[‘DOCUMENT_ROOT’]

‘/ch21/cache/jpcache/’;

2 Create a database called jpcache in your MySQL database server If you

want to use an existing database name, skip to the next step

3 Create a table called CACHEDATA in the jpcache database (or your

exist-ing database) usexist-ing script.sql For example:

mysql -u root -p -D jpcache < script.sql

The above command will create CACHEDATA table per script.sql in a data-base called jpcache in localhost If your MySQL datadata-base server is not

localhost, you can use -h hostname option Also, if you are using an exist-ing database replace -D jpcache with -D your_existexist-ing_database name.

4 Edit the jpcache-config.php file to include the following lines:

$JPCACHE_TYPE = “mysql”;

$JPCACHE_TIME = 900;

$JPCACHE_DB_HOST = “localhost”;

$JPCACHE_DB_DATABASE = “jpcache”;

$JPCACHE_DB_USERNAME = “sqluser”;

$JPCACHE_DB_PASSWORD = “passwd”;

$JPCACHE_DB_TABLE = “CACHEDATA”;

$JPCACHE_OPTIMIZE = 1;

Here, the cached data will be stored in a table called CACHEDATA in a database called jpcache in the localhost Access to the database will be allowed using a username called sqluser and the password “passwd”

5 Now create the following test script called test.php:

<?php require “/path/to/jpcache/jpcache.php”;

echo time();

phpinfo();

?>

Make sure that /path/to/jpcachein the require()line points to the appropriate directory in which jpcache.phpis installed

Trang 4

6 Now run this script via a Web browser using http://server/path/

to/jpcache/test.php You should see a page with a timestamp on top

Keep accessing this script by refreshing the request a few times Notice that the timestamp shown as the output does not change This means that caching is working, as the page will be cached for the duration of

$JPCACHE_TIMEspecified in the jpcache-config.php

That’s all that is required to configure jpcache Now you are ready to use it with your existing PHP applications

Deploying jpcache

The jpcache caching should be used only for applications that do not generate their own headers (such as cookies) and are not user-level personalized You should use this caching technique for pages that generate data from a database or external files unless you are comfortable with the lag that results from non-cache hits To use jpcache in your existing PHP application, do the following:

1 Edit your application to include the following lines at the very beginning

of your PHP application:

$cachetimeout=900;

require_once($_SERVER[‘DOCUMENT_ROOT’]

‘/jpcache/jpcache.php’);

The preceding code assumes that jpcache is installed in the %DocumentRoot/

jpcachedirectory If you install it somewhere else, make sure the path reflects the change

2 If you wish to cache the output more or less than every 900 seconds,

change the value of $cachetimeout Setting $cachetimeoutto -1 will disable caching for the current application Setting $cachetimeoutto 0 will enable a cache that does not expire automatically

Caching PHP contents using the PEAR cache

PEAR cache support comes with the PEAR package found at http://pear.php.net For more information about installing PEAR, refer to Chapter 4

PEAR caching can store cached data in files, shared memory, or a database

Because you are already familiar with jpcache as a database-based caching method, here we will use a file as the cache storage This section shows you how a simple PHP script (shown in Listing 21-6) can be converted to use the PEAR output caching feature

Trang 5

Listing 21-6: non_cached.php

<?php echo “This is the contents<P>”;

echo “Time is “ date(‘M-d-Y H:i:s A’, time()) “<BR>”;

?>

To use the PEAR output cache for the preceding PHP script, you need to do the following:

1 Include PEAR in the path of this script using the following:

$PEAR_DIR = $_SERVER[‘DOCUMENT_ROOT’] ‘/pear’ ;

$PATH = $PEAR_DIR;

ini_set( ‘include_path’, ‘:’ $PATH ‘:’

ini_get(‘include_path’));

2 Include the Output.php cache subclass from PEAR using the following:

require_once ‘Cache/Output.php’;

3 Create a cache directory variable as follows:

$cacheDir = ‘/tmp/pear_cache’;

Make sure this directory is writable by the Web server user The caching scheme will write cache data in subdirectories within this directory

4 Create an Output cache object as follows:

$cache = new Cache_Output(‘file’,

array(‘cache_dir’ => $cacheDir) );

The first argument states that we are choosing file-based caching, and the second argument is an associative array with the cache directory path defined as cache_dir

5 Generate a unique cache ID for this page as follows:

$cache_id = $cache->generateID(

array(‘url’ => $REQUEST_URI,

‘post’ => $HTTP_POST_VARS,

‘cookies’ => $HTTP_COOKIE_VARS )

);

Ngày đăng: 07/07/2014, 07:20