简体   繁体   中英

How to run PHP locally on MacOS

I need a php sandbox on my local.

But I have to make just one class in PHP.

In NODE.JS I can do the following:

test.js

// my test js script
console.log('hello world')

I can run it like this:

~$ node test.js
~$ hello world
~$ 

I would like to do something like this:

test.php

echo('hello world');

I would like to run it like this:

~$ php test.php
~$ hello world
~$ 

Is there any way to do this, without installing apache and everything? I just like to have a php sandbox on my mac.

OSX comes with php installed:

$ which php # => /usr/bin/php

So you can run your php file. But don't forget to include your code between <?php... ?> .

// test.php
<?php
echo("Hello world")
?>

So now you can run in your terminal:

$ php test.php
$ Hello world%

Apache is not needed.

download and install xampp or any alternative that runs an Apache server on local machine should do the trick.

edit: Just googled a little myself, apparently you can just download php and run the web server from cli now, $ php -S localhost:8000

First of all, you have to check if php is present on your mac:

php --version

should give you something like (as php is installed by default on mac):

PHP 7.4.10 (cli) (built: Sep 3 2020 18:19:30) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies with Zend OPcache v7.4.10, Copyright (c), by Zend Technologies

Once you've checked that, you can create your php file containing just one line:

<?php echo "Hello world\n"; ?>

prints:

Hello World

You do not need anything else than php.

Apache and php are already installed on MacOS

Alternatively You can use docker or just find sandbox on-line, eg https://sandbox.onlinephpfunctions.com/

I had a similar problem when I came into Mac, and before using Homebrew my temporary solution is mamp . Simply a quick solution that helped me work.

then there are articles that explain well how to create a lamp en mac development environment: Setup Local (L)AMP Stack on Mac with Homebrew

Try opening a localhost. You can use XAMPP etc...

You can install only pah with Homebrew.

Make sure the brew is updated

brew update
brew upgrade

Install PHP 7.2

brew install php72

Wait for the installation to finish, you're now running on PHP 7.2. You may run $ php -v to check the current PHP version on your machine.

now create file test.php

<?php
 echo "hello";

and run

php path/to/test.php

I would recommend Docker...

Since it's running in a virtual machine already, it's the perfect sandbox. And you can add new services or change the setup, like trying new PHP versions, different webservers, or other operating system quite easily.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM