Search code examples
phpjsphttpforwarding

Does PHP Have an Equivalent of Java's RequestDispatcher.forward?


In Java I can write a really basic JSP index.jsp like so:

<% request.getRequestDispatcher("/home.action").forward(request, response); %>

The effect of this is that a user requesting index.jsp (or just the containing directory assuming index.jsp is a default document for the directory) will see home.action without a browser redirect, i.e. the [forward](http://java.sun.com/javaee/5/docs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)) happens on the server side.

Can I do something similar with PHP? I suspect it's possible to configure Apache to handle this case, but since I might not have access to the relevant Apache configuration I'd be interested in a solution that relies on PHP alone.


Solution

  • If you are concerned about CURL availability then you could use file_get_contents() and streams. Setting up a function like:

    function forward($location, $vars = array()) 
    {
        $file ='http://'.$_SERVER['HTTP_HOST']
        .substr($_SERVER['REQUEST_URI'],0,strrpos($_SERVER['REQUEST_URI'], '/')+1)
        .$location;
    
        if(!empty($vars))
        {
             $file .="?".http_build_query($vars);
        }
    
        $response = file_get_contents($file);
    
        echo $response;
    }
    

    This just sets up a GET, but you can do a post with file_get_contents() as well.