Configuring Apache + PHP + MySQL in Mac OS X
Jul 09, 2016 am 09:09 AMRespect the author: Reprinted from: http://dancewithnet.com/2010/05/09/run-apache-php-mysql-in-mac-os-x/
Configuring Apache + PHP + MySQL in Mac OS X
Mac OS X has built-in Apache and PHP, which is very convenient to use. This article takes Mac OS X 10.6.3 and 10.8.1 as examples. The main contents include:
- Start Apache
- Run PHP
- Install MySQL
- Use phpMyAdmin
- Configuring PHP’s MCrypt extension library
- Set up virtual host
Start Apache
There are two methods:
- Open "System Preferences" -> "Sharing" -> "Web Sharing". Note that “Web Sharing” has been removed from Mac OS X starting from 10.8.
- Open "terminal", and then (note that the password required for sudo is the root account password of the system)
- Run "
sudo apachectl start
" and enter your account and password, so Apache will run. - Run "
sudo apachectl -v
", you will see the Apache version information of Mac OS X, such as in 10.8.1:<code>Server version: Apache/2.2.22 (Unix) Server built: Jun 20 2012 13:57:09 </code>
- Run "
In this way, enter "http://localhost" in the browser, you can see a page with the content "It works!", which is located under "/Library (resource library)/WebServer/Documents/", this This is the default root directory of Apache.
Note: Turning on Apache means turning on "Web Sharing". At this time, Internet users will access the "/Library (resource library)/WebServer/Documents/" directory through "http://[local IP]/" , access the "/Users/[user name]/Sites/" directory through "http://[local IP]/~[user name]". It is worth noting that when Mac OS X canceled "Web Sharing" in 10.8, it also removed the "/Users/[username]/Sites/" directory, so accessing "http: //[Local IP]/~[Username]" will display "403 Forbidden", but http://[Local IP]/ can still be accessed. You can go to "System Preferences" -> "Security" -> "Firewall", turn on the firewall, and then check "Block all incoming connections (block)" in "Firewall Options" all incoming connections)". You can also set httpd.conf to only allow localhost and 127.0.0.1 to access "/Library (resource library)/WebServer/Documents/".
<code><directory> <span>...... # # Controls who can get stuff from this server. #</span> Order allow,deny <span>#Allow from all</span> Allow from 127.0.0.1 Allow from localhost </directory> </code>
Run PHP
- Run "
sudo vi /etc/apache2/httpd.conf
" in the terminal to open the Apache configuration file. (If you are not used to operating the terminal and vi, you can set it to display all system hidden files in Finder. Remember to restart Finder after setting up, and then you can find the corresponding files and edit them as you like. Please note that some files still need to be modified. Open the root account, but in general it is safer to usesudo
on the terminal to temporarily obtain root permissions) .
- Find "
#LoadModule php5_module libexec/apache2/libphp5.so
", remove the # sign in front, save (enter:w
on the command line) and exit vi (enter:q
on the command line). - Run "
sudo cp /etc/php.ini.default /etc/php.ini
", so you can run <code>sudo vi /etc/php.ini</code> to edit php.ini to configure various functions. for example:<code><span>;通過下面兩項來調(diào)整PHP提交文件的最大值,如phpMyAdmin中導(dǎo)入數(shù)據(jù)的最大值</span> upload_max_filesize = 2M post_max_size = 8M <span>;通過display_errors來控制是否顯示PHP程序的報錯信息,這在調(diào)試PHP程序時非常有用</span> display_errors = Off </code>
- Run "
sudo apachectl restart
" and restart Apache so that PHP can be used. - Run "
sudo cp /Library/WebServer/Documents/index.html.en /Library/WebServer/Documents/info.php
", that is, copy the index.html.en file in the root directory of Apache and rename it to info.php. - Run "
sudo vi /Library/WebServer/Document/info.php
" in the terminal so that you can edit the info.php file in vi. Add “<?php phpinfo(); ?>
” after “It’s works!” and save it. In this way, you can see information about PHP in http://localhost/info.php. For example, the built-in PHP version number in 10.8 is 5.3.13.
Install MySQL
Mac OS X does not have built-in MySQL, so you need to install it manually. Currently, the most stable version of MySQL is 5.5. MySQL provides installation instructions for Mac OS X.
- 下載MySQL 5.5。選擇合適版本,如這里選擇了mysql-5.5.27-osx10.6-x86_64.dmg。
- 運行dmg,會發(fā)現(xiàn)里面有4個文件。首先點擊安裝mysql-5.5.27-osx10.6-x86_64.pkg,這是MySQL主安裝包。一般情況下,安裝文件會自動把MySQL安裝到
/usr/local
下的同名文件夾下。如運行“mysql-5.5.27-osx10.6-x86_64.dmg
”會把MySQL安裝到“/usr/local/mysql-5.5.27-osx10.6-x86_64
”中,一路默認安裝完畢。(注意,從10.8開始Mac OS X的權(quán)限更加嚴格,直接點擊會提示“mysql-5.5.27-osx10.6-x86_64.pkg can’t be opened because it is from an unidentified developer. Your security preferences allow installation of only apps from the Mac App Store and identified developers.”阻止了安裝,你可以使用雙指單擊該安裝文件,在彈出菜單中選擇“用…打開(open with)”,再選擇“安裝(Installer)”就可以接著安裝了。) - 安裝第2個文件MySQLStartupItem.pkg,MySQL就會自動在開機時啟動了。(注意,10.8的安裝方法同上。)
- 安裝第3個文件MySQL.prefPane,就會在“系統(tǒng)設(shè)置偏好”中看到“MySQL”的ICON,通過它就可以控制MySQL是否開啟,以及開機時是否自動運行。到這里MySQL就基本安裝完畢了。(注意,10.8中用雙指單擊該安裝文件,在彈出的菜單中選擇“用…打開(open with)”,然后選擇“系統(tǒng)偏好(System Perference)”就可以接著安裝了。)
- 通過運行“
sudo vi /etc/bashrc
”,在bash配置文件中加入mysqlstart
、mysql
和mysqladmin
的別名(注意:修改完畢之后需要退出“終端(Terminal)”之后重新進入,這些命令才會生效):<code>#mysql alias mysqlstart='sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart' alias mysql='/usr/local/mysql/bin/mysql' alias mysqladmin='/usr/local/mysql/bin/mysqladmin' </code>
這樣就可以在終端中比較簡單地通過命令進行相應(yīng)的操作。由于開始安裝MySQLStartupItem.pkg到“
/Library/StartupItems/MySQLCOM/
”來控制MySQL的運行、自動運行、停止、關(guān)閉之類。在MySQL沒有啟動時,直接運行mysql
或mysqladmin
命令會提示“Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
”,所以我們可以通過控制面板或者直接運行mysqlstart
命令來啟動MySQL,之后再運行mysql
或mysqladmin
命令就正常了。比如安裝完畢后MySQL的root
默認密碼為空,如果要設(shè)置密碼可以在終端運行“mysqladmin -u root password "mysqlpassword"
”來設(shè)置,其中mysqlpassword即root的密碼。更多相關(guān)內(nèi)容可以參考B.5.4.1. How to Reset the Root Password。
注意:Mac OS X的升級或其他原因可能會導(dǎo)致MySQL啟動或開機自動運行時,在MySQL操作面板上會提示“Warning:The /usr/local/mysql/data directory is not owned by the 'mysql' or '_mysql'?
”,這應(yīng)該是某種情況下導(dǎo)致/usr/local/mysql/data
的宿主發(fā)生了改變,只需要運行“sudo chown -R mysql /usr/local/mysql/data
”即可。
另外,使用PHP連接MySQL可能會報錯“Can’t connect to local MySQL server through socket ‘/var/mysql/mysql.sock’”,或使用localhost無法連接MySQL而需要127.0.0.1,原因是連接時php默認去找/var/mysql/mysql.sock
了,但MAC版的MYSQL改動了文件位置,放在/tmp下了。處理辦法是按如下修改php.ini:
<code>mysql.default_socket = /tmp/mysql.sock</code>
使用phpMyAdmin
phpMyAdmin是用PHP開發(fā)的管理MySQL的程序,非常的流行和實用。能夠使用phpMyAdmin管理MySQL是檢驗前面幾步效果的非常有效方式。
- 下載phpMyAdmin。選擇合適的版本,比如這里選擇phpMyAdmin-3.5.22-all-languages.tar.bz2這個版本。
- 把“下載(downloads)”中phpMyAdmin-3.5.22-all-languages.tar.bz2文件解壓到“
/Library/WebServer/Documents/
”中,并改名為phpmyadmin。<code>sudo tar -xf ~/Downloads/phpMyAdmin-3.5.2.2-all-languages.tar.bz2 -C /Library/WebServer/Documents/ sudo mv /Library/WebServer/Documents/phpMyAdmin-3.5.2.2-all-languages /Library/WebServer/Documents/phpmyadmin </code>
- 復(fù)制“
/Library/WebServer/Documents/phpmyadmin/
”中的config.sample.inc.php,并命名為config.inc.php - 編輯config.inc.php,修改如下:
<code><span>用于Cookie加密,隨意的長字符串</span> $cfg['blowfish_secret'] = 'a8b7c6d'; <span>當(dāng)phpMyAdmin中出現(xiàn)“#2002 無法登錄 MySQL 服務(wù)器(#2002 Cannot log in to the MySQL server)”時, 請把localhost改成127.0.0.1就ok了, 這是因為MySQL守護程序做了IP綁定(bind-address =127.0.0.1)造成的</span> $cfg['Servers'][$i]['host'] = 'localhost'; <span>把false改成true,這樣就可以訪問無密碼的MySQL了, 即使MySQL設(shè)置了密碼也可以這樣設(shè)置,然后登錄phpMyAdmin時輸入密碼</span> $cfg['Servers'][$i]['AllowNoPassword'] = false; </code>
- 這樣就可以通過
http://localhost/phpmyadmin
訪問phpMyAdmin了。此時會看到一個提示“無法加載 mcrypt 擴展,請檢查您的 PHP 配置。(The mcrypt extension is missing. Please check your PHP configuration.)”,這會涉及到下一節(jié)安裝MCrypt擴展了。
配置PHP的MCrypt擴展
MCrypt是一個功能強大的加密算法擴展庫,它包括有22種算法,phpMyAdmin依賴這個PHP擴展庫。但在Mac OS X下的安裝卻不那么友善,具體如下:
- 下載libmcrypt-2.5.8.tar.gz。
- 在終端執(zhí)行如下命令(注意如下命令需要安裝Xcode支持,可直接去Mac App Store下載,安裝完畢后可能會發(fā)現(xiàn)在終端運行
./configure --disable-posix-threads --enable-static
會報錯,運行make
會提示命令不存在,此時還需要打開Xcode,然后在Xcode的軟件“配置(Preference…)”)-> “下載(Downloads)” 中安裝 “命令行工具(Command Line Tools)”:<code>cd ~/Downloads tar -zxvf libmcrypt-2.5.8.tar.bz2 cd libmcrypt-2.5.8 ./configure --disable-posix-threads --enable-static make sudo make install</code>
- 下載PHP源碼文件php-5.3.13.tar.bz2,記得選擇中國鏡像會比較快。Mac OS X 10.6.3中預(yù)裝的PHP版本是5.3.1,10.8的版本是5.3.13,而現(xiàn)在最新的PHP版本是5.4.6,所以需要依據(jù)自己的實際情況選擇對應(yīng)的版本,本文以10.8的PHP版本為例。
- 在終端執(zhí)行如下命令,把php-5.3.13.tar.bz2,并配置autoconf(在新的Mac OS X的Xcode中需要自己配置),然后才能運行
phpize
命令:<code>cd ~/Downloads tar -zxvf php-5.3.13.tar.bz2 cd php-5.3.13/ext/mcrypt curl -O http://ftp.gnu.org/gnu/autoconf/autoconf-latest.tar.gz tar -zxvf autoconf-latest.tar.gz cd autoconf-2.69 ./configure make sudo make install cd .. phpize ./configure make sudo make install </code>
- 打開php.ini
<code>sudo vi /etc/php.ini</code>
在php.ini中加入如下代碼,并保存后退出,然后重啟Apache
<code>extension=mcrypt.so</code>
當(dāng)你再訪問http://localhost/phpmyadmin
時,會發(fā)現(xiàn)“無法加載 mcrypt 擴展,請檢查您的 PHP 配置?!碧崾緵]有了,這就表示MCrypt擴展庫安裝成功了。如果還不能加載,嘗試把php.ini中的加入的extension
修改為:
<code>extension=/usr/lib/php/extensions/no-debug-non-zts-20090626/mcrypt.so</code>
Mac OS X下安裝MCrypt擴展的確比較復(fù)雜,而且稍微不小心會有各種小問題出現(xiàn),大家還可以參考How to Install mcrypt for php on Mac OSX Lion 10.8 & 10.7 Development Server和Adding MCRYPT to your OSX Lion PHP install
設(shè)置虛擬主機
- 在終端運行“
sudo vi /etc/apache2/httpd.conf
”,打開Apche的配置文件 - 在httpd.conf中找到“
#Include /private/etc/apache2/extra/httpd-vhosts.conf
”,去掉前面的“#
”,保存并退出。 - 運行“
sudo apachectl restart
”,重啟Apache后就開啟了虛擬主機配置功能。 - 運行“
sudo vi /etc/apache2/extra/httpd-vhosts.conf
”,就打開了配置虛擬主機文件httpd-vhost.conf,配置虛擬主機了。需要注意的是該文件默認開啟了兩個作為例子的虛擬主機:<code><virtualhost> ServerAdmin webmaster@dummy-host.example.com DocumentRoot "/usr/docs/dummy-host.example.com" ServerName dummy-host.example.com ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log" CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common </virtualhost> <virtualhost> ServerAdmin webmaster@dummy-host2.example.com DocumentRoot "/usr/docs/dummy-host2.example.com" ServerName dummy-host2.example.com ErrorLog "/private/var/log/apache2/dummy-host2.example.com-error_log" CustomLog "/private/var/log/apache2/dummy-host2.example.com-access_log" common </virtualhost> </code>
而實際上,這兩個虛擬主機是不存在的,在沒有配置任何其他虛擬主機時,可能會導(dǎo)致訪問localhost時出現(xiàn)如下提示:
<code>Forbidden You don't have permission to access /index.php on this server</code>
最簡單的辦法就是在它們每行前面加上#,注釋掉就好了,這樣既能參考又不導(dǎo)致其他問題。
- 增加如下配置
<code><virtualhost> DocumentRoot "/Library/WebServer/Documents" ServerName localhost ErrorLog "/private/var/log/apache2/localhost-error_log" CustomLog "/private/var/log/apache2/localhost-access_log" common </virtualhost> <virtualhost> DocumentRoot "/Users/[用戶名]/Sites" ServerName sites ErrorLog "/private/var/log/apache2/sites-error_log" CustomLog "/private/var/log/apache2/sites-access_log" common <directory></directory> Options Indexes FollowSymLinks MultiViews AllowOverride None Order deny,allow Allow from all </virtualhost> </code>
保存退出,并重啟Apache。
- 運行“
sudo vi /etc/hosts
”,打開hosts配置文件,加入"127.0.0.1 sites
",這樣就可以配置完成sites虛擬主機了,可以訪問“http://sites”了,在10.8之前Mac OS X版本其內(nèi)容和“http://localhost/~[用戶名]”完全一致。 - 注意,記錄log的“
ErrorLog "/private/var/log/apache2/sites-error_log"
”也可以刪掉,但記錄日志其實是一個好習(xí)慣,在出現(xiàn)問題時可以幫助我們判斷。如果保留這些log代碼,一定log文件路徑都是存在的,如果隨便修改一個不存在的,會導(dǎo)致Apache無法服務(wù)而沒有錯誤提示,這個比較惡心。
這里利用Mac OS X 10.6.3和10.8.1中原生支持的方式來實現(xiàn)的配置,也可以參考“Mac OS X Leopard: 配置Apache, PHP, SQLite, MySQL, and phpMyAdmin(一)?”和“Mac OS X Leopard: 配置Apache, PHP, SQLite, MySQL, and phpMyAdmin(二)?”。實際上,還可以使用XAMPP或MacPorts這種第三方提供的集成方案來實現(xiàn)簡單的安裝和使用。
您或許有興趣:

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

WhensettingupMySQLtables,choosingtherightdatatypesiscrucialforefficiencyandscalability.1)Understandthedataeachcolumnwillstore—numbers,text,dates,orflags—andchooseaccordingly.2)UseCHARforfixed-lengthdatalikecountrycodesandVARCHARforvariable-lengthdata

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The steps for setting MySQL semi-synchronous replication are as follows: 1. Confirm the version supports and load the plug-in; 2. Turn on and enable semi-synchronous mode; 3. Check the status and operation status; 4. Pay attention to timeout settings, multi-slave library configuration and master-slave switching processing. It is necessary to ensure that MySQL 5.5 and above versions are installed, rpl_semi_sync_master and rpl_semi_sync_slave plugins, enable corresponding parameters in the master and slave library, and configure automatic loading in my.cnf, restart the service after the settings are completed, check the status through SHOWSTATUS, reasonably adjust the timeout time and monitor the plug-in operation.

Apache's default web root directory is /var/www/html in most Linux distributions. This is because the Apache server provides files from a specific document root directory. If the configuration is not customized, systems such as Ubuntu, CentOS, and Fedora use /var/www/html, while macOS (using Homebrew) is usually /usr/local/var/www, and Windows (XAMPP) is C:\xampp\htdocs; to confirm the current path, you can check the Apache configuration file such as httpd.conf or apache2.conf, or create a P with phpinfo()

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

MySQL error "incorrectstringvalueforcolumn" is usually because the field character set does not support four-byte characters such as emoji. 1. Cause of error: MySQL's utf8 character set only supports three-byte characters and cannot store four-byte emoji; 2. Solution: Change the database, table, fields and connections to utf8mb4 character set; 3. Also check whether the configuration files, temporary tables, application layer encoding and client drivers all support utf8mb4; 4. Alternative solution: If you do not need to support four-byte characters, you can filter special characters such as emoji at the application layer.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
