Installing PHP and MySQL on Leopard with MacPorts (pre-alpha)

  1. If you are brave, you can try out the entropy version of PHP package. It’s beta. Try with care.

  2. If you encounter an error when installing sqlite3, run sudo port clean sqlite3, and reinstall it. See the bug report.


Installing PHP and MySQL on Leopard

(Important: This documentatoin is still pre-alpha. I still have a MySQL launching problem. If you find any error on this tutorial, please email me.)

Why Install?

As the built-in PHP is missing some key features, it’s not very usable as a web development environment. This tutorial aims to instruct the way to install PHP 5, Apache2 and MySQL 5 for Mac OS X 10.5 (Leopard) running under Intel-based Macs.

Prerequisite

If you are not comfortable with editing files with command line tools such vi, pico and emacs, I would highly suggest that you use a GUI editor with command-line tool support. This tutorial uses TextMate. You can install TextMate’s command line tool, mate from “Help” → “Terminal Usage…”.

(TODO: screenshot for a dialog for the mate command install might be added.)

You should have a basic understanding of Mac OS X and Unix. Familiarity with basic commands like cd, ls, which, man, sudo and chmod is a prerequisite. Unix FAQ at The macosxhints Forums is a great resource if you get into trouble. After running a command that start with sudo, you are asked to enter your password. Try add sudo if you see permission errors.

We are using MacPorts as a tool to install them. MacPorts is (from the official website):

A system for compiling, installing, and managing free and open source software comprised of an infrastructure called MacPorts base and a collection of ports. MacPorts current port collection defines the software may be installed.

With MacPorts, you don’t have to download source files, configure and compile them on your own.

Installing MacPorts

MacPorts has an excellent documentation for users. Follow the guide. The easiest way is to follow the package install as written in section 2.3.1. Don’t forget to install Xcode Tools before opening the package. In addition, after installing MacPorts with the package, be sure to set the path as written in section 2.4. Your system doesn’t recognize MacPorts unless you set the right path in .profile.

Read MacPorts guide carefully. I would rather not explain each step for MacPorts installation. The guide is easy-to-read and well-written.

You can check make sure that MacPorts is ready to use by runnning the following command in Terminal:

port help

MacPorts uses port as the command. The command above shows help page of the port command. That’s a compact description of various usage of the command. It should start with somethig like this:

port
    [-bcdfiknopqRstuvx] [-D portdir] [-F cmdfile] action [privopts] [actionflags]
    [[portname|pseudo-portname|port-url] [@version] [+-variant]... [option=value]...]...

If you see an error at this point, double-check the path in .profile. After editing .prifile, you need to open a new Terminal window. Read the section carefully.

Installing MacPorts doesn’t guarantee that everything works. We need to (a) check if there’s any update of MacPorts itself, and we need to (b) update the list of available installs.

We use selfupdate for (a) and sync for (b). Both require admin access, which means you prepend sudo to the command itself. After runnin the commands, you will be asked to type your password.

(a) selfupdate

sudo port selfupdate

(b) sync

sudo port sync

(Note: You don’t have to use port sync because port selfupdate includes port sync.) As is often the case with Unix commands, if you see no message, the command run successfuly.

Installing PHP, MySQL and Apache with MacPorts

What we want are:

  • PHP, MySQL and Apache installation
  • Files needed for automatic startup

We install PHP, MySQL and Apache all at once. We need all of them working together. We also want to start the web server (Apache) and database (MySQL) automatically when we log into Mac OS X. Starting the Apache and MySQL manually everytime you restart your Mac is a pain in the ass.

The automatic startup process is done by launchd. We want to download the files needed for launchd, not just files needed to make the server up and running. (d in launchd stands for daemon.)

The command we use is port install. We want to install PHP 5 that comes with Apache and MySQL. To get other necessary installs such as Apache and MySQL, we use port variants. Variants are (from the offical documentation):

Variants are a way for port authors to provide options for a port that may be chosen during the port install.

Variants are added when used with plus sign (+).

As of this writing, installing Apache with MacPorts on Mac OS X (Leopard) gives an error. We use a workaround to avoid the issues. The workaround is to install gawk and nawk before anything else. (See the ticket for details.)

Let’s install the two tools above. You will be asked for your password.

sudo port install gawk

Wait until everything finishes. Then, install the other one. This will take some time.

sudo port install nawk

Okay. Let’s dive into the most important part. We are going to install PHP 5, MySQL 5 and Apache 2 at the same time. Run the following command. Wait a while. Time for coffee.

sudo port install php5 +apache2 +mysql5 +server

(Note: +server is not listed as a variant for php5. +server is a variant for mysql5. Without +server option, you don’t get a file needed for launchd.)

MacPorts output a log on your Terminal screen while installation. The information is useful when you encounter a problem.

Automatic startup with launchd

We are going to set up our installs to make them work together. First we will run launchd that is necessary for the automatical startup. You may get some errors after running the commands because you haven’t configured Apache or MySQL yet. Just run the commands now. (See the man page to know more about launchd)

sudo launchctl load -w /Library/LaunchDaemons/org.macports.apache2.plist

and

sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

To lean more about launchctl, visit the man page As you may have notices, the two files we loaded are located in /Library/LaunchDaemon. But with some exceptions, MacPorts installs everything at /opt.

Runnin Apache and PHP

Let’s set up Apache and PHP. Run the following command.

cd /opt/local/apache2/modules

and

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

We then need to make two configuration files. One for Apache and the other for PHP. We don’t write configuration files from scrach. We simply make a copy of a default setting and rename with a new name.

PHP’s configuration file (php.ini) can be made by copying the sample file.

sudo cp /opt/local/etc/php.ini-dist /opt/local/etc/php.ini

Apache’s configuration file (httpd.conf) can be made by copying the sample file.

sudo cp /opt/local/apache2/conf/httpd.conf.sample /opt/local/apache2/conf/httpd.conf

To lean more about cp command, visit the man page .

Editing Apache Configuration files

In order for Apache to work with PHP, you need to edit the configuration file. You can use your favorite text editor. TextMate, BBEdit, SubEthaEdit, vi, emacs or pico will do for you. I use mate command of TextMate as an example.

mate /opt/local/apache2/conf/httpd.conf

If you get an error, the command tool, mate, is not installed.

Workaround of ssl_module

There is a bug in a module. In the httpd.conf, find “LoadModule ssl_module modules/mod_ssl.so” and comment out the line. # sign is used for comments in Apache files. The resultant line now should look like this.

(TODO: More explanation for why this happens will be good.)

#LoadModule ssl_module modules/mod_ssl.so

Activating PHP via Apache files

Apache file needs to be configuired so that it can work with PHP.

Add the following the httpd.conf file and save it.

LoadModule php5_module modules/libphp5.so
AddHandler php5-script .php
AddType text/html .php
DirectoryIndex index.php

Check if Apache and PHP work correctly. Before running the web server, make sure you turn off “Web Sharing” at Sharing in System Preferences. You will get an error if you try to do the command below with Web Sharing on.

Now let’s run Apache server by running:

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

(Note: you have more than one apachectl installed because Mac OS X comes with it. Therefore you need to specify the path to the command. Just to remember “ctl” means “control”.)

Where your web files are located

The files you access from your browser is located at /opt/local/apache2/htdocs. The directory already has several folders including index.html. Visit localhost. If you see the webpage say “It works.”, your web server is running without a problem. Congraturations. Apache is working.

(TODO: screenshot will be added.)

Next, we want to know if PHP is working. Make a php file that contains a PHP script. I will do so by creating a file called “test.php”.

mate /opt/local/apache2/htdocs/test.php

Write a short script shown below in the file and save it.

<?php phpinfo(); ?>

phpinfo function shows your PHP configuration. Visit localhost/test.php. It will output a long page that contains all the configuration information starting with your PHP version number.

(TODO: screenshot will be added)

Activating MySQL

You can’t still use MySQL yet. Let’s initialize the database. Run the command.

sudo -u mysql mysql_install_db5

Make a configuration file, my.cnf by copying from /opt/local/share/mysql5/mysql/my-small.cnf.

sudo /opt/local/share/mysql5/mysql/my-small.cnf /opt/local/etc/mysql5/my.cnf

Run the MySQL daemon. By this command, MySQL will keep on running in the background.

sudo /opt/local/lib/mysql5/bin/mysqld_safe

(Note: We haven’t set a password for root. It is recommended that you set a password for root.)

Let’s use MySQL. Open another Terminal window or tab, and run the command:

mysql5 -u root

Did you see an error like this?

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/opt/local/var/run/mysql5/mysqld.sock' (2)

If you see the error, you may not have a socket file. Create a file with touch command. touch command simply creates an empty file.

sudo touch /opt/local/var/run/mysql5/mysqld.sock

(FIXME: I have no idea why I need to restart the sytem.)

And restart the system and try once again. (Note: I don’t know why MySQL gets stuck for this problem. Need your help!)

If successful, you see the welcome message like this:

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 3 Server version: 5.0.51 Source distribution

Type ‘help;’ or ‘\h’ for help. Type ‘\c’ to clear the buffer.

mysql>

Type quit to exit from MySQL. Now we know MySQL is working.

Setting up a password for MySQL

We haven’t set a password for the root user. As the root user has a permission to do anything, this is a security risk. We use the following command to set up a root password. Replace the ‘secret-password’ with your original password.

mysqladmin5 -u password 'secret-password'

Then, let’s connect to MySQL with your password.

mysql5 -u root -p

You will be asked to enter your password. Type your password press return.

See the welcome message? Then the password you just set works. Exit from MySQL by running quit.

Connecting MySQL via PHP

We not modify the test.php so that we test if your PHP script can connect to MySQL.

mate /opt/local/apache2/htdocs/test.php

Type the following script in test.php and save it. Don’t forget to change the “secret_password” with the password you just for your root password. When you save it, you will be asked to enter your password.

<?php

$connection = mysql_connect("localhost", "root", "secret_password");

if ($connection) {
    echo "MySQL connection is successful.";
} else {
    echo "MySQL connection failed.";
}

?>

Now visit http://localhost/test.php. If you see “MySQL connection is successful.”, your connection is successful. If you get an error: Access denied for user 'root'@'localhost' (using password: YES), then your passwod is in correct. Make sure your password in test.php is correct.

Important File Locatoins

You at least should remember the important file locations. During your adventure with web development, you will find many other tutorials that ask you to change configuration. You basically need the following information.

  • Apache configuration file is /opt/local/apache2/conf/httpd.conf.
  • PHP configuration file is /opt/local/etc/php.ini.
  • Web root directory is /opt/local/apache2/htdocs/.
  • MySQL configuration file is /opt/local/etc/mysql5/my.cnf.

References

Comments

When using your guides for

When using your guides for installing php/apache and mysql and after that symfony on Mac Leopard.

I found out that when using symfony tutorial i got errors complaining about missing sqlite. Maybe you can update your guide so that it also compiles php with sqlite

@Mark, can you be more

@Mark, can you be more specific? Where exactly did you get the error? You don’t need sqlite to use symfony. Which tutorial are you following?

when using the tutorial

when using the tutorial on: http://www.symfony-project.org/tutorial/1_0/my-first-project

this one uses a sqlite database i think , because the script complains about sqlite missing when trying to add model to database in tutorial.

I know you can use mysql instead for symfony, but newcomers to symfony and working on a mac can come across this problem.

I also ran into a problem when running: sudo port install nawk it gives a error. “Target org.macports.fetch returned: fetch failed” . Maybe there’s something wrong with the macports server?

The tutorial you mentions

The tutorial you mentions uses the sandbox install of symfony, which is why I refer to “Ajax tutorial”.

I haven’t used sqlite personally. I’m sure sqlite comes with Leopard as many apps take advantage of it.

I will look into how to install sqlite with macports.

Following these instructions

Following these instructions explicitly, I get these errors:

1. nawk won't fetch...

---> Fetching nawk
---> Attempting to fetch awk.tar.gz from http://cm.bell-labs.com/cm/cs/who/bwk/

...and trying to proceed without it (the ticket closed with suggestion to install gawk but didn't mention nawk)...

1. Error: Target org.macports.configure returned: configure failure: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_devel_ncursesw/work/ncurses-5.6" && ./configure --prefix=/opt/local --enable-widec --disable-rpath --with-shared --without-debug --without-ada --enable-safe-sprintf --enable-sigwinch --mandir=/opt/local/share/man " returned error 1

...followed by...

Error: The following dependencies failed to build: apache2 apr-util sqlite3 readline ncurses ncursesw openssl zlib pcre bzip2 curl pkgconfig freetype jpeg libmcrypt libpng libxml2 libxslt mhash mysql5 tiff
Error: Status 1 encountered during processing.

There is a related ticket set to port bugs today (1/9/08):
http://trac.macosforge.org/projects/macports/ticket/13876

Any workaround in the interim? Also, what should I do regarding the partial port install and failed builds?

Thanks

@scott, Sorry for my late

@scott, Sorry for my late reply.

We might not need to install nawk. I haven’t test my tutorial since macports are updated to 1.6.

Not sure why the config error occurred. Can you please bring your error message to MacPorts email list?

Below are some fixes to this

Below are some fixes to this article’s instructions that I needed to make for the installation and configuration of apache2 and php to work. I have not been able to configure mysql5 so that it works yet, and I’ll ask about this in my next post. Hope this helps someone.


1.

In the step where you are instructed to type: sudo /opt/local/apache2/bin/apxs -a -e -n “php5” libphp5.so

the following error message is returned: apxs:Error: Config file /opt/local/apache2/conf/httpd.conf not found.

Solution: I found the file: httpd.conf.sample, which was installed by default, and copied it as httpd.conf: sudo cp httpd.conf.sample httpd.conf

Then I reexecuted the command again: sudo /opt/local/apache2/bin/apxs -a -e -n “php5” libphp5.so


2.

The command, sudo /opt/local/apache2/bin/apachectl restart gave the following error output httpd: Syntax error on line 96 of /opt/local/apache2/conf/httpd.conf: Cannot load /opt/local/apache2/modules/modssl.so into server: dlopen(/opt/local/apache2/modules/modssl.so, 10): Symbol not found: sslcmdSSLCACertificateFile\n Referenced from: /opt/local/apache2/modules/modssl.so\n Expected in: flat namespace\n

Solution:

I commented out line 96 of httpd.conf file, and then ran the original command again.

3. LoadModule php5_module modules/libphp5.so AddHandler php5-script .php AddType text/html .php DirectoryIndex index.php

This block of text above didn’t work when added to the end of the /opt/local/apache2/conf/httpd.conf file. It had to be added in between the tags in that file. Excerpt below:

This should be changed to whatever you set DocumentRoot to.

# # # Possible values for the Options directive are “None”, “All”, # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that “MultiViews” must be named explicitly —- “Options All” # doesn’t give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride None

#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all

#added by me
LoadModule php5_module modules/libphp5.so
AddHandler php5-script .php
AddType text/html .php
DirectoryIndex index.php


4.

In order to set the user path ~myusername such that I can point my browser to http://localhost/~myusername , the same file, /opt/local/apache2/conf/httpd.conf , was modified as follows

User home directories

I REMOVED THE COMMENT BELOW:

Include conf/extra/httpd-userdir.conf


I seem to have the exact

I seem to have the exact same problem as Scott, even though I did successfully install both gawk and nawk.

It was trying to install:

sudo port install php5 +apache2 +mysql5 +server
Things went well… up until this point:
--->  Building sqlite3 with target all
Error: Target org.macports.build returned: shell command " cd "/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_databases_sqlite3/work/sqlite-3.5.5" && gnumake all " returned error 2
Command output: sed -e s/--VERS--/3.5.5/ ./src/sqlite.h.in | \
    sed -e s/--VERSION-NUMBER--/3005005/ >sqlite3.h
/usr/bin/gcc-4.0 -O2 -o lemon ./tool/lemon.c
cp ./tool/lempar.c .
cp ./src/parse.y .
./lemon  parse.y
mv parse.h parse.h.temp
f ./addopcodes.awk parse.h.temp >parse.h
/bin/sh: f: command not found
gnumake: [parse.c] Error 127 (ignored)
cat parse.h ./src/vdbe.c |  -f ./mkopcodeh.awk >opcodes.h
/bin/sh: -f: command not found
cat: stdout: Broken pipe
gnumake: *** [opcodes.h] Error 127

Error: The following dependencies failed to build: apache2 apr-util sqlite3 openssl zlib pcre bzip2 curl pkgconfig freetype jpeg libmcrypt libpng libxml2 libxslt mhash mysql5 tiff
Error: Status 1 encountered during processing.

So I’m a little concerned that I have a half-baked install right now. :(

When I try to install gawk I

When I try to install gawk I can see this output:

copito:~ alraben$ sudo /opt/local/bin/port install nawk —-> Fetching nawk —-> Attempting to fetch awk.tar.gz from http://cm.bell-labs.com/cm/cs/who/bwk/ —-> Attempting to fetch awk.tar.gz from http://svn.macports.org/repository/macports/distfiles/nawk —-> Attempting to fetch awk.tar.gz from http://svn.macports.org/repository/macports/distfiles/general/ —-> Attempting to fetch awk.tar.gz from http://svn.macports.org/repository/macports/downloads/nawk Error: Target org.macports.fetch returned: fetch failed Error: Status 1 encountered during processing.

What’s the problem?

Greetings from Spain…

I was getting the same

Error: The following dependencies failed to build: apache2 apr-util sqlite3 Error: Status 1 encountered during processing.

Anyway… just typed: sudo port clean —all sqlite3

then it works fine. great tutorial!

Something was not working

Something was not working with MYSQL. So I keep googleing, till I found http://www.appleblog.es/index.php/instalar-apache-2-mysql-php-y-ruby-on-rails-en-mac/

Great tutorial too!

Works OK until I get to

Works OK until I get to mySQL. “sudo -u mysql mysqlinstalldb5” results in “command not found.”

Brand new Mac Book Pro

Brand new Mac Book Pro running 10.5.2.

Installed Macports today and then started with this installation. It starts failing at the sqlite3 part:

Error: The following dependencies failed to build: apache2 apr-util sqlite3 openssl zlib pcre bzip2 curl pkgconfig freetype jpeg libmcrypt libpng libxml2 libxslt mhash mysql5 tiff Error: Status 1 encountered during processing.

I uninstalled everything and then reinstalled several times—but it failed at the same place. The first run I had installed gawk and nawk. The second time I only installed neither gawk nor nawk but got an error that awk was missing. I again uninstalled everything and then installed nawk and then tried your main install but it then gave the error you see above.

Bumming. Whole day I’ve wasted.

My last computer PPC iBook running Leopard worked fine with your install a couple weeks ago. Didn’t even need gawk first.

Hope this helps you troubleshoot.

Troy

Follow up: Ran the “sudo

Follow up:

Ran the “sudo port clean —all sqlite3” ike the last poster and it fixed my issue too. Everything installed without issue.

Keep up the good work!

I had been checking some

I had been checking some tutorials about setting up apache2+php5+mysql on Leopard, but this one is a real piece of cake!!! :-). I want to give PHP programming a shot!, and this article got me going …

There are some trifling typos.

Congratulations.