Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Portable PHP in the Browser using WebAssembly

Wouldn’t it be nice if you could run PHP in the browser and that too without installing anything on your machine? Well, a technology called WebAssembly lets you do just that.

Essentially, WebAssembly is a binary instruction format for a stack-based virtual machine. It is designed as a portable target for the compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

We can use WebAssembly to leverage the power of PHP in the browser. Let’s see how.

The php-wasm project

There’s a project called php-wasm which uses WebAssembly to run PHP in the browser. It is a port of the PHP CLI version 8.2.11 to WebAssembly, by compiling the original source code to WebAssembly using Emscripten.

To use it, you can include the php-tags.js script from a CDN like so.

<script 
    async 
    type = "text/javascript" 
    src = "https://cdn.jsdelivr.net/npm/php-wasm/php-tags.mjs"
></script>

Next, you can run PHP code in the browser by using the <script> tag with the type attribute set to text/php like so.

<script type = "text/php" data-stdout = "#output" data-stderr = "#error">
<?php 
  echo "Hello World!";
?>
</script>

<div id="output"></div>

As you can tell, the data-stdout and data-stderr attributes are used to specify the element IDs where the output and error messages will be displayed respectively.

Here’s it in the action in the CodePen below.

See the Pen PHP in Browser by Amit Merchant (@amit_merchant) on CodePen.

Note: This demo might not work in mobile browsers due to the lack of WASM support.

It’s all HTML and yet, PHP is running in the browser. Isn’t that cool?

Using it as npm package

You can also use it as an npm package. You can install it like so.

npm install php-wasm

And then, you can use it like so.

php.addEventListener('ready', () => {
	php.run('<?php echo "Hello, world!";');
});

This is because you need to wait for the WASM module to be loaded before you can run any PHP code. The ready event is fired when the WASM module is loaded and ready to run PHP code.

Learn more about the project: php-wasm

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?