New Ticket     Tickets     Wiki     Browse Source     Timeline     Roadmap     Ticket Reports     Search
Last modified 3 months ago Last modified on 05/12/14 15:56:44

<- Back to the HOWTO section

Getting Apache, MySQL, and PHP Running under MacPorts

  • Audience: Users who don’t like the default OS X installation
  • Requires: MacPorts

Introduction

These instructions are written for the following versions:

  • Apache 2.2.*
  • MySQL 5.1.*
  • PHP 5.3.*

Installation

Step 1: Turn off Apple's "Personal Web Sharing"

If you haven’t already done so, make sure you turn off Apple’s "Personal Web Sharing" in the System Preferences so that the default Apache server is not running. While you can set things up so that both servers run on different ports (e.g., port 80 and port 8080), it’s not worth the hassle of maintaining two web server daemons. Just use the latest Apache from MacPorts and be done with it.

Step 2: Install Apache

sudo port install apache2

A sample configuration file is provided in /opt/local/apache2/conf/original/httpd.conf. Don't edit this file; leave it as is so you can refer to the defaults later. The first time you install apache2, the sample configuration file will be copied to /opt/local/apache2/conf/httpd.conf for you. You can edit this file as desired. When you later upgrade apache2 to a newer version, MacPorts will upgrade the sample configuration file but will not modify your httpd.conf, so be sure to manually compare your httpd.conf with the new sample configuration file and bring over any relevant changes. You should also keep backup copies of your httpd.conf in a safe place.

Activate your Apache installation so that it starts now and every time you boot your machine:

sudo port load apache2

If the sever name is not set properly in the configuration file, /opt/local/apache2/conf/httpd.conf, you will encounter the warning below.

httpd: Could not reliably determine the server's fully qualified domain name, using <Computer-Name>.local for ServerName

Where <Computer-Name> refers to the name of your computer as specified in the System Preferences Sharing pane. To resolve the warning, edit the configuration file and set the server name appropriately. For personal use, localhost is sufficient.

ServerName localhost:80

To verify Apache is now running, point your browser to http://localhost/ (you may need to reload the page). You should see a page that says "It works!"

If desired, reboot your machine and point your browser again to http://localhost/ to confirm that Apache is again running.

User directories

If you would like to be able to access web pages in the Sites directory of your home directory, edit /opt/local/apache2/conf/httpd.conf and locate the following line:

#Include conf/extra/httpd-userdir.conf

Uncomment it by removing the "#" at the start of the line so that it reads:

Include conf/extra/httpd-userdir.conf

Then edit /opt/local/apache2/conf/extra/httpd-userdir.conf add the following lines to the end of the file:

For Mac OS X 10.4 and lower:

#
# Include user configurations
#
Include /private/etc/httpd/users/*.conf

For Mac OS X 10.5 and above:

#
# Include user configurations
#
Include /private/etc/apache2/users/*.conf

Restart Apache using sudo /opt/local/apache2/bin/apachectl -k restart to make this change take effect. You can then view your personal pages by accessing http://localhost/~username/, where "username" is your Mac OS X account's short name.

However, the purpose of launchd is to notice processes that stop without its knowledge, and to restart them. So if you use apachectl -k restart, launchd may notice apache "crashing" and restart it itself, confusing apachectl. Instead, you may want to use "port" to tell launchctl to unload apache2, then load it again. This will result in a short interruption of service.

This is done by using

sudo port unload apache2

to stop apache and then using

sudo port load apache2

to start it again.

Local Apache manual

The Apache manual is available on the Apache web site. If you would like to be able to access a copy of this manual on your web server, edit /opt/local/apache2/conf/httpd.conf and uncomment the following line:

#Include conf/extra/httpd-manual.conf

So that it reads like this:

Include conf/extra/httpd-manual.conf

Restart Apache using sudo /opt/local/apache2/bin/apachectl -k restart to make this change take effect. You can then view the manual by accessing http://localhost/manual/.

Secure Sockets (https)

This works for a development system (not recommended for production!).

openssl genrsa -des3 -out server.key 1024
# [enter your passphrase, a simple password we will remove soon]
openssl req -new -key server.key -out server.csr
# [you can accept all the defaults, it does not matter, or customize it to your liking]
openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
# [will ask for passphrase]
cp server.key server.key.bak
openssl rsa -in server.key.bak -out server.key
# [passphrase needs to be typed]
sudo cp server.crt /opt/local/apache2/conf/
sudo cp server.key /opt/local/apache2/conf/

Then enable the following in /opt/local/apache2/conf/httpd.conf

LoadModule ssl_module modules/mod_ssl.so

# Secure (SSL/TLS) connections
Include conf/extra/httpd-ssl.conf

Step 3: Install MySQL

If you merely want to access a MySQL server running on another computer, skip to step 4. If you want to run a MySQL server on this computer, install MySQL like this:

sudo port install mysql51-server

mysql51-server is used in this example because it is the closest to the port that was previously used in this example, which was mysql5-server. However, there are newer versions of mysql in MacPorts that may be worth considering instead. The only reason for not using any of these newer versions in this example is because that would probably require making even more changes than the move to mysql51 required. If you are personally moving from the mysql5 port to the mysql51 port, you may want to add the +openssl variant, as the openssl support that had previously been available by default in the mysql5 port has been moved to a variant in the mysql51 port. Even though the mysql51-server port does not have this variant itself, if you supply the variant with your invocation of port, it will still get passed down to the mysql51 port, because it will be installed as a dependency. Also, mysql51 now uses the port select mechanism, so you will have to run one of the following to get the mysql commands in your PATH: either:

sudo port select mysql mysql51

or:

export PATH=$PATH:/opt/local/lib/mysql51/bin

Once you have done at least one of the two previous commands, you can then set up the main database like this:

sudo -u mysql mysql_install_db5 
sudo chown -R mysql:mysql /opt/local/var/db/mysql51/ 
sudo chown -R mysql:mysql /opt/local/var/run/mysql51/ 
sudo chown -R mysql:mysql /opt/local/var/log/mysql51/ 

If that fails to work, then try this:

sudo mysql_install_db5 
sudo chown -R mysql:mysql /opt/local/var/db/mysql51/ 
sudo chown -R mysql:mysql /opt/local/var/run/mysql51/

Activate your MySQL server installation so that it autostarts when you boot your machine:

sudo port load mysql51-server

and then verify that it is running:

ps -ax | grep mysql

Set the MySQL root password (it should currently be empty, see also the security option below):

mysqladmin5 -u root -p password <new-password> 

where <new-password> is your new desired root password. You will be prompted for your existing password ("Enter password:"); since it is empty, just press Return.

Test everything by logging in to the server.

mysql5 -u root -p

Once you are logged in, simply exit the session like this:

mysql> exit ;

If desired, reboot your machine and then run:

ps -ax | grep mysql

again to verify that the daemon is again running.

Optional database upgrade

If the database exists from a previous installation, you may need to upgrade.

man mysql_upgrade
sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper restart
sudo /opt/local/lib/mysql5/bin/mysql_upgrade -u root -p
sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper restart

(note: these instructions might not be applicable any longer...)

Optional security configuration

There is an interactive program to secure a MySQL installation.

$ man mysql_secure_installation
$ /opt/local/bin/mysql_secure_installation5

The following is a more detailed process that may achieve the same results as the interactive program. Place the following into mysql_security.sql and replace the 'MyNewPass' with your root password. Note that the SQL will remove all access for root from any location other than 'localhost'. You might like to keep this SQL file - all the lines beginning with '--' are doc-comments about how to use it.

-- HOW TO USE THIS FILE (with a MacPorts installation):
-- $ sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper stop
-- $ sudo mysqld_safe5 --init-file=mysql_security.sql &
-- The init will terminate if there are any errors in the init file.
-- Wait a bit to be sure the server is running.
-- If it's running, then shutdown the server (root password required):
-- $ /opt/local/bin/mysqladmin5 -u root -p shutdown
-- Check that everything worked.  There may be an ERROR if the test database
-- doesn't exist.  Otherwise there should be no errors in the file reported by
-- 'mysqld_safe Logging to ..." during the mysql_safe5 startup from above:
-- $ sudo tail -n 20 /opt/local/var/db/mysql5/*.err 

UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';
DELETE FROM mysql.user WHERE User='';
FLUSH PRIVILEGES;
DROP DATABASE test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';

The server startup options --skip-networking and --skip-grant-tables may be useful while implementing security. See also http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html#resetting-permissions-unix

Step 4: Install PHP

sudo port install php5 +apache2
sudo port install php5-mysql

As of the php54 port, installing PHP to work in Apache is a separate port rather than a variant of the php5 port and so should be installed with:

sudo port install php54-apache2handler
sudo port install php54-mysql

Note: the php5 port contains the core PHP features, but there are many optional features available in separate ports, some of which you may want to install as well (such as MySQL support via the php5-mysql port). Use port search php5 to see all the ports that are available.

Register PHP with Apache

cd /opt/local/apache2/modules
sudo /opt/local/apache2/bin/apxs -a -e -n "php5" libphp5.so

As of the php54 port, the module has been renamed to mod_php54.so and so the command should be

cd /opt/local/apache2/modules
sudo /opt/local/apache2/bin/apxs -a -e -n "php5" mod_php54.so

Update Apache’s httpd.conf file to enhance the "DirectoryIndex" directive to include additional "index" files. Search for:

DirectoryIndex index.html

and change it this way:

DirectoryIndex index.php index.html

Also, at the end of the httpd.conf file, add the following lines so that Apache includes the mod_php "AddType" configurations

# 
# Include PHP configurations
#
Include conf/extra/mod_php.conf

As of the php54 port, the configuration file has been renamed to mod_php54.conf and so the command should be

# 
# Include PHP configurations
#
Include conf/extra/mod_php54.conf

You may also need to load the PHP module before including mod_php.conf as described above:

# Load the PHP module
LoadModule php5_module modules/libphp5.so

Or if you are using the php54 port

# Load the PHP module
LoadModule php5_module modules/mod_php54.so

Notice either of the above commands are only required if not present in the httpd.conf file, as the apxs command (executed above) will write those for you.

Set up your PHP configuration files

cd /opt/local/etc/php5
sudo cp php.ini-development php.ini

or (depending on your needs)

cd /opt/local/etc/php5
sudo cp php.ini-production php.ini

Setup the MySQL default socket to use the MacPorts configuration (/opt/local/var/run/mysql5/mysqld.sock)

$ sudo -i
# cd /opt/local/etc/php5
# cp php.ini php.ini.bak
# defSock=`/opt/local/bin/mysql_config5 --socket`
# cat php.ini | sed \
  -e "s#pdo_mysql\.default_socket.*#pdo_mysql\.default_socket=${defSock}#" \
  -e "s#mysql\.default_socket.*#mysql\.default_socket=${defSock}#" \
  -e "s#mysqli\.default_socket.*#mysqli\.default_socket=${defSock}#" > tmp.ini
# grep default_socket tmp.ini  # Check it!
# mv tmp.ini php.ini
# exit # OR rm php.ini.bak && exit

If you installed php5 with the +pear variant you should also:

cd /opt/local/etc/php5
sudo cp pear.conf.sample pear.conf

Restart Apache so that your changes take effect

sudo /opt/local/apache2/bin/apachectl -k restart

Note: Make sure to use the full path as shown here, as apachectl in your PATH refers to the system provided Apache!

Create a file named phpinfo.php that contains the following three lines

<?php
phpinfo();
?>

and place it in your Apache "DocumentRoot" directory (should be "/opt/local/apache2/htdocs") or your own user "Sites" directory if you activated user directories as specified above. Point your browser to http://localhost/phpinfo.php (or http://localhost/~username/phpinfo.php if applicable) and verify that the correct version of PHP is active (v5.3.0 as of this writing) and that MySQL support is active (you may want to search the page for "mysql").

If by some reason the server still doesn't interpret PHP files (your web client tries to download them) it means the PHP configurations, as described above, are not taking effect and in that case you should open the httpd.conf file once again and search for the block

<IfModule mime_module>

And then add before the end

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

Then restart the server.

As a last check, reboot and verify that everything has autostarted and is running (i.e., repeat the above tests).

Step 5: Install phpMyAdmin (optional)

Use MacPorts to install the latest version of phpMyAdmin.

sudo port install phpmyadmin

Update Apache’s httpd.conf file to find phpmyadmin. First add the following lines to the end of the file:

# Local access to phpmyadmin installation
Include conf/extra/httpd-phpmyadmin.conf

and then create a file /opt/local/apache2/conf/extra/httpd-phpmyadmin.conf containing this text:

AliasMatch ^/phpmyadmin(?:/)?(/.*)?$ "/opt/local/www/phpmyadmin$1"

<Directory "/opt/local/www/phpmyadmin">
  Options -Indexes
  AllowOverride None
  Order allow,deny
  Allow from all
  
  LanguagePriority en de es fr ja ko pt-br ru 
  ForceLanguagePriority Prefer Fallback
</Directory>

Restart Apache so that your changes take effect

sudo /opt/local/apache2/bin/apachectl -k restart

Note: Make sure to use the full path as shown here, as apachectl in your PATH refers to the system provided Apache!

Finally, you need to set up the phpMyAdmin configuration to access mySQL. First, set up the config file:

cd /opt/local/www/phpmyadmin/
sudo cp config.sample.inc.php config.inc.php

This will create a file config.inc.php in the phpMyAdmin folder. Edit that file, and locate the lines:

$cfg['Servers'][$i]['auth_type']     = 'config';    // Authentication method (config, http or cookie based)?
$cfg['Servers'][$i]['user']          = 'root';      // MySQL user
$cfg['Servers'][$i]['password']      = '';          // MySQL password (only needed
                                                    // with 'config' auth_type)

Where ' ' is an empty password; fill it with your MySQL root password. You can either change the 'auth_type' from 'config' to 'cookie' or 'httpd', or alternatively provide the password you selected for the root user in the 'password' option.

There is also an interactive setup, see http://www.phpmyadmin.net/documentation/#setup_script and the demo at http://www.phpmyadmin.net/documentation/setup/

To check your phpMyAdmin installation, point your browser to http://localhost/phpmyadmin and verify that phpMyAdmin loads and can access your database (by providing a username and password, depending on the authentication method you selected).

Optional pmadb

For additional features provided by pmadb (http://wiki.phpmyadmin.net/pma/pmadb), run

mysql5 -u root -p < /opt/local/www/phpmyadmin/examples/create_tables.sql

Then run this SQL to setup the pma 'controluser' (change the 'pmapass' to your password).

-- HOW TO USE THIS FILE (with MacPorts installation)
-- mysql5 -u root -p < /opt/local/www/phpmyadmin/examples/create_tables.sql
-- mysql5 -u root -p < mysql_phpMyAdmin_pmaSetup.sql

CREATE USER 'pma'@'localhost' IDENTIFIED BY 'pmapass';

GRANT USAGE ON mysql.* TO 'pma'@'localhost' IDENTIFIED BY 'pmapass';
GRANT SELECT (
    Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv,
    Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv,
    File_priv, Grant_priv, References_priv, Index_priv, Alter_priv,
    Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv,
    Execute_priv, Repl_slave_priv, Repl_client_priv
    ) ON mysql.user TO 'pma'@'localhost';
GRANT SELECT ON mysql.db TO 'pma'@'localhost';
GRANT SELECT ON mysql.host TO 'pma'@'localhost';
GRANT SELECT (Host, Db, User, Table_name, Table_priv, Column_priv)
    ON mysql.tables_priv TO 'pma'@'localhost';

-- Privileges
GRANT SELECT, INSERT, DELETE, UPDATE ON `phpmyadmin`.* TO 'pma'@localhost;

Finally, edit the config file, at /opt/local/www/phpmyadmin/config.inc.php, so it's like this:

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'pmapass';
/* Advanced phpMyAdmin features */
$cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
$cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
$cfg['Servers'][$i]['relation'] = 'pma_relation';
$cfg['Servers'][$i]['table_info'] = 'pma_table_info';
$cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
$cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
$cfg['Servers'][$i]['column_info'] = 'pma_column_info';
$cfg['Servers'][$i]['history'] = 'pma_history';
$cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';

<- Back to the HOWTO section