Categories
PHP Web

From Scratch PHP Project with the PHP Built-in Web Server

If you are starting a PHP project from scratch you will probably use the PHP built-in web server during development.

This tutorial follows the folder structure of a composer based project:

project/
├── vendor/
│   └── autoload.php
├── web/
│   └── index.php
├── composer.json
└── router

Now, let us create a script that can serve as the router for PHP’s built-in web server. Save a file named router to the root of the project. We could also name it router.php.

<?php
/*
 * PHP Server
 *
 * To start the built-in web server run from the root directory:
 * |> php -S localhost:9999 -t web router
 */
$path = urldecode(
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

if ($path !== '/' && file_exists(__DIR__.'/web'.$path)) {
    return false;
}

unset($path);

require_once __DIR__.'/web/index.php';

This router directs all non-existing file requests in the web folder to the web/index.php file. Then, it unsets the $path variable to remove it from the global scope.

Next, take a look at the web/index.php file. This basic file handles a few things that need to be addressed on every request:

  1. Browsers try to load a favicon.ico on most requests (even if you do not have one). If that file does not exist then the web/index.php file will be used. This is not what we want so let’s exit right away if that happens.
  2. Set the timezone to UTC.
  3. Set the encoding to UTF-8.
  4. Include composer’s autoload.php file.
<?php
if ( '/favicon.ico' == $_SERVER['REQUEST_URI'] ) {
    header( 'Content-Type: image/vnd.microsoft.icon' );
    exit;
}

date_default_timezone_set('UTC');
mb_internal_encoding('UTF-8');

require_once __DIR__ . '/../vendor/autoload.php';

// Now your code...

The web/index.php file can contain any code you want but this is how I like to set things up for the beginning of a web request. If you are new to PHP, but not to programming, https://phptherightway.com/ is a great resource.

From here we can start the web server using the terminal.

php -S localhost:9999 -t web router

This command breaks down into a few parts.

  1. php -S localhost:9999 defines the web server’s web host address.
  2. -t web router directs the PHP built-in server to use the web folder as the webroot and to use the router file as the router (use router.php if you saved the file with the PHP extension).

And that’s it. Happy Coding!

P.S. If you are using Xdebug be sure you have the following added to your php.ini file:

xdebug.remote_autostart=1
xdebug.remote_enable=1
xdebug.remote_port=9000
xdebug.remote_host=127.0.0.1
xdebug.idekey=PHPSTORM

If you need more help or have issues connecting to Xdebug and PHPStorm I have an article on that.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.