Apache Server 2 Bible Hungry Minds phần 7 ppt

80 290 0
Apache Server 2 Bible Hungry Minds phần 7 ppt

Đ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

450 Part III ✦ Running Web Applications </table> </body> </html> 8. As you can see, the embedded PHP script is parsed out and the end user on the browser side does not even know which database or which user/password was used to produce this page. If you have a lot of pages where you use the same MySQL database to display data elements using various queries, you should use the include() function to simplify your code management tasks. For example, Listing 15-12 shows a modified version of simple_query.php script that includes the include() function. Listing 15-12: simple_query2.php <?php include(‘/usr/local/apache/secrets/mysql/header.inc’); ?> <html> <head><title>Simple Query Script</title></head> <body> <table border=1> <tr><th>Name</th> <th>Password</th></tr> <?php $sth = mysql_query(“SELECT * from $table”, $dbh); while ($myRow = mysql_fetch_row($sth)) { printf(“<tr><td>%s</td><td>%s</td></tr>”, $myRow[0], $myRow[1]); } ?> </table> </body> </html> When the above script is accessed via the Web the resulting page is same as the one produced by simple_query.php. However, here the script users a header file that contains the database connection script as shown below: <?php $host = ‘localhost’; $user = ‘httpd’; $passwd = ‘no1secret’; $database_name = ‘www; g4821-2 ch15.F 2/22/02 10:29 AM Page 450 451 Chapter 15 ✦ PHP and Apache $table = ‘users’; $dbh = mysql_connect($host, $user, $passwd); mysql_select_db($database_name, $dbh); ?> By removing this script from each page that uses it, you make it very easy to change the host name, username, password, database name, and table name. If you have 20 pages that use the same database and table, you can now update the password once in the header.inc file and be done! Securing PHP include files If you use include files, as shown in the last section, to store username, password, and other information, such as database host name, database name, and table names, that are not to be seen by users, make sure you keep the include files in a safe directory where Web browsers cannot browse them. The best place is outside the document tree of the Web site. If the document root is /www/mysite/htdocs, then create a directory called /www/mysite/secrets/mysql and keep the include files there. If you must create the include files inside the document root, disallow Web browsing by using the following configuration in httpd.conf: <Directory /path/to/include_files> <Limit> order deny,allow deny from all </Limit> </Directory> Don’t forget to replace /path/to/include_files with the path to the real directory of the include files. If you keep your include files all over the Web site, you can still disable Web access to them by using the following configuration segment in httpd.conf: <Files ~ “\.inc$”> Order allow,deny Deny from all </Files> This will only work if you always make sure all your PHP include files are named with the extension .inc. Authenticating users with PHP and MySQL You can use a PHP script to authenticate users via MySQL database. Listing 15-13 shows a simple script that uses a MySQL database to authenticate users. Note g4821-2 ch15.F 2/22/02 10:29 AM Page 451 452 Part III ✦ Running Web Applications Listing 15-13: auth.php <?php ob_start(); include(‘/usr/local/apache/htdocs/mysql/header.inc’); function show_dialog($realm = “Restricted Section”) { header(“WWW-Authenticate: Basic realm=’$realm’”); header(‘HTTP/1.0 401 Unauthorized’); echo ‘Authorization Required.’; exit; } if ((!isset($PHP_AUTH_USER)) || (!isset($PHP_AUTH_PW))) { show_challenge(); } else if ((isset($PHP_AUTH_USER)) && (isset($PHP_AUTH_PW))){ $sth = mysql_query(“SELECT 1 from $table WHERE username = ‘$PHP_AUTH_USER’ and passwd = ‘$PHP_AUTH_PW’”, $dbh); $success = mysql_fetch_row($sth); if ($success[0] == ‘’) { show_challenge(); } else { echo “<P>You’re authorized!</p>”; # Do something here } } ob_end_flush(); ?> When this script is requested, it uses the isset() function checks whether two variables called $PHP_AUTH_USER and $PHP_AUTH_PW are set. These two variables are set by PHP if a user has entered a username and password in response to a basic authentication challenge. g4821-2 ch15.F 2/22/02 10:29 AM Page 452 453 Chapter 15 ✦ PHP and Apache Because the first-time user has not yet seen the authentication challenge dialog box, these two variables are empty and the show_challenge() function is called. This function simply prints out the Basic HTTP authentication headers, which forces the Web browser to display a dialog box asking the user to enter a username and a password. When the user enters a username and password pair, the pair is sent via the authentication response header to the Apache server, which is seen by PHP. PHP then sets the $PHP_AUTH_USER and $PHP_AUTH_PW variables accordingly. After the script is called again automatically in the authentication response request, the script uses the MySQL database to verify whether or not the username/password pair exists. If the user credentials (username/password pair) are valid, the script displays the message “You’re authorized!” and terminates. On the other hand, if the credentials are invalid, the authentication challenge is reissued. Notice that the include(‘/usr/local/apache/htdocs/mysql/header.inc’) call hides all the database connectivity code. The header.inc file is shown below: <?php $host = ‘localhost’; $user = ‘httpd’; $passwd = ‘no1secret’; $database_name = ‘www; $table = ‘users’; $dbh = mysql_connect($host, $user, $passwd); mysql_select_db($database_name, $dbh); ?> Here the MySQL database called www is on localhost and can be accessed by a user called httpd using no1secret as the password. The www database has a table called users. You can change these parameters as desired to connect to the appropriate database on the local host or a remote MySQL database server. This include file opens a connection to the named database on the appropriate host and returns a connection handle called $dbh, which is available to auth.php. In the auth.php script, notice this line: $sth = mysql_query(“SELECT 1 from $table WHERE username = ‘$PHP_AUTH_USER’ and passwd = ‘$PHP_AUTH_PW’”, $dbh); This line performs an SQL query that returns 1 if user-supplied credentials (stored in $PHP_AUTH_USER and $PHP_AUTH_PW automatically by PHP) matches a username and passwd field, respectively, in the (users) table. g4821-2 ch15.F 2/22/02 10:29 AM Page 453 454 Part III ✦ Running Web Applications If your users table has a different field name for username or passwd, make sure you change the query statement to reflect those names. The $success = mysql_fetch_row($sth) statement returns an array called $success, which should have returned the value 1 as the first element in $success[0] if the query is successful. Or else the element is undefined. By using the first element $success[0], the decision to display (or not to display) the authentication challenge by using show_challenge() is made. After a user is authenticated, this simple auth.php script does not do anything other than print a message stating that the user was successfully authenticated. You can, of course, have the script do much more than that. For example, you can redirect the user to a protected subdirectory by using the Header(“Location: /path/to/subdirectory”); . ✦✦✦ Note g4821-2 ch15.F 2/22/02 10:29 AM Page 454 Using Perl with Apache A primary goal of the Apache/Perl integration project was to bring the full power of the Perl programming language into the Apache server. This resulted in the development of mod_perl, which you can compile and link together with Apache and Perl to provide an object-oriented Perl interface to the server’s C language API. This enables Perl programmers to write Apache modules in Perl. An Apache-Perl module may step in during the handler, header parser, URI translation, authentication, authorization, access, type check, fix-up, logger, and cleanup stages of a request. The mod_perl module is widely used with Apache to create dynamic contents. mod_perl is a very efficient way to use Perl with Apache; you no longer have to run Perl-based CGI scripts, which are slow, resource consuming, and often not suitable for sites that receive a large number of simultaneous requests per second. This chapter discusses how to compile, install, and configure Apache for mod_perl, how to run your old CGI scripts by using mod_perl, and how to develop mod_perl modules to take advantage of the Apache API. Compiling and Installing mod_perl Here is how you can download, compile and install mod_perl on your system: 1. Download the latest version of the mod_perl source into the /usr/local/src directory from the http://perl. apache.org/dist site or from an official mirror site. Please make sure you read the installation notes and README files in the source distribution before proceeding with the compilation. The steps discussed below might change with newer version of mod_perl and/or newer Apache. Caution 16 16 CHAPTER ✦✦✦✦ In This Chapter Compiling and installing mod_perl Running CGI scripts via mod_perl Writing a mod_perl module Preloading modules Sharing memory Writing a database application in mod_perl ✦✦✦✦ g4821-2 ch16.F 2/22/02 10:29 AM Page 455 456 Part III ✦ Running Web Applications 2. As root, extract the mod_perl source distribution by using the tar xvzf mod_perl-version.tar.gz command. This section assumes that you extracted the Apache source distribution into /usr/local/src. 3. Change to the /usr/local/src/mod_perl-version directory and run: Perl Makefile.PL APACHE_SRC= /apache-version \ DO_HTTPD=1 \ USE_APACHE=1 \ PERL_MARK_WHERE=1 \ EVERYTHING=1 Don’t forget to change /apache-version with the appropriate pathname. 4. Run the make && make test && make install command to compile, test, and install the mod_perl library into the Apache source distribution. 5. Change to the Apache source distribution directory and run make install to compile and install Apache with mod_perl support. 6. Start the newly compiled Apache server by using the /usr/local/apache/ bin/apachectl start command. If you are already running a previous version of Apache server, use the /usr/local/apache/bin/apachectl stop command to stop it and then run the start command to relaunch the new server with mod_perl capabilities. If you’re on a Unix system, you can run the lynx -dump -head http://localhost/ command to dump the headers that the server displays. If mod_perl is installed properly, you will see mod_perl/version information in the header information. Running CGI Scripts by Using mod_perl Because CGI scripts are slow and take up more resources under heavy load, in an ideal world you will not run CGI scripts when mod_perl is working on your system. However, the reality is that system administrators are busy people and porting something that is working already is often ignored because other, more serious, work is awaiting elsewhere. Fortunately, mod_perl enables you to run your CGI scripts by using a default mod_perl module called Apache::Registry.pm. So, you can run your CGI scripts under mod_perl immediately. Here is how. 1. In httpd.conf file, create an alias called /apps/ to point to your CGI script directory by adding the following line: Alias /apps/ “/www/mysite/cgi-bin” Make sure you change the /www/mysite/cgi-bin to whatever is the appropriate CGI script directory on your system. 2. Tell Apache to load the Apache::Registry module during startup by adding the following line in httpd.conf: PerlModule Apache::Registry g4821-2 ch16.F 2/22/02 10:29 AM Page 456 457 Chapter 16 ✦ Using Perl with Apache 3. Tell Apache to run all scripts via Apache::Registry for the /apps/ directory by adding the following configuration segment in httpd.conf: <Location /apps> SetHandler perl-script PerlHandler Apache::Registry Options ExecCGI </Location> 4. Restart the Apache server by using the /usr/local/apache/bin/apachectl restart command. 5. Access a CGI script using a Web browser by using http://your_server_ name/apps/script_name . If you have a ScriptAlias directive setup to point /cgi-bin/ to /www/mysite/cgi-bin (or whatever the CGI script directory on your system is called), then you can access the CGI scripts as “CGI” script by using http:// your_server_name /cgi-bin/script_name, or you can access the same script with mod_perl by using http://your_server_name/ apps/script_name . The latter has the advantage of not spawning a new CGI process for each request, enabling it to perform faster. Note that the mod_perl environment variable can distinguish how a script is being run (CGI or mod_perl). Consider, for example, the following code segment: if ($ENV{MOD_PERL} ne ‘’) { # Run as mod_perl script as a native mod_perl # module or Apache::Registry run script } else { # CGI Script being run via mod_cgi as a # separate process } The above conditional statement detects how a script is being run. The scripts in the apps directory will be run via the Apache::Registry module. This means that you can remove the mod_cgi module from your system completely by recompiling Apache with disable-module=cgi option. Don’t Reinvent the Wheel Before you go about writing a cool mod_perl module for your Web server, consider looking around on CPAN for existing modules that might solve your problem. As of this writing, there are about 500 mod_perl-specific Perl modules on CPAN. You can view the available modules on CPAN as follows: 1. Run the perl -MCPAN -e shell command. 2. At the cpan> prompt, enter i /Apache/. You should receive a list of all the available Apache-related modules. g4821-2 ch16.F 2/22/02 10:29 AM Page 457 458 Part III ✦ Running Web Applications Creating mod_perl Module By Using the Perl API for Apache When you installed mod_perl on your system you also installed a very powerful Perl Application Programming Interface (API) for Apache. By using this API, you can develop mod_perl scripts that take advantage of mod_perl in a “native” way. Although you can run CGI scripts by using mod_perl, they are not designed for mod_perl that uses the Perl API and therefore cannot take full advantage of power of mod_perl. The following material shows how you can develop scripts that are written using the Perl API for Apache to take full advantage of the mod_perl module. A native mod_perl script is written as a Perl module with the following architecture: package MODULE_NAME; sub handler { # use the Apache API provided request # object to do something useful } sub module_method_1 { # do something useful } sub module_method_2 { # do something useful } sub module_method_3 { # do something useful } sub module_method_N { # do something useful } 1; Here, the module file starts with a package name. The name of the package must match the name of the module file. For example, if you name your package (that is, module) as: Package MyModule; then you must name the file that contains this module as MyModule.pm. Typically, Perl module files are kept in a subdirectory within the list of directories pointed to by the @INC array. You can find out which directories are pointed to by @INC by running the following command from the command-line: perl -le ‘print join(“\n”, @INC)’ You might see output similar to the following: /usr/lib/perl5/5.6.0/i386-linux /usr/lib/perl5/5.6.0 /usr/lib/perl5/site_perl/5.6.0/i386-linux /usr/lib/perl5/site_perl/5.6.0 /usr/lib/perl5/site_perl . g4821-2 ch16.F 2/22/02 10:29 AM Page 458 459 Chapter 16 ✦ Using Perl with Apache If you use a Perl version other than 5.6.0, then the paths should reflect that. When mod_perl encounters the first request for a module, it looks at the directories to locate the module. Because it is not a good idea to mix your custom module(s) with the standard modules provided with Perl and mod_perl, you should create a new directory called Development in /usr/lib/perl5/site_perl and keep your custom modules in that directory. This enables mod_perl to find your custom modules in the /usr/lib/perl5/site_perl/Development directory when they are needed. Also, make sure you set the file permissions for this new directory so that Apache user (set via User directive in httpd.conf) can read this directory and the files within it. You can use the following commands to create the new directory and to set the file permissions: mkdir -p /usr/lib/perl5/site_perl/Development chown -R Apache_User:Apache_Group /usr/lib/perl5/site_perl/Development chmod -R 750 /usr/lib/perl5/site_perl/Develpoment Don’t forget to change Apache_User and Apache_Group to the appropriate user and group names as set in httpd.conf, by using User and Group directives, respectively. After you have created a directory, you can create a simple module as shown in Listing 16-1. Save this module as /usr/lib/perl5/site_perl/ Develpoment/SimpleAPI.pm . Listing 16-1: A Simple Example of a Perl API for Apache package Development::SimpleAPI; use strict; use Apache::Constants qw(:common); my $callCounter = 0; sub handler { my $r = shift; $r->send_http_header(‘text/html’); print <<HTML_DOC; <html> <head><title>Simple Perl API Example Script</title> </head> <body> <h1>Simple Perl API Example Script</h1> <hr> Continued g4821-2 ch16.F 2/22/02 10:29 AM Page 459 [...]... contains the properties shown in Listing 17- 1 473 g4 821 -2 ch 17. F 474 2/ 22/ 02 10 :29 AM Page 474 Part III ✦ Running Web Applications Listing 17- 1: Default Tomcat (worker) properties workers.tomcat_home=c:\jakarta-tomcat workers.java_home=c:\jdk1 .2. 2 ps=\ worker.list=ajp 12, ajp13 worker.ajp 12. port=80 07 worker.ajp 12. host=localhost worker.ajp 12. type=ajp 12 worker.ajp 12. lbfactor=1 worker.ajp13.port=8009 worker.ajp13.host=localhost... how to write ASP scripts in Perl visit the ASP Web site at www .apache- asp.org ✦ ✦ ✦ 4 67 g4 821 -2 ch16.F 2/ 22/ 02 10 :29 AM Page 468 g4 821 -2 ch 17. F 2/ 22/ 02 10 :29 AM Page 469 17 C H A P T E R Running Java Servlets and JSP Pages with Tomcat ✦ ✦ ✦ ✦ In This Chapter Installing JDK Installing Tomcat Installing mod_jk module for Apache O ver the last few years, Java has become the leading Web-application platform... servlets, JSP, and even Tomcat itself By using the Java Security Manager, you can control what each application can or cannot do Table 17 -2 shows the types of permissions you can set 477 g4 821 -2 ch 17. F 478 2/ 22/ 02 10 :29 AM Page 478 Part III ✦ Running Web Applications Table 17 -2 Java Security Manager Permission Types Permission Type Meaning java.util.PropertyPermission Controls read/write access to JVM properties... default properties file defines an ajp 12 worker, ajp13 worker, a jni worker, and a lb worker The differences among these worker types are shown in Table 17- 1 g4 821 -2 ch 17. F 2/ 22/ 02 10 :29 AM Page 475 Chapter 17 ✦ Running Java Servlets and JSP Pages with Tomcat Table 17- 1 Differences Among Types of Workers Worker Type Description ajp 12 This worker uses the ajpv 12 protocol to forward requests to out-ofprocess... /usr/java/jdk1.3.0_ 02) So, this should be set as follows: workers.java_home=/usr/java/jdk1.3.0_ 02 The next line tells Tomcat what separator to use for separating directory elements The default value \ works for Windows system because on Windows platforms directory names are separated by using \ On UNIX systems, it should be / So, set this line as shown here: ps=/ 475 g4 821 -2 ch 17. F 2/ 22/ 02 10 :29 AM Page 477 Chapter 17. .. JAVA_HOME=/usr/java/jdkversion For example: export JAVA_HOME=/usr/java/jdk1.3.0_ 02 Enter echo $JAVA_HOME in your shell prompt to determine whether this environment variable is set If you just added it to the bashrc file, then you must run source ~/.bashrc to export the variable 471 g4 821 -2 ch 17. F 4 72 2 /22 / 02 10 :29 AM Page 4 72 Part III ✦ Running Web Applications Note If you use a different shell, such... script called /usr/bin/tomcatctl, which is shown in Listing 17 -2 This saves a lot of typing and helps avoid mistyping errors g4 821 -2 ch 17. F 2/ 22/ 02 10:30 AM Page 485 Chapter 17 ✦ Running Java Servlets and JSP Pages with Tomcat Listing 17 -2: /usr/bin/tomcatctl #!/bin/sh # Change the version number below if your # JDK is not 1.3.0_ 02 # VERSION=1.3.0_ 02 export JAVA_HOME=/usr/java/jdk$VERSION export PATH=${PATH}:${JAVA_HOME}/bin... Tomcat’s HTTP service ✦ ✦ ✦ ✦ g4 821 -2 ch 17. F 470 2/ 22/ 02 10 :29 AM Page 470 Part III ✦ Running Web Applications Tomcat also implements Java Server Page (JSP) support that allows you to place Java code in HTML pages with jsp extensions Pages with such extensions are parsed by the servlet very similarly to how PHP or ASP pages are parsed This makes JSP very similar to PHP or Active Server Pages (ASP) — with... no more buffer overrun to worry about g4 821 -2 ch 17. F 2/ 22/ 02 10 :29 AM Page 471 Chapter 17 ✦ Running Java Servlets and JSP Pages with Tomcat Installing Tomcat To install Tomcat on your server you need to have a Java Run-time Environment (JRE), and if you plan on developing servlets then you will also need Java Development Kit (JDK) Also, to use Tomcat with Apache you need the mod_jk module In this... external startup script, you do not need the PerlModule Apache: :Status line Instead, load the Apache: :Status module in the startup script before any other module 465 g4 821 -2 ch16.F 466 2/ 22/ 02 10 :29 AM Page 466 Part III ✦ Running Web Applications 3 Restart the Apache server and access information on loaded mod_perl modules by using http://your _server_ name/perl-status This page displays a list of options . ASP scripts in Perl visit the ASP Web site at www .apache- asp.org. ✦✦✦ Note g4 821 -2 ch16.F 2/ 22/ 02 10 :29 AM Page 4 67 g4 821 -2 ch16.F 2/ 22/ 02 10 :29 AM Page 468 Running Java Servlets and JSP Pages. system. 2. Tell Apache to load the Apache: :Registry module during startup by adding the following line in httpd.conf: PerlModule Apache: :Registry g4 821 -2 ch16.F 2/ 22/ 02 10 :29 AM Page 456 4 57 Chapter. among the Apache child processes. For example: PerlRequire /usr/local /apache/ apps/startup.pl g4 821 -2 ch16.F 2/ 22/ 02 10 :29 AM Page 464 465 Chapter 16 ✦ Using Perl with Apache This tells Apache require

Ngày đăng: 14/08/2014, 06:22

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

Tài liệu liên quan