&
PHP&Apache
Why httpd.conf is your new BFF!
Why httpd.conf is your new BFF!
PHP & Apache
Jeff Jones
AtlantaPHP
February 5th, 2009
Jump by reebs*
Web “Solutions Stacks”
(Thanks Wikipedia!)
LAMP
Linux Apache MySQL PHP
WAMP
Windows Apache MySQL PHP
WIMP
Windows IIS MySQL PHP
LAPP
Linux Apache PostgreSQL PHP
FAPP
FreeBSD Apache PostgreSQL PHP
Common denominator? Apache. “yellow lamp“
Apache Background
Since April 1996 Apache has been the most
popular HTTP server on the World Wide Web.
As of December 2008 Apache served over
51% of all websites.
“Fort Apache by PhillipC”
Apache Software Foundation
From ApacheCon 2007, Atlanta, GA
“ASF by Ted Leung”
Apache HTTP Server
“Geronimo's Camp”
“a patchy server”
Skydiving
“Needs more duct tape”
Full-Featured Web Server
Some Features...
Authentication, Authorization, Environment Variables
& Access Control Log Files
CGI: Dynamic Content w/ CGI Server Side Includes
Configuration Files URL Mapping
Content negotiation URL Rewriting
“Server” by existentist
Apache Configuration
By handjes
Contexts
Server config: Server wide httpd.conf and included files.
VirtualHost: <VirtualHost></VirtualHost>
Directory: Directory,DirectoryMatch,Files,FilesMatch
.htaccess: Per directory config files.
“PCI Slot” by Ryan
Apache Modules
#httpd.conf
httpd.conf
#Comment
#Directive
Include /usr/local/apache/conf/ssl.conf
Include /usr/local/apache/conf/vhosts/
Include /usr/local/apache/conf/a/*.conf
#Block Directive
<IfModule mod_rewrite.c>
RewriteEngine on
</IfModule> “Floppy” by Marcin Wichary
.htaccess
“Apple I & Altair” by Shiny Things
Scope Directives
VirtualHost
Directory / DirectoryMatch
Files / FilesMatch
Location/LocationMatch
“Radiance” by jurvetson
Virtual Host
<VirtualHost 10.1.2.3>
ServerAdmin admin@example.com
DocumentRoot /www/example.com
ServerName example.com
ErrorLog exlogs/error_log
TransferLog exlogs/access_log
</VirtualHost>
“CNN Hologram” by Hard Seat Sleeper
Directory
<Directory />
</Directory>
<Directory /home/*>
</Directory>
“Dewey” by emdot
DirectoryMatch
<DirectoryMatch "^/www/.*/[0-9]{3}">
</DirectoryMatch>
Files
<Files admin.cgi>
Require group admin
</Files>
“Filed away..” by tpholland
FilesMatch
<FilesMatch "\.(gif|jpe?g|png)$">
</FilesMatch>
“Alphabetical”
Location
“Lost” by w00kie
LocationMatch
“Little Blue Pins”
mod_core
“Earth Core”
ErrorDocument “Coat Check Fail”
#Output a customized message.
ErrorDocument 403 "No Access”
#Redirect to a local URL-path.
ErrorDocument 404 /errors/404.php
#Redirect to an external URL.
ErrorDocument 500 http://example.com/5.php
404 for pretty urls: Bad Idea!
(Hello mod_rewrite!)
ErrorDocument 404 index.php “Irony”
KeepAlive “Zombie Jeff”
KeepAlive on
KeepAliveTimeout 2
MaxKeepAliveRequests 100
TimeOut
TimeOut 300
“Hang up.” by Robert Brook
UseCanonicalName
ServerName example.com
UseCanonicalName On
Request: www.example.com/secure
Redirects to: example.com/secure/
By Greyhorn
mod_php
● php_value / php_flag
● php_admin_value / php_admin_flag
● Contexts: All, Perdir, System.
“php is cool” by Sara Golemon
PHP Config Contexts
● PHP_INI_ALL
● PHP_INI_PERDIR
● PHP_INI_SYSTEM
php_value
“Gratuitous Bacon”
php_value name value
php_flag
php_flag name off|on “Wave the flags”
php_admin_(flag|value)
php_admin_flag safe_mode on
“The Flag”
How is this useful?
“Mixer Detail”
Set PHP Configuration per directory, uri, or file.
Prepend & Append
auto_prepend_file header.php
auto_append_file footer.php
auto_prepend_file none
“My Stapler”
include_path
include_path=".;/php/includes"
include_path=".;C:/php/includes"
“Gahuti Trail” by Jeff Jones
Turn that crap off!
php_flag magic_quotes_gpc off
php_flag register_globals off “Sausage King”
Output Buffering
php_flag output_buffering on
php_value output_handler ob_tidyhandler
php_flag implicit_flushoff
“AOL Coasters”
PHP Error Logging
log_errors stderr
php_value error_log /path/to/error.log
“Telex Machine”
Display Errors
display_errors off
“Don't you feel secure?”
mod_env
“Capitol Reef National Park” by W. Staudt
● Access via $_ENV[] or getenv();
SetEnv
SetEnv webenv production
SetEnv webenv testing
SetEnv scriptdebug true
“Programmable Thermostat”
mod_mime
“Mime Typing...”
AddType/Handler
AddType image/gif .gif
AddHandler php-script .php
#Not the best way:
AddType application/x-httpd-php .html
#better
AddHandler php-script .html
“Juggling Practice”
ForceType/SetHandler
ForceType application/x-httpd-php
<Files *.php>
SetHandler php-script
</Files>
<Location /images>
ForceType image/jpeg
</Location>
mod_negotiation
URI: foo
URI: foo.jpeg
Content-type: image/jpeg; qs=0.8
URI: foo.gif
Content-type: image/gif; qs=0.5
URI: foo.txt
Content-type: text/plain; qs=0.01
“Tough Negotiations”
MultiViews
Set as part of directory options
MultiViews tracks down the best file.
<Directory /usr/local/www>
Options Indexes MultiViews
</Directory>
foo
foo.html.es
foo.html.en.gz “Sniffin'”
mod_rewrite
http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html
http://httpd.apache.org/docs/1.3/misc/rewriteguide.html
The Definitive Guide to Apache mod_rewrite
by Rich Bowen
http://apress.com/book/view/9781590595619 “The Vortex”
Rewrite Rules
RewriteEngine On
RewriteBase /
RewriteCond /home/www/$1.php -f
RewriteRule ^(/?[^/\.]+)/$ /$1.php
“Tapping a pencil”
RewriteRule Flags
RewriteEngine On
RewriteCond %{HTTP_HOST} ^.*website2.com
RewriteRule ^/?$ /website2.php [QSA, E=thedomain:website2,NC,L]
QSA = Query String Append
E = Set Environment Variables
NC=No Case
L=Last
Rewrites & Redirects
RewriteCond %{HTTP_HOST} !=www.domain.com
RewriteRule (.*) http://www.domain.com/$1 [R=301,L]
Front Controller
The Front Controller Pattern is a
software design pattern listed in
several pattern catalogs. The pattern
relates to the design of web
applications. It "provides a
centralized entry point for handling
requests."
Source: Wikipedia
mod_auth
Other Auth & Related Modules
● mod_access
● Access control based on client hostname or IP address
● mod_auth_dbm
● User authentication using DBM files
● mod_auth_db
● User authentication using Berkeley DB files
● mod_auth_anon Apache 1.1 and up
● Anonymous user access to authenticated areas
● mod_digest
● MD5 authentication
Basic Auth
.htpasswd .htgroups
username:md5(password) phpers: Tetraboy bdole
Tetraboy:crypt(password)
bramsey:md5(WildGarlic)
bdole:crypt(lbp)
AuthType Basic
AuthName "Apache Logins"
AuthUserFile /usr/apasswd/.htpasswd
AuthGroupFile /usr/apasswd/.htgroups
#Examples
Require user Tetraboy bramsey bdole
Require group phpers
Require valid-user
PHP HTTP Auth
$_SERVER['PHP_AUTH_USER'] & $_SERVER['PHP_AUTH_PW']
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>Your pass:{$_SERVER['PHP_AUTH_PW']}.</p>";
}
?>
mod_headers
Header set|append|add header value
Header unset header
ErrorHeader
Setting Headers
<Files *.css>
SetHandler php-script
Header Set Content-type “text/css”
</Files>
PHP's Apache Extension
● apache_child_terminate — Terminate apache process after this request
● apache_get_modules — Get a list of loaded Apache modules
● apache_get_version — Fetch Apache version
● apache_getenv — Get an Apache subprocess_env variable
● apache_lookup_uri — Perform a partial request on a URI, returns info.
● apache_note — Get and set apache request notes
● apache_request_headers — Fetch all HTTP request headers
● apache_reset_timeout — Reset the Apache write timer
● apache_response_headers — Fetch all HTTP response headers
● apache_setenv — Set an Apache subprocess_env variable
● ascii2ebcdic — Translate string from ASCII to EBCDIC
● ebcdic2ascii — Translate string from EBCDIC to ASCII
● getallheaders — Fetch all HTTP request headers
“Trilions Served”
● virtual — Perform an Apache sub-request
apache_child_terminate();
“Terminator
apache_lookup_uri
<?php
info = apache_lookup_uri('index.php?var=value');
var_dump($info);
?> stdClass Object
(
[status] => 200
[the_request] => GET /dir/file.php HTTP/1.1
[method] => GET
[mtime] => 0
[clength] => 0
[chunked] => 0
[content_type] => application/x-httpd-php
[no_cache] => 0
[no_local_copy] => 1
[unparsed_uri] => /dir/index.php?var=value
[uri] => /dir/index.php
[filename] => /home/htdocs/dir/index.php
[args] => var=value
[allowed] => 0
[sent_bodyct] => 0
[bytes_sent] => 0
[request_time] => 1074282764
)
Apache HTTP Headers
<?php
apache_request_headers();
apache_response_headers();
?>
Tip of Iceberg
● There are around 100 modules for Apache 1.3.x
● There are about 300 modules for Apache 2.x
● mod_rewrite can do amazing stuff with URIs
● Apache can be expanded with custom modules!
“Ice Breaker”
“Books by Bowen”
Apache is a Web Server.
●
Don't rewrite a web server in PHP.
●
Unless you really have to.
More info?
● http://httpd.apache.org/
● irc.freenode.net #apache
● http://planetapache.org/
● http://apache-cookbook.com/
“Theo Thinks”
Questions?
● Why is the sky blue?
● Why is the moon white?
● Why is the grass green?
● Where do babies come from?
“Downtown ATL”