Search code examples
phprubywebrick

Using WEBrick to serve PHP web applications


I am a PHP developer who has started learning Ruby on Rails. I love how easy it is to get up and running developing Rails applications. One of the things I love most is WEBrick. It makes it so you don't have to configure Apache and Virtual Hosts for every little project you are working on. WEBrick allows you to easily start up and shut down a server so you can click around your web application.

I don't always have the luxury of working on a Ruby on Rails app, so I was wondering how I might configure (or modify) WEBrick to be able to use it to serve up my PHP projects and Zend Framework applications.

Have you attempted this? What would be the necessary steps in order to achieve this?


Solution

  • To get php support in webrick you can use a handler for php files. To do this you have to extend HttpServlet::AbstractServlet and implement the do_GET and do_POST methods. These methods are called for GET and POST requests from a browser. There you just have to feed the incoming request to php-cgi.

    To get the PHPHandler to handle php files you have to add it to the HandlerTable of a specific mount. You can do it like this:

    s = HTTPServer.new(
        :Port => port,
        :DocumentRoot => dir,
        :PHPPath => phppath
    )
    s.mount("/", HTTPServlet::FileHandler, dir, 
        {:FancyIndexing => true, :HandlerTable => {"php" => HTTPServlet::PHPHandler}})
    

    The first statement initializes the server. The second adds options to the DocumentRoot mount. Here it enables directory listings and handling php files with PHPHandler. After that the server can be started with s.start().

    I have written a PHPHandler myself as I haven't found one somewhere else. It is based on webricks CGIHandler, but reworked to get it working with php-cgi. You can have a look at the PHPHandler on GitHub:

    https://github.com/questmaster/WEBrickPHPHandler