Domanda

In Java posso scrivere un JSP di base index.jsp in questo modo:

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

L'effetto di ciò è che un utente che richiede home.action (o solo la directory contenente che assume <=> è un documento predefinito per la directory) vedrà <=> senza un reindirizzamento del browser, vale a dire il [forward] (< a href = "http://java.sun.com/javaee/5/docs/api/javax/servlet/RequestDispatcher.html#forward(javax.servlet.ServletRequest,%20javax.servlet.ServletResponse))" rel = " nofollow noreferrer "> 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 poiché potrei non avere accesso alla relativa configurazione di Apache sarei interessato a una soluzione che si basa solo su PHP.

È stato utile?

Soluzione

Se sei preoccupato per la disponibilità di CURL, puoi 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 un GET, ma puoi anche pubblicare un post con <=>.

Altri suggerimenti

Il trucco di Request.Forward è che ti dà una nuova, chiara richiesta all'azione che desideri. Pertanto non hai alcun residuo dalla richiesta corrente e, ad esempio, nessun problema con gli script che si basano sull'eq java di $ _SERVER ['REQUEST_URI'] essendo qualcosa.

Potresti semplicemente inserire una classe CURL e scrivere una semplice funzione per farlo:

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

}

Scarica questo in class.CURLHandler.php e puoi farlo:

ovviamente, usare $ _REQUEST non è davvero 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);
?>

Ovviamente, CURL non è installato ovunque ma abbiamo emulatori di curl nativi PHP per questo.

Inoltre, ciò offre una flessibilità ancora maggiore rispetto a Request.Fourward, in quanto è anche possibile catturare e post-elaborare l'output.

Credo che uno dei metodi analoghi più vicini sarebbe usare virtual ( ) attiva durante l'esecuzione di php come modulo apache.

  

virtuale () è una funzione specifica di Apache che è simile a    nel   mod_include. Esegue un Apache   sub-richiesta.

Se si utilizza un MVC come previsto da Zend Framework, è possibile modificare l'azione del controller o persino saltare tra le azioni del controller. Il metodo è _forward come descritto qui .

Prova questo.

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

nella pagina inclusa, la variabile $vars funzionerà come gli attributi della richiesta java

Concetti Reindirizzamento e Inoltro come in Java, possono essere ottenibili anche in PHP.

Reindirizzamento :: header("Location: redirect.php"); - (modifica dell'URL nella barra degli indirizzi)

Inoltra :: include forward.php ; - (URL invariato nella barra degli indirizzi)

È gestibile con questo & amp; altre logiche di programmazione

Puoi usare come:

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

L'uscita è necessaria nel caso in cui un output HTML sia stato inviato prima, l'intestazione () non funzionerà, quindi è necessario inviare una nuova intestazione prima di qualsiasi output al browser.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top