¿Por qué fsockopen tienen problemas de rendimiento y no fopen al enviar una solicitud POST en PHP?

StackOverflow https://stackoverflow.com/questions/1930074

Pregunta

He intentado dos implementaciones diferentes para simular la publicación de un formulario. Uno de ellos utiliza fsockopen (ejemplo aquí: http://www.faqts.com/knowledge_base /view.phtml/aid/7962 ) y el otro utiliza fopen (ejemplo aquí: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl ).

Me encontré con algunos problemas graves de rendimiento con fsockopen - cuando me paso a través de él con un depurador, todo parece funcionar bien, pero cuando no asociar el depurador la página tarda muuuucho tiempo para cargar (probablemente más de 10 segundos). fopen funciona perfectamente (además de que no tengo que analizar fuera de las cabeceras de respuesta). ¿Alguien sabe por qué fsockopen tendría estos problemas de rendimiento? ¿Tiene que ver con la configuración de tiempo de espera?

He incluido mi código a continuación.


//fsockopen implementation
/**
 * The class that posts form data to a specified URL.
 * @package Core
 * @subpackage Classes
 */
class SU_form_poster_class
{
    /**
     * The file handle which is created when a form is posted.
     * @var resource
     */
    protected $file_handle;

    protected $port;

    protected $timeout;


    /**
     * Creates a new instance of this class.
     * @param int $timeout the timeout (in seconds) to wait for the request
     * @param int $port the port to make the request on
     */
    public function __construct($timeout = 30, $port = 80)
    {
        $this->timeout = $timeout;
        $this->port = $port;
    }

    /**
     * Sends a POST request to a specified page on a specified host with the
     * specified data.
     * @param string $path the part of the URL that specifies the page (including
     * the query string)
     * @param string $host the host part of the URL to post to
     * @param string $request_data the data to be posted in "query string" format,
     * e.g. name1=value1&name2=value2&name3=value3
     */
    public function do_post($path, $host, $request_data)
    {
        $err_num = 0;
        $err_str = '';
        $this->file_handle = fsockopen($host, $this->port, $err_num, $err_str, $this->timeout);
        if (!$this->file_handle)
        {
            throw new RuntimeException($err_str, $err_num);
        }
        else
        {
            $request = 'POST '.$path." HTTP/1.1\r\n".
                'Host: '.$host."\r\n".
                "Content-type: application/x-www-form-urlencoded\r\n".
                'Content-length: '.strlen($request_data)."\r\n\r\n".
                $request_data;

            fputs($this->file_handle, $request);
        }
    }

    /**
     * Retrieves data from the most recent request.
     * @return string the response
     */
    public function get_last_response()
    {
        if (!$this->file_handle)
        {
            throw new RuntimeException('A valid request must be made first.');
        }
        else
        {
            $response = '';
            $linenum = 0;
            while (!feof($this->file_handle))
            {
                $line = fgets($this->file_handle, 1024);
                if ($linenum > 6)
                {
                    $response .= $line;
                }
                ++$linenum;
            }
            fclose($this->file_handle);
            return $response;
        }
    }
}


/**
 * The class that posts form data to a specified URL.
 * @package Core
 * @subpackage Classes
 */
class SU_form_poster_class
{
    /**
     * The file handle which is created when a form is posted.
     * @var resource
     */
    protected $stream;

    /**
     * Sends a POST request to a specified page on a specified host with the
     * specified data.
     * @param string $url
     * @param string $request_data the data to be posted in "query string" format,
     * e.g. name1=value1&name2=value2&name3=value3
     */
    public function do_post($url, $request_data)
    {
        $params = array(
            'http' => array(
                'method' => 'POST', 'content' => $request_data
            )
        );

        $context = stream_context_create($params);
        $this->stream = fopen($url, 'rb', false, $context);
        if (!$this->stream)
        {
            throw new RuntimeException('Stream was not created correctly');
        }
    }

    /**
     * Retrieves data from the most recent request.
     * @return string the response
     */
    public function get_last_response()
    {
        if (!$this->stream)
        {
            throw new RuntimeException('A valid request must be made first.');
        }
        else
        {
            return stream_get_contents($this->stream);
        }
    }
}

¿Fue útil?

Solución

HTTP predeterminado 1,1 a conexiones persistentes. Esto significa que la conexión no obtiene automáticamente cerrado y feof() no vuelve verdadera hasta que los tiempos de espera de solicitud. Para evitar esto envía la cabecera Connection: close o el uso de HTTP 1.0 que no soporta conexiones persistentes.

Otros consejos

  

¿Alguien sabe por qué lo haría fsockopen   tener estos problemas de rendimiento? Hace   Tiene que ver con el tiempo de espera   entorno?

he tenido problemas en el pasado con fsockopen sobre SSL -. Pero eso no es lo que su pedir

¿Ha intentado utilizar el curl_ * familia de funciones en lugar, que podría ayudar?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top