Mac に PHP をインストールする

環境

  • MacOS Sonoma 14.6
  • Homebrew v4
  • Zsh
  • iTerm

Homebrew を使って Mac に PHP をインストールする。

インストール可能なパッケージを探す

$ brew search php
==> Formulae
brew-php-switcher   php@8.0             phpmd               pup
php                 php@8.1             phpmyadmin          pop
php-code-sniffer    php@8.2             phpstan             pcp
php-cs-fixer        phpbrew             phpunit

==> Casks
eclipse-php         phpstorm            phpwebstudy         pop

インストール

インストール後のメッセージ重要。
後でパスを通す。

$ brew install php@8.2

Finally, check DirectoryIndex includes index.php
    DirectoryIndex index.php index.html

The php.ini and php-fpm.ini file can be found in:
    /opt/homebrew/etc/php/8.2/

php@8.2 is keg-only, which means it was not symlinked into /opt/homebrew,
because this is an alternate version of another formula.

If you need to have php@8.2 first in your PATH, run:
  echo 'export PATH="/opt/homebrew/opt/php@8.2/bin:$PATH"' >> ~/.zshrc
  echo 'export PATH="/opt/homebrew/opt/php@8.2/sbin:$PATH"' >> ~/.zshrc

For compilers to find php@8.2 you may need to set:
  export LDFLAGS="-L/opt/homebrew/opt/php@8.2/lib"
  export CPPFLAGS="-I/opt/homebrew/opt/php@8.2/include"

To start php@8.2 now and restart at login:
  brew services start php@8.2
Or, if you don't want/need a background service you can just run:
  /opt/homebrew/opt/php@8.2/sbin/php-fpm --nodaemonize

パスを通す

$ vi ~/.zshrc

# 下記を最後尾に追加
export PATH="/opt/homebrew/opt/php@8.2/bin:$PATH"
export PATH="/opt/homebrew/opt/php@8.2/sbin:$PATH"
export LDFLAGS="-L/opt/homebrew/opt/php@8.2/lib"
export CPPFLAGS="-I/opt/homebrew/opt/php@8.2/include"

iTerm の再起動もしくは下記コマンド叩くか、
新しくウインドウを開く。

$ export PATH="/opt/homebrew/opt/php@8.2/bin:$PATH"
$ export PATH="/opt/homebrew/opt/php@8.2/sbin:$PATH"
$ export LDFLAGS="-L/opt/homebrew/opt/php@8.2/lib"
$ export CPPFLAGS="-I/opt/homebrew/opt/php@8.2/include"

バージョン確認

$ php -v
PHP 8.2.28 (cli) (built: Mar 11 2025 17:58:12) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.2.28, Copyright (c) Zend Technologies
    with Zend OPcache v8.2.28, Copyright (c), by Zend Technologies