How to run a webphar PHP file from built-in PHP 5.4 webserver? How to run a webphar PHP file from built-in PHP 5.4 webserver? php php

How to run a webphar PHP file from built-in PHP 5.4 webserver?


php -S localhost:80 -t /path/to/phar isn't going to work since the -t argument is meant to be used for directories. The trick is that the php webserver supports passing a router as argument. Therefore, suppose your phar is in /tmp (it can be anywhere), this is how you create a simple router, and setup the webserver:

echo '<?php require("/path/to/phar");'>/tmp/router.phpphp -S localhost:80 /tmp/router.php


php -S localhost:8080 phpinfo.phar

That seemed to work for me just fine from a simple phar file I created to out put phpinfo();

I did notice in the PHP docs, when creating the PHAR file, that you seem to need to setup stubs for CLI and WWW interfaces.

http://php.net/manual/en/phar.buildfromdirectory.php

<?php// create with alias "project.phar"$phar = new Phar('project.phar', 0, 'project.phar');// add all files in the project$phar->buildFromDirectory(dirname(__FILE__) . '/project');$phar->setStub($phar->createDefaultStub('cli/index.php', 'www/index.php'));

EDIT

Specifically, this is what I did.

#!/usr/bin/env php<?php$phar = new Phar('phpinfo.phar', 0, 'phpinfo.phar');$phar->buildFromDirectory(__DIR__ . '/phpinfo');$phar->setStub($phar->createDefaultStub('index.php'));

to create a phar file of a directory:

phpinfo/└── index.php

and index.php was just:

<?php phpinfo();


After hours of messing around with built-in web server, finally found the solution to what you are looking for. The key is router file for the web server. Follow below procedure

1) Create a router.php file for built-in web server with following content

    $path = $_SERVER["REQUEST_URI"];    if($pathPosition = strpos($path,'/myapp') !== false){        //Request has been made to Phar-ed application        $pathPosition += strlen('/myapp');        $file = substr($path, $pathPosition);        //Here include the base path of your Phar-ed application with file path        //I placed myphar.phar and router.php in the root directory for this example        require_once("phar://myphar.phar/$file");        exit;    }    return FALSE;

What this does: It checks the Uri for your application name, in my case "/myapp" and then extract the file path you want to access. Then includes the desired phared file into current script and exits. Else process the request as normal.

2) Start the built-in web server as follows:

     php -S localhost:80 -t . router.php

What this does: Fires up the built-in webserver making current directory as document root folder and uses router.php as router file (Placed in the same folder)

3) Make a request in browser like this:

    http://localhost/myapp/foo/bar

You will get the Phar-ed file from you application .phar file

Let me know in case of questions.

Note: You can also use regex to match the Uri pattern in router.php