Portable PHP in the Browser using WebAssembly

Created on November 12, 2023 at 11:28 am

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

Essentially, WebAssembly ORG 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 ORG to leverage the power of PHP ORG in the browser. Let’s see how.

The php-wasm project

There’s a project called php-wasm which uses WebAssembly ORG to run PHP ORG in the browser. It is a port of the PHP ORG CLI version 8.2.11 to WebAssembly ORG , by compiling the original source code to WebAssembly ORG 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 ORG 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 WORK_OF_ART !" ; ?> </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 PERSON (@amit_merchant) on CodePen.

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

It’s all HTML and yet, PHP ORG 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 PERSON ( ‘ ready ‘ , () => { php . run ( ‘ <?php echo "Hello, world!"; ‘ ); });

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

Learn more about the project: php-wasm

Connecting to blog.lzomedia.com... Connected... Page load complete