15. Advanced PHP-Apache-MySQL - PHP & MySQL Web Development


Published on

Advanced concepts about PHP, Apache and MySQL
Telerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2011/10/11/php-school-academy-meeting
The website and all video materials are in Bulgarian.

This lecture discusses the following topics:

PHP Settings: Modifying PHP settings at runtime, Modifying trough .htaccess
Apache Settings: Virtual Hosts, Modules – mod_rewrite, mod_autoindex, mod_expires, etc
MySQL Settings: Performance

Published in: Education, Technology
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

15. Advanced PHP-Apache-MySQL - PHP & MySQL Web Development

  1. 1. Advanced PHP, Apache and MySQL Advanced SettingsNikolay KostovTechnical Trainerhttp://nikolay.itTelerik Software Academyacademy.telerik.com
  2. 2. Summary PHP Settings  Modifying PHP settings at runtime  Modifying trough .htaccess Apache Settings  Virtual Hosts  Modules – mod_rewrite, mod_autoindex, mod_expires, etc MySQL Settings  Performance
  3. 3. Configuring PHP The php.ini file
  4. 4. PHP Settings PHP settings are in the php.ini file  Set of name=value statements  Location of the file is different across the operating systems and versions  Which php.ini file is loaded can be checked with the phpinfo() function PHP supports add-ons  Most add-ons read their settings from the same file
  5. 5. Code Settings short_open_tags (on or off)  Defines if <? and <?= should be considered PHP opening tags  Will be deprecated, do not turn on asp_tags (on or off)  Defines if <% and %> should be considered PHP open and close tags
  6. 6. File Upload Settings file_uploads (on or off)  Turns PHP file upload handling on and off upload_tmp_dir  Defines the directory where PHP should store the temporary uploaded files upload_max_filesize  Defines the maximum allowed uploaded file size (in megabytes)
  7. 7. Buffer Settings output_buffering (on or off)  Sets whether the entire PHP output should be buffered  Emulates ob_start and ob_end_flush implicit_flush (on or off)  Sets if the buffer should be flushed to the browser automatically after every output block
  8. 8. Other Settings magic_quotes_gpc (on or off)  defines whether data received in $_GET, $_POST, $_COOKIE arrays should be escaped with back slashes  Deprecated, never turn on! register_globals (on or off)  When turned on all data from $_GET, $_POST, etc. arrays is converted to variables  $_GET[name] becomes $name  Deprecated, never turn on!
  9. 9. Changing Configuration Settings at Runtime Use ini_set function to change php.ini settings at runtime <?php ini_set(include_path,c:/php/PEAR); ?> Use ini_getfunction to check a value of php.ini variable <?php echo ini_get(upload_max_filesize); ?> Use phpinfo() function to see the current values of the PHP settings <?php phpinfo() ?>
  10. 10. Configuring Apache The httpd.conf file
  11. 11. Apache Settings Apache settings are defined in the httpd.conf file  Location and name may differ across platforms and Apache versions  Older version read from multiple files  The site-specific settings and module-specific settings are in separate files  Follows syntax close to XML format  Name value pairs sometimes in tags
  12. 12. Prefork vs. Worker Apache has two core modules (versions) – prefork and worker  Different behavior  Prefork is process based, doesnt utilize threads much, better for single/dual core CPU servers  Worker utilizes threaded-architecture – better for multi-core/CPU servers  Some tests say prefork is better, some say worker
  13. 13. Apache Modules Loading a module LoadModule ssl_module modules/mod_ssl.so Using conditional configuration settings: <IfModule dir_module> DirectoryIndex index.php DirectoryIndex index.html </IfModule> Loading mod_php LoadModule php5_module "C:/Program Files/PHP/php5apache2_2.dll"
  14. 14. Connection Settings Timeout (in seconds)  The number of seconds before it sends timeout to a dead connection Keepalive (on or off)  Turns on and off persistent connections MaxKeepAliveRequests  The maximum number of persistent connections allowed KeepAliveTimeout  The number of seconds before closing a dead persistent connection
  15. 15. More Settings Listen  Sets port for apache to listen for connections  Can be repeated with different ports  Usually separated in ports.conf file HostnameLookups (on or off)  If turned on logs the host names of remote clients instead of IP addresses User, Group – set the user and group that apache process should work in
  16. 16. More Settings DirectoryIndex  Sets default file names that should be shown in case directory is requested  Example: DirectoryIndex index.php index.html  If the user requests http://www.example.com/test/ the server will look for index.php and then for index.html in the requested directory
  17. 17. Log Settings ErrorLog  Sets the file apache logs errors to  Can be specified separately for each site LogLevel  Sets the level of logging to the error log  One of debug, info, notice, warn, error, crit LogFormat  Specifies nick names for different log formats  Can be used for site-specific access logs
  18. 18. Virtual Hosts Apache supports multiple sites on the same IP address/port  Specified in VirtualHost directives  Usually virtual hosts are separated in different files  Requires NameVirtualHost directive  Sets the IP address and port on which the apache will receive requests for the name-based virtual hosts  IP and Port can be replaced with * (any)
  19. 19. Example Virtual Host NameVirtualHost *:80 <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example/htdocs ErrorLog /var/www/example/logs/err CustomLog /var/www/example/logs/custom </VirtualHost> ServerName specifies the (domain) name of the virtual host ServerAlias specifies additional names (domains) for this virtual host
  20. 20. VirtualHost Settings DocumentRoot  Sets the root directory for this host  Passed to PHP in the $_SERVER[DOCUMENT_ROOT] variable  Be careful with the ending slash ErrorLog sets the host-specific error log CustomLog sets the location and format for the host access log file
  21. 21. Location Directive The Location directive is used to define URL- specific settings  Settings are directory based  Can be placed in VirtualHost or for server-wide <VirtualHost *:80> … <Location /admin> Require valid-user </Location> </VirtualHost>
  22. 22. Directory Directive <VirtualHost *:80> … <Directory /var/www/includes> Allow from localhost Deny from all </Directory> </VirtualHost> The Directory directive is used to define file system directory settings  Can be defined server-wide or host-specific
  23. 23. Deny and Allow The Deny from, Allow from and Order directives are used to limit access to certain hosts  Deny and Allow values are lists of hosts (space- separated), partial domain names, partial IPs or "all"  The Order directive sets whether deny or allow should be higher priority  Value is "Allow,Deny" or "Deny,Allow"  First is with higher priority, if host is not matched, second in list is used
  24. 24. Deny and Allow – ExamplesAllow from localhostDeny from allOrder Allow, DenyAllow from .net # partial domainDeny from 192.168 # partial IPOrder Deny, AllowAllow from localhost from # deny a networkOrder Deny, AllowAllow from 2001:db8::a00:20ff:fea7:cceaDeny from allOrder Allow, Deny
  25. 25. The Options Directive Sets values of several additional directory- based options  Each option is prefixed with + or – to turn on or off; if no prefix is supplied, on is assumed  ExecCGI – whether CGI scripts execution is allowed in the directory  FollowSymLinks – whether Apache should use only files or can follow symbolic links in the directory
  26. 26. The Options Directive  Indexes – If a URL maps to directory and there is no file that matches the DirectoryIndex directive then mod_autoindex will return page with the list of files in the directory  Turning this on for hosts/locations that do not explicitly require it is considered security risk!<Directory /var/www/docs> Options +Indexes +FollowSymLinks -ExecCGI</Directory
  27. 27. Setting-up a Virtual Host – Example To set-up a virtual host follow the steps: 1. Set your domain name to point to your external IP address For testing you can modify the "hosts file"  /etc/hosts in Linux  C:WINDOWSSystem32driversetc hosts in Linux 2. Add NameVirtualHost and VirtualHost directives in the httpd.conf 3. Restart Apache
  28. 28. Using HTTPS HTTPS is HTTP over SSL/TLS Apache has separate module for handling https Running virtual host over https requires certificate and connection on port 443  In Linux the packages openssl and ssl-cert are necessary too  Apache has automated script for generating certificates – apache2-ssl-certificate
  29. 29. Configuring HTTPS Example of virtual host with SSL <VirtualHost *:443> ServerName phpmyadmin.example.com DocumentRoot /usr/shared/phpmyadmin/ SSLEngine on SSLCertificateFile /etc/apache2/ssl/myadmin.pem </VirtualHost> The SSLEngine directive turns on the SSL security engine SSLCertificateFile supplies valid certificate file  The domain property in the file must match the host name
  30. 30. Configuring HTTPS – Example1. First ensure that httpd-ssl.conf file will be loaded. Put this code in httpd.conf: Include conf/extra/httpd-ssl.conf2. Create a self-signed SSL certificate: openssl genrsa 1024 > host.key openssl req -new -x509 -nodes -sha1 -days 365 -key host.key > host.cert cat host.cert host.key > host.pem3. Define a virtual host on port 443 with SSL engine switched on4. Restart Apache
  31. 31. HTTP Authentication The apache module mod_auth allows the use of HTTP Basic Authentication  Restrict or allow access to certain areas  Requires user and password input  For stronger authentication and scalability use mod_auth_digest or mod_auth_dbm  Usernames and password are stored encrypted in a file
  32. 32. mod_auth directives AuthType  Sets the type of user authentication  Possible values are Basic and Digest AuthName  User-friendly name of the realm that requires authorization  Must be enclosed in quotation marks AuthUserFile  Specifies the file that stores users and passwords
  33. 33. mod_auth directives AuthGroupFile  Specifies the file that stores the groups of users  Groups are simply alias to list of users  Example content of group file: Boss: john pesho Accounting: mara ceca Testers: chocho bobo shusi  Groups cannot be nested or inherited  Never put the user file or groups file in the document tree of the site!
  34. 34. Require Directive Require sets which users/groups are allowed to access the realm  Possible values are: Require user [list of users] Require group [list of groups] Require valid-user
  35. 35. The htpasswd tool Apache comes with a small tool for generating user files named htpasswd  Encrypts the passwords  Usually these files are named .htpasswd // the –c flag means "create a new file" htpasswd –c .htpasswd mara // asks you to supply password // add new user htpasswd .htpasswd john // again asks for password
  36. 36. Authentication – Example<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/ex/htdocs … <Location /admin> AuthType Basic AuthName "Example admin area" AuthUserFile /var/www/ex/.htpasswd </Location></VirtualHost>
  37. 37. Using .htaccess Apache can read additional settings from files in the site document tree  The name of the file is controlled by the AccessFileName server directive  Usually named .htaccess In the .htaccess file can be placed all directives, valid for Location Slows down the Apache  It has to read it on every request
  38. 38. Example .htaccess Options +Indexes AuthType Basic AuthName "test" AuthUserFile ".htpasswd" php_value magic_quotes_gpc off Apache reads all .htaccess files in the directories from the document root up to the requested resource and combines them Can contain mod_rewrite settings Can contain PHP settings with the php_value directive
  39. 39. mod_rewrite mod_rewrite allows rule-based rewriting and redirecting of requests  Example: user requests index.html but the rewrite rules change this to index.php  This is NOT redirecting!  Used to make friendly URLs, rename resources, etc.  Based on regular expressions  Operates on per-server or per-directory context
  40. 40. Rewriting Directives RewriteEngine (on or off) RewriteBase  Sets the base URL for per-directory (.htaccess) rewriting RewriteRule [pattern] [substitution][flags]  If the requested URL matches the pattern it is rewritten with the replacement  Allows using back-references and groups
  41. 41. RewriteRule flags [L] – rewriting should stop and no other rules should be checked [F] – force 403 forbidden response code [G] – force 410 gone response code [R=(code)] – force redirect with response code  User is redirected to the result URL [N] – restart rewriting with the new address [NC] – case insensitive match [C] – chain rule with the next  If not matched, skips the chained rules
  42. 42. URL Rewriting – ExampleRewriteEngine On#rewrite directories to index filesRewriteRule ^(.*)/$ $1/index.html#send all html files to the template engine#so the URLs are friendlyRewriteRule ^(.*).html$ /template.php?page=$1#generate the human validation imageRewriteRule ^captcha.gif$ /captcha_gen.php#stream the videosRewriteRule ^/(.{10}).swf$ /stream.php?vid=$1#rewrite product URLsRewriteRule ^/products/(.*)/(.*).html$ /product.php?category=$1&product=$2
  43. 43. RewriteCond The RewriteCond directive defines a rule condition  Used to match HTTP headers, connection and request properties, server settings, system properties, etc.  One or more RewriteCond directives can precede RewriteRule directive  All must match to rewrite the URL
  44. 44. RewriteCond example#mozila users special page ;)RewriteCond ${HTTP_USER_AGENT} ^Mozilla.*RewriteRule ^/index.html$ /index.mozilla.php#internal network special home page#use for the 10.0 and 192.168 networksRewriteCond %{REMOTE_HOST} ^10.0.*$ [OR]RewriteCond %{REMOTE_HOST} ^192.168.*$RewriteRule ^/index.html$ /index.internal.php#only HTTP authenticated user admin !RewriteCond %{REQUEST_METHOD} ^HEAD$RewriteCond %{REMOTE_USER} ^admin$RewriteRule .* $1 [F] # Force forbidden!
  45. 45. Configuring MySQLThe my.cnf and my.ini files
  46. 46. MySQL Settings MySQL settings are in the:  my.cnf  my.ini Split into sections  Section name is defined in [ and ]  Settings are in name=value form
  47. 47. Network Settings port  Sets the connection port (usually 3306)  Passed to all clients bind-address  Sets interfaces to listening on  For security reasons usually set (allows only local connections)
  48. 48. Fine tuning settings Fine tuning of MySQL is done in the mysqld section  Defines memory usages for buffers and connections key_buffer  Sets the size of the cache buffer for primary and foreign keys join_buffer  The size of the cache buffer for matching fields from two tables  Set higher if multiple joins in one query are used often
  49. 49. Fine Tuning Settings sort_buffer_size  Size of buffer for sorting  Increase when sorting too many rows thread_cache_size  Size of cache for each thread  Increase when running multiple queries on same tables in a single script table_cache  Size of per-table cache
  50. 50. Fine Tuning Settings thread_concurrency  Sets the level of concurrency of threads  Supposed to affect only Solaris platforms  seems it works fine under Linux platforms  Set to double the number of CPU cores wait_timeout  The number of seconds to wait before closing dead connection wait_interactive_timeout  The time the server waits for persistent connection
  51. 51. MySQL Tuning – Example Always play around with the settings, testing with benchmarks  Apache Benchmark (AB) key_buffer = 250M max_allowed_packet = 16M thread_stack = 128K thread_cache_size = 128 max_connections = 1000 table_cache ` = 6000 thread_concurrency = 16 wait_timeout = 100 interactive_timeout = 100 connect_timeout = 10
  52. 52. MySQL Tuning – Examplejoin_buffer = 2Msort_buffer_size = 2Mread_buffer_size = 2Mread_rnd_buffer_size = 768Kmyisam_sort_buffer_size = 64Mquery_cache_limit = 4Mquery_cache_size = 128Mquery_cache_type = 1
  53. 53. Advanced PHP, Apache and MySQL курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  54. 54. Exercises1. Configure a virtual host www.music.bg in the Apache server to point the directory C:TEMPmusic.bg  Change the "hosts" file to register www.music.bg to be resolved as  Configure the virtual host  Configure the directory and enable browsing its files2. Configure SSL in Apache to allow opening https://www.music.bg  Use self-signed certificate created with openssl
  55. 55. Exercises3. Configure /admin directory to require authentication4. Configure mod_rewrite to rewrite requests like http://www.music.bg/Black%20Lab/That %20night as http://www.music.bg/song.php?artist=Black%20La b&name=Black%20Lab  Create song.php script to display the song name and artist
  56. 56. Free Trainings @ Telerik Academy “PHP & MySQL Web Design" course academy.telerik.com/.../php-school- academy-meeting Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.