在 macOS 上搭 PHP 开发环境,核心是用 Homebrew 统一管理 PHP 及其运行时组件,尤其要让 PHP-FPM 正常工作——它不是可选插件,而是 Nginx 或 Apache 处理 PHP 请求的必需桥梁。在 macOS 上搭 PHP 开发环境,核心是用 Homebrew 统一管理 PHP 及其运行时组件,尤其要让 PHP-FPM 正常工作——它不是可选插件,而是 Nginx 或 Apache 处理 PHP 请求的必需桥梁。
装好 Homebrew 并确认基础就绪
homebrew 是整个流程的地基,所有后续操作都依赖它:
- 终端中运行:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" - 安装完执行
brew --version,看到版本号说明成功 - 立刻运行
brew update,确保软件源最新 - 查当前 shell:
echo $SHELL;Apple Silicon Mac 默认是/bin/zsh,配置文件为~/.zshrc
安装并激活指定 PHP 版本(含 PHP-FPM)
Homebrew 安装 PHP 时,默认同时部署 PHP-FPM,但需手动启用服务并确认路径正确:
- 安装例如 PHP 8.3:
brew install php@8.3 - 按提示把 PHP 路径加入环境变量:Apple Silicon 执行
echo 'export PATH="/opt/homebrew/bin:/opt/homebrew/sbin:$PATH"' >> ~/.zshrc - 重载配置:
source ~/.zshrc - 验证:
php -v显示版本,which php-fpm应返回/opt/homebrew/sbin/php-fpm
启动并验证 PHP-FPM 服务
PHP-FPM 必须运行起来,Web 服务器才能通过 FastCGI 与之通信:
- 启动服务:
brew services start php@8.3(注意带版本号,避免冲突) - 检查状态:
brew services list | grep php,应显示started - 默认监听地址是
127.0.0.1:9000,也可查配置文件确认:/opt/homebrew/etc/php/8.3/php-fpm.d/www.conf - 临时测试:运行
php-fpm -t检查配置语法是否正确
对接 Web 服务器(以 Nginx 为例)
Nginx 不直接解析 PHP,必须把 .php 请求转发给正在运行的 PHP-FPM:
- 安装 Nginx:
brew install nginx - 编辑配置:
sudo nano /opt/homebrew/etc/nginx/nginx.conf - 在
server块内添加:
location ~ \.php$ {<br> fastcgi_pass 127.0.0.1:9000;<br> fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;<br> include fastcgi_params;<br>} - 启动 Nginx:
brew services start nginx - 在
/opt/homebrew/var/www放一个info.php(内容<?php phpinfo(); ?>),访问http://localhost/info.php看是否显示 PHP 信息页



















