Mac 搭建PHP快速开发环境
安装 PHP
添加 PHP 扩展仓库
brew tap shivammathur/php
安装指定版本的 PHP
brew install shivammathur/php/php@8.1
安装扩展
brew install shivammathur/php/php@8.1-mongodb
配置环境变量
nano ~/.zshrc
export PATH="/opt/homebrew/opt/php@8.1/bin:$PATH"
export PATH="/opt/homebrew/opt/php@8.1/sbin:$PATH"
安装并配置 Nginx
安装 Nginx
brew install nginx
配置 Nginx 以支持 PHP
Nginx 的默认配置文件在 /opt/homebrew/etc/nginx/nginx.conf (Apple Silicon)
你需要修改这个文件,告诉 Nginx 如何处理 .php 文件。找到 server 块,修改 location 部
server {
listen 8080; # 默认端口是8080,你可以改为80
server_name localhost;
# 你的网站根目录,例如:
root /Users/你的用户名/Sites;
index index.php index.html index.htm;
# 处理 PHP 文件的核心配置
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
# 这个参数非常重要,确保 PHP 能找到正确的文件
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
配置 PHP-FPM
PHP 通过 PHP-FPM (FastCGI Process Manager) 来与 Nginx 通信。
启动 PHP-FPM
brew services start php@8.1
这条命令会在后台启动 PHP-FPM 并设置为开机自启。默认情况下,它会监听 9000 端口,这正好与上面 Nginx 配置中的 fastcgi_pass 对应。
(可选) 修改 PHP 配置
PHP 的主配置文件 php.ini 位于 /opt/homebrew/etc/php/8.1/php.ini。你可以在这里修改时区、上传大小限制等。
nano /opt/homebrew/etc/php/8.1/php.ini
启动服务并测试
启动 Nginx
brew services start nginx
创建测试文件
在你的网站根目录(例如 /Users/你的用户名/Sites)下,创建一个 index.php 文件,内容为:
<?php
phpinfo();
?>
访问测试
打开浏览器,访问 http://localhost:8080 (或你配置的端口)。如果能看到 PHP 的详细配置信息页面,恭喜你,环境搭建成功!