If you’re a web developer, aspiring to be one, or simply interested in learning PHP, it’s important to know how to run PHP on your local machine. In this blog post, we’ll walk you through the process of setting up and running PHP on your Mac.
Step 1: Check if PHP is Already Installed
Mac OS X comes with PHP pre-installed, but it might not be the latest version. First, let’s check if PHP is already installed on your Mac. Open the Terminal application and type the following command:
php -v
If PHP is installed, you’ll see the version number displayed in the terminal. If it’s not installed or you want to use a different version, continue to the next step.
Step 2: Install Homebrew
Homebrew is a package manager for macOS that makes it easy to install and manage software. We will use Homebrew to install the latest version of PHP. If you don’t have Homebrew installed, you can install it by running the following command in your terminal:
/bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)”
Once the installation is complete, run this command to ensure Homebrew is set up correctly:
brew doctor
Step 3: Install PHP with Homebrew
Now that Homebrew is installed, you can use it to install the latest version of PHP. Run the following command in your terminal:
brew install php
After the installation is complete, you can check the PHP version again with:
php -v
Step 4: Create a PHP File
Now that PHP is installed, let’s create a simple PHP file to test our setup. Open your favorite text editor and create a new file called “index.php”. Then, add the following code to the file:
Save the file in a folder (e.g., “php_test”) where you want to run your PHP script.
Step 5: Run PHP in the Terminal
To run the PHP file you created, navigate to the folder containing the “index.php” file in the terminal. For example, if you saved the file in a folder called “php_test” on your desktop, you would type:
cd ~/Desktop/php_test
Next, run the PHP file with the following command:
php -S localhost:8000
This command will start a local PHP server on port 8000. You can now open your web browser and navigate to http://localhost:8000 to see your “Hello, World!” message.
Conclusion
You’ve successfully installed PHP on your Mac and learned how to run PHP files using the terminal. This setup is perfect for learning PHP and developing web applications on your local machine. As you dive into PHP development, you may also want to explore additional tools and services, such as MAMP or XAMPP, which provide a more comprehensive development environment with additional features like databases and web server software.