- Upgrade to PHP 8 with Homebrew on Mac
- # Upgrading with Homebrew
- # Normal upgrade
- # Upgrade with shivammathur/homebrew-php
- # Next steps
- # Valet
- # Extensions
- # Last step
- Jason McCreary I build things with my hands
- Updating Apache
- Updating PHP
- Updating MySQL
- Jason McCreary I build things with my hands
- Installing PHP
- Configuring Apache
- Updating your PATH
- Configuring PHP
- Как обновить PHP в Mac OS X?
- 12 ответов
Upgrade to PHP 8 with Homebrew on Mac
Do you want to learn more about PHP 8.1? There’s The Road to PHP 8.1. For the next 10 days, you’ll receive a daily email covering a new and exiting feature of PHP 8.1; afterwards you’ll be automatically unsubscribed, so no spam or followup. Subscribe now!
# Upgrading with Homebrew
Start by making sure brew is up-to-date:
Next, upgrade PHP. You can either use the built-in php recipe, use tap shivammathur/homebrew-php . I’d recommend the second approach, since it allows you to easily install several PHP versions and switch between them.
# Normal upgrade
# Upgrade with shivammathur/homebrew-php
To switch between versions, use the following command:
You can read more in the repository.
# Next steps
Check the current version by running php -v :
Restart Nginx or Apache:
And make sure that your local web server also uses PHP 8 by visiting this script:
The version should show 8.0.x .
Note: if you’re using Laravel Valet, please keep on reading, you need some extra steps in order for the web server to properly work.
# Valet
If you’re using Laravel Valet, you should do the following steps to upgrade it:
You can use valet use to switch between PHP versions:
Note that if you’re using an older Valet version (prior to v2.13.18), when switching from PHP 8 to PHP 7.4 there was a bug that didn’t properly update the changes. This was fixed in Valet 2.13.18 so that it now automatically removes the valet socket after having run valet use php@7.4 . If you need to do this manually, you can run:
# Extensions
PHP extensions are installed using pecl. I personally use Imagick, Redis and Xdebug. They can be installed like so:
You can run pecl list to see which extensions are installed:
You can search for other extensions using pecl search :
Make sure to restart your web server after installing new packages:
If you’re using Laravel Valet, you should restart it as well.
Make sure all extensions are correctly installed and loaded by checking both your PHP webserver and CLI installs:
If extensions aren’t properly loaded, there are two easy fixes.
First, make sure the extensions are added in the correct ini file. You can run php —ini to know which file is loaded:
Now check the ini file:
Note that if you’re testing installed extensions via the CLI, you don’t need to restart nginx, apache or Valet when making changes to ini settings.
The second thing you can do, if you’re updating from an older PHP version which also used pecl to install extension; is to reinstall every extension individually.
# Last step
Finally you should test and upgrade your projects for PHP 8 compatibility.
Источник
Jason McCreary I build things with my hands
Main Thread November 3, 2019 • 3 min read
Recommend switching to Docker
I finally switched to using Docker for local development on macOS. While the following tutorial works for macOS Catalina, it has limitations. I recommend following my latest tutorial on installing Apache, MySQL, and PHP on macOS using Docker.
Note: This post assumes you followed installing Apache, PHP, and MySQL on Mac OS X Mojave and have since upgraded to macOS Catalina. If you did not follow the original post, you should follow installing Apache, PHP, and MySQL on macOS Catalina.
When Mac OS X upgrades it overwrites previous configuration files. However, before doing so it will make backups. For Catalina the original versions may have a suffix of mojave or be copied to a backup folder on the Desktop. Most of the time, configuring your system after updating Mac OS X is simply a matter of comparing the new and old configurations.
This post will look at the differences in Apache, PHP, and MySQL between Mac OS X Mojave and macOS Catalina.
Updating Apache
Mac OS X Mojave and macOS Catalina both come with Apache pre-installed. As noted above, your Apache configuration file is overwritten me when you upgrade to macOS Catalina.
There were a few differences in the configuration files. However, since both Mojave and Catalina run Apache 2.4, you could simply backup the configuration file from Catalina and overwrite it with your Mojave version.
However, I encourage you to stay up-to-date. As such, you should take the time to update Catalina’s Apache configuration. First, create a backup and compare the two configuration files for differences.
Now edit the Apache configuration. Feel free to use a different editor if you are not familiar with vi.
Uncomment the following line (remove # ):
In addition, uncomment or add any lines you noticed from the diff above that may be needed. For example, I uncommented the following lines:
Finally, I cleaned up some of the backups that were created during the macOS Catalina upgrade. This will help avoid confusion in the future.
Note: These files were not changed between versions. However, if you changed them, you should compare the files before running the commands.
Updating PHP
Mac OS X Mojave came with PHP version 7.1 pre-installed. This PHP version has reached its end of life. macOS Catalina comes with PHP 7.3 pre-installed. If you added any extensions to PHP you will need to recompile them.
Also, if you changed the core PHP INI file it will have been overwritten when upgrading to macOS Catalina. You can compare the two files by running the following command:
Note: Your original file may note be named something else. You can see which PHP core files exist by running ls /etc/php.ini* .
I would encourage you not to change the PHP INI file directly. Instead, you should overwrite PHP configurations in a custom PHP INI file. This will prevent Mac OS X upgrades from overwriting your PHP configuration in the future. To determine the right path to add your custom PHP INI, run the following command:
Note: It appears Catalina does not include the PHP Zip extension. This is a popular extension used by many packages. This was one of the reasons I switched to using Docker.
Updating MySQL
MySQL is not pre-installed with Mac OS X. It is something you downloaded when following the original post. As such, the macOS Catalina upgrade should not have changed your MySQL configuration.
Find this interesting? Let’s continue the conversation on Twitter.
Источник
Jason McCreary I build things with my hands
Main Thread September 19, 2016 • 3 min read
Recommend switching to Docker
If you are running macOS Mojave or higher, the recommended solutions in this tutorial may no longer work. For those reasons, I recommend following my latest tutorial on installing Apache, MySQL, and PHP on macOS using Docker.
As noted in my posts on installing Apache, PHP and MySQL on Mac OS X, Mac OS X comes pre-installed with Apache and PHP. Unfortunately, the pre-installed version of PHP with macOS is outdated:
- Mac OS 10.11 (El Capitan) pre-installed with PHP 5.5
- Mac OS 10.12 (Sierra) pre-installed with PHP 5.6
- Mac OS 10.14 (Mojave) pre-installed with PHP 7.1
- Mac OS 10.15 (Catalina) pre-installed with PHP 7.3
Many of these PHP versions are already end of life. In fact, macOS Mojave was the first time the pre-installed version was recent — although still not the latest PHP version.
So what do you do if you want to upgrade or install a different PHP version on your Mac? Well, you could use Homebrew. But I found a pre-packaged alternative — PHP OSX.
PHP OSX is a package installer for PHP versions 5.3 to 7.3 (current). It’s available for Mac OS 10.6+ (Snow Leopard to Mojave). While installing PHP OSX is just a few steps, I’ll walk you through each of them.
Installing PHP
First, choose the version of PHP you want to install. In this example, I’ll install PHP 7.2 as that is the latest stable version of PHP. However, if you want to install PHP 7.1 that is available as well.
If you’re not comfortable executing scripts from the Internet, you can do the install by hand.
Configuring Apache
Provided you are using the pre-installed version of Apache, PHP OSX will add the /etc/apache2/other/+php-osx.conf configuration file which will automatically be loaded by Apache.
If you had previously enabled PHP (as I did), you’ll need to comment out the following line in /etc/apache2/httpd.conf :
If you are running an older version of Mac OS X, the line may be:
Updating your PATH
Although Apache will now run the new version of PHP, the command line will not. In order for the command line to use the new version of PHP you will need to update your PATH .
If you don’t want to run the command above every time you open a new terminal, you can update the PATH in your .bash_profile .
Configuring PHP
Finally, you will want to update some of the PHP configuration values. PHP OSX installs a PHP INI file for you to change. To edit this file, run:
If you kept all of your local PHP configuration within a single INI file (as I did), you can simply append it to the PHP OSX file with:
Now you’ll just need to review your PHP code to ensure it’s compatible with your newly installed PHP version. And for that, I recommend PHP Shift.
Find this interesting? Let’s continue the conversation on Twitter.
Источник
Как обновить PHP в Mac OS X?
Я считаю, что это ужасно тупой вопрос, но как ни странно, эта проблема плохо документированы.
Я хотел бы обновить php, но есть несколько проблем:
- нет встроенного менеджера пакетов. MacPorts не распознает php как установленный пакет, потому что он не устанавливал сам PHP.
- под управлением locate php указывает, что, вероятно, много зависимостей.
- Я не знаю, как был установлен php, как это было включено в ОС, поэтому я не знаю, должен ли я устанавливать из исходного кода или загружать двоичные файлы. Я также не знаю, как правильно удалить предыдущую версию без нарушения зависимостей.
Я бегу на леопарда. У меня такое чувство, что Apple не хочет, чтобы Вы обновлялись. Будет ли покупка Snow Leopard и обновление решить эту проблему (и будущие, как это)?
12 ответов
возможно, вы захотите проверить PHP-пакет Marc Liyanage. Он поставляется в хорошем пакете установщика Mac OS X, который вы можете дважды щелкнуть. Он держит все в курсе.
кроме того, хотя обновление до Snow Leopard не поможет вам делать обновления PHP в будущем, это, вероятно, даст вам более новую версию PHP. Я запускаю OS X 10.6.2, и у него есть PHP 5.3.0.
затем config в .bash_profile или .bashrc
нет встроенного менеджера пакетов. MacPorts не распознает php как установленный пакет, потому что он не устанавливал сам PHP.
вы все еще можете установить его с MacPorts. sudo port install php52 (или любая версия, которую вы хотите) установит PHP.
он не будет перезаписывать версию, поставляемую Apple. Он установит его под /opt/local . Вы можете добавить /opt/local в начало $PATH и используйте версию MacPorts в конфигурации Apache.
Я думаю, что один простой способ сделать это, это:
1-Проверьте, где находится ваш текущий PHP:
вы видите? Обычно наши команды, которые мы запускаем, являются ссылкой в /usr/local/bin so.
2-разблокируйте эту текущую ссылку PHP
если вы предпочитаете, прежде чем разорвать его, проверьте путь, а затем удалите файлы php (do ls -al /usr/local/bin / grep php, а затем rm -rf на нужный путь)
3-установить PHP 7.1
4 — Создайте новую ссылку (используя php 7.1 bin, который вы установили)
как я уже сказал, Это простой способ, я думаю.
Как было рекомендовано здесь, этот сайт обеспечивает удобный, современный один вкладыш.
Это не перезаписывает базовую версию PHP в вашей системе, а вместо этого устанавливает ее чисто в /usr/local/php5.
мой предпочтительный метод-просто установить через Homebrew.
прежде чем я продолжу, У меня есть последняя версия (v5.0.15) of сервер OS X (да, ужасно, я знаю. однако веб-сервер, похоже, работает A-OK). Я искал повсюду в течение нескольких дней, пытаясь обновить (или, по крайней мере, заставить Apache указать) новую версию PHP. Мой mcrypt не работал, вместе с другими расширениями, и я установил и переустановил PHP бесчисленное количество раз из http://php-osx.liip.ch/и другие учебники пока я, наконец, заметил tid-бит информации, написанной в комментарии в одном из многих разных .conf файлы OS X Server сохраняет, который был, что OS X Server загружает его собственный пользовательский .conf файл перед загрузкой Apache httpd.conf (расположенном в /etc/apache2/httpd.conf ). Файл сервера находится:
когда вы открываете этот файл, вы должны прокомментировать эту строку следующим образом:
затем добавьте правильный путь (который уже должен быть установлен, если у вас есть устанавливается черезhttp://php-osx.liip.ch/ ссылка):
после этой модификации мой PHP наконец-то загрузил правильную установку PHP. При этом, если что-то пойдет не так, это может быть потому, что OS X сделана для работы с родной установкой PHP во время установки OS X. Чтобы вернуться, просто отмените изменение выше.
в любом случае, надеюсь, это полезно для тех, кто тратит бесчисленные часы на это.
обновление до Snow Leopard не решит вашу основную проблему обновления PHP. Apple не всегда поддерживает стороннее программное обеспечение, которое она связывает с обновлениями ОС. И полагаясь на Apple, чтобы получить вам исправление ошибки / обновление для системы безопасности, вам нужны проблемы.
кроме того, я бы рекомендовал установить через MacPorts (и сделать конфигурацию, необходимую для ее использования вместо PHP от Apple), а не пытаться обновить PHP, поставляемый Apple на месте. Все, что вы делаете /usr/bin риски перезаписи некоторыми будущими обновлениями Apple.
сохранение при нажатии клавиш, это сработало на MacOS Sierra:
Проверьте текущую версию php в терминале с помощью следующей команды,
вы видите текущую версию php в терминале, и следующая команда запускается в терминале, если вы хотите обновить свою версию php с php concat с версией, понравившейся как,
пожалуйста, перезапустите терминал, если вы закончили обновление версии php и запустите команду.
Теперь вы видите текущую версию PHP в терминале. спасибо
используйте эту команду:
лучший способ обновления скомпилировать его из исходников
см. этот учебник, который может быть полезным для вас
для обновления php7 до последней стабильной версии brew upgrade php7 или для рнр5.X до последней стабильной версии
использовать brew list чтобы проверить установленную версию
Источник