sebk69
Posted on December 9, 2022
introduction
Swoole is a PHP extension including async and multithread http server.
In this tutorial, we will create a simple http server which listen to port 9501 and respond a hello world html.
install extension
You are required to have a recent linux distribution debian based (here an Ubuntu 22.04).
Lets install PHP cli :
$ apt-get install php-cli php-pear php-dev
And swoole. Run as root :
$ pecl install swoole
$ echo "extension=swoole.so" > /etc/php/8.1/cli/conf.d/90-swoole.ini
Create our project
Let's create our directory :
$ mkdir hello-world
$ cd hello-world
Now we will create our index.html file with your favorite editor
<!-- index.html -->
<html>
<body>
<h1>Hello World !</h1>
</body>
</html>
Create the server
Create a file named "serve" with this content :
#!/usr/bin/php
<?php
$server = new \Swoole\Http\Server('0.0.0.0', 9501);
$server->on('Request', function (\Swoole\Http\Request $request, \Swoole\Http\Response $response) {
$response->write(file_get_contents('index.html'));
$response->status(200);
$response->end();
});
$server->start();
Set file executable :
$ chmod 755 serve
Test your server
Run server :
$ ./serve
And go to your favorite browser, to see the result http://localhost:9501.
That's all !
Other posts on swoole
💖 💪 🙅 🚩
sebk69
Posted on December 9, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.