PhpStorm: Run a single PHP script locally

Run a simple PHP script file locally within PhpStorm. Some mini code which you want to test, a regex, a symfony console app or what ever fancy code you’ve written 😉

Josef Glatz
Productiveness

--

I often want to test just some small code snippet before I’m sure that it does the correct thing. Basically var_dump the return of a small function. Mostly! Of course, I can use xdebug - but sometimes - I don’t want to 👻 !

How I did it before?

Screenshot of CodeRunner: Executed a small function within a PHP file

I found CodeRunner years ago in the Apple App Store — a small macOS application with which you can run simple code (not only PHP). I spent some bucks, of course. At some point I thought I was doing it wrong.. I use PhpStorm everyday since many years for all kind of web projects — there must have been a better solution for me!

Why not use PhpStorm therefore? I would say, there’s no reason TO NOT USE PhpStorm (if you use it anyway). Enjoy all the benefits of your beloved IDE. So let’s check the possibilities!

What does PhpStorm offer for such a task?

Well, I think I don’t know all possibilities of PhpStorm. But two of them are

  • executing PHP executables on your workstation
  • executing PHP within a Docker container

I’m known for running lot of “stuff” in a docker environment. But in this case, I don’t see any benefit at this point. I have many different versions of PHP CLI interpreters already installed on my workstation. Seems enough for me. Reason enough to only write about the first method mentioned:

Using a local PHP CLI interpreter/executable

On macOS: Use php executables installed via homebrew

I know, you’ve also a default PHP interpreter within macOS. But hey you need more then one version, if you have plenty of different PHP projects or want to test any new PHP feature!

Install Homebrew (if you have not installed it anyway): https://brew.sh/

Install preferred PHP version(s): brew install php70 php71

Open a PhpStorm project and open the Project Preferences. Then open Languages & Frameworks > PHP:

Open the CLI Interpreters dialog by pressing button next to CLI Interpreter select box:

Press + button and select the interpreter you want to add:

The list will be different on your workstation

Press OK once you’ve selected an interpreter:

Make sure the CLI Interpreter was selected and the correct PHP language level is set: Then click OK!

You’re ready! Create a PHP file (could even be a scratch file) with some code:

Choose Run > Run.. (or press CMD+ALT+R) and select Run on your actual file:

Great, you’ve completed this tutorial! Check the output of your script in the Run panel:

I hope you enjoyed it! 🎃

Now clap and have fun!

--

--