2009-01-11 17 views
9

In Java Riesco a scrivere una JSP veramente di base index.jsp in questo modo:PHP ha un equivalente di RequestDispatcher.forward di Java?

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

L'effetto di questo è che un utente che richiede index.jsp (o solo la directory contenente assumendo index.jsp è un documento predefinito per la directory) vedrà home.action senza un redirect del browser, ovvero il [avanti] (http://java.sun.com/javaee/5/docs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse)) accade sul lato server.

Posso fare qualcosa di simile con PHP? ho il sospetto che sia possibile configurare Apache per gestire questo caso, ma dal momento che non potrebbe avere accesso al relativo Apache con figurazione Sarei interessato a una soluzione che si basa solo su PHP.

risposta

0

Se si è preoccupati della disponibilità di CURL, è possibile utilizzare file_get_contents() e gli stream.Impostazione di una funzione come:

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; 
} 

Questo imposta solo su un GET, ma si può fare un post con file_get_contents() pure.

+0

Ci sono molte cose sbagliate in questo approccio. Per uno, non passerà lungo alcuna intestazione e funzionerà solo con una richiesta di tipo GET. – troelskn

+0

e fallirà miseramente se PHP è in esecuzione in modalità provvisoria ... – SchizoDuckie

+0

... ma viene accettato: D –

-3

È possibile utilizzare come:

header ("Location: /path/"); 
exit; 

L'uscita è necessario solo nel caso in cui un output HTML è stato inviato prima, l'intestazione() non funziona, quindi è necessario inviare nuova intestazione prima qualsiasi uscita il browser.

+0

Questo la soluzione coinvolge il cliente, che non è il caso del reindirizzamento interno. – MatthieuP

1

Il trucco di Request.Forward è che ti offre una nuova, pulita richiesta per l'azione desiderata. Quindi non hai residu dalla richiesta corrente, e per esempio, nessun problema con gli script che si basano su java eq di $ _SERVER ['REQUEST_URI'] è qualcosa.

Si può solo cadere in una classe CURL e scrivere una semplice funzione per fare questo:

<?php 
/** 
* CURLHandler handles simple HTTP GETs and POSTs via Curl 
* 
* @author SchizoDuckie 
* @version 1.0 
* @access public 
*/ 
class CURLHandler 
{ 

    /** 
    * CURLHandler::Get() 
    * 
    * Executes a standard GET request via Curl. 
    * Static function, so that you can use: CurlHandler::Get('http://www.google.com'); 
    * 
    * @param string $url url to get 
    * @return string HTML output 
    */ 
    public static function Get($url) 
    { 
     return self::doRequest('GET', $url); 
    } 

    /** 
    * CURLHandler::Post() 
    * 
    * Executes a standard POST request via Curl. 
    * Static function, so you can use CurlHandler::Post('http://www.google.com', array('q'=>'belfabriek')); 
    * If you want to send a File via post (to e.g. PHP's $_FILES), prefix the value of an item with an @ ! 
    * @param string $url url to post data to 
    * @param Array $vars Array with key=>value pairs to post. 
    * @return string HTML output 
    */ 
    public static function Post($url, $vars, $auth = false) 
    { 
     return self::doRequest('POST', $url, $vars, $auth); 
    } 

    /** 
    * CURLHandler::doRequest() 
    * This is what actually does the request 
    * <pre> 
    * - Create Curl handle with curl_init 
    * - Set options like CURLOPT_URL, CURLOPT_RETURNTRANSFER and CURLOPT_HEADER 
    * - Set eventual optional options (like CURLOPT_POST and CURLOPT_POSTFIELDS) 
    * - Call curl_exec on the interface 
    * - Close the connection 
    * - Return the result or throw an exception. 
    * </pre> 
    * @param mixed $method Request Method (Get/ Post) 
    * @param mixed $url URI to get or post to 
    * @param mixed $vars Array of variables (only mandatory in POST requests) 
    * @return string HTML output 
    */ 
    public static function doRequest($method, $url, $vars=array(), $auth = false) 
    { 
     $curlInterface = curl_init(); 

     curl_setopt_array ($curlInterface, array( 
      CURLOPT_URL => $url, 
      CURLOPT_CONNECTTIMEOUT => 2, 
      CURLOPT_RETURNTRANSFER => 1, 
      CURLOPT_FOLLOWLOCATION =>1, 
      CURLOPT_HEADER => 0)); 

     if (strtoupper($method) == 'POST') 
     { 
      curl_setopt_array($curlInterface, array(
       CURLOPT_POST => 1, 
       CURLOPT_POSTFIELDS => http_build_query($vars)) 
      ); 
     } 
     if($auth !== false) 
     { 
       curl_setopt($curlInterface, CURLOPT_USERPWD, $auth['username'] . ":" . $auth['password']); 
     } 
     $result = curl_exec ($curlInterface); 
     curl_close ($curlInterface); 

     if($result === NULL) 
     { 
      throw new Exception('Curl Request Error: '.curl_errno($curlInterface) . " - " . curl_error($curlInterface)); 
     } 
     else 
     { 
      return($result); 
     } 
    } 

} 

Proprio discarica presente in class.CURLHandler.php e si può fare questo:

naturalmente, utilizzando $ _REQUEST non è sicuro (dovresti controllare $ _SERVER ['REQUEST_METHOD']) ma ottieni il punto.

<?php 
include('class.CURLHandler.php'); 
die CURLHandler::doRequest($_SERVER['REQUEST_METHOD'], 'http://server/myaction', $_REQUEST); 
?> 

Naturalmente, CURL non è installato ovunque ma abbiamo native PHP curl emulators for that.

Inoltre, questo ti dà ancora più flessibilità rispetto Request.Forward come si potrebbe anche prendere e post-process l'uscita.

+0

curl non è abilitato di default in php. Anche arricciatura farà un'altra richiesta http che strega significa più utilizzo della CPU. – Ivan

+0

Sì, ma .forward fa qualcosa di simile anche a FAIK. Non hai alcun materiale ambientale associato alla richiesta corrente. Pertanto, deve succedere un'altra richiesta HTTP, non si desidera eseguire questo script nello stesso ambito. in quanto può causare problemi con variabili definite. – SchizoDuckie

1

Credo che uno dei metodi analoghi più vicini sarebbe utilizzare la funzione virtual() mentre si esegue php come un modulo apache.

virtuale() è una funzione Apache che è simile a in mod_include. Esegue una sotto-richiesta Apache .

1

Se si utilizza un MVC come Zend Framework, è possibile modificare l'azione del controller o saltare tra le azioni del controller. Il metodo è _forward come described here.

1

Prova questo.

function forward($page, $vars = null){ 
    ob_clean(); 
    include($page); 
    exit; 
} 

sulla pagina inclusa la variabile $vars funzionerà come attributi della richiesta java

0

Concetti reindirizzare e in avanti come in Java, può essere realizzabile in PHP troppo.

Redirect :: header("Location: redirect.php"); - (URL nei cambiamenti barra degli indirizzi)

avanti :: include forward.php ; - (URL invariato a barra degli indirizzi)

sua gestibile con questo altro & logiche di programmazione