PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

FTP y FTPS> <Lista de Protocolos/Envolturas Soportadas
Last updated: Fri, 22 Aug 2008

view this page in

HTTP y HTTPS

PHP 4, PHP 5, PHP 6. https:// a partir de PHP 4.3.0

  • http://example.com
  • http://example.com/archivo.php?var1=val1&var2=val2
  • http://usuario:contrasenya@example.com
  • https://example.com
  • https://example.com/archivo.php?var1=val1&var2=val2
  • https://usuario:contrasenya@example.com

Permite acceso de sólo-lectura a archivos/recursos a través de HTTP 1.0, usando el método HTTP GET. Una cabecera Host: es enviada con la petición para gestionar hosts virtuales basados en nombres. Si ha configurado una cadena user_agent usando su archivo ini o en el contexto de secuencia, también ésta será usada en la petición.

Warning

Cuando se usa SSL, Microsoft IIS violara el protocolo, cerrando la conexion sin mandar un indicador close_notify. PHP avisara de esto con este mensaje "SSL: Fatal Protocol Error", cuando llegue al final de los datos. Una solucion a este problema es bajar el nivel de aviso de errores del sistema para que no incluya advertencias. PHP 4.3.7 y versiones posteriores detectan servidores IIS con este problema y suprime la advertencia. Si usais la funcion fsockopen() para crear un socket ssl://, tendreis que suprimir la advertencia explicitamente.

Las redirecciones han sido soportadas desde PHP 4.0.5; si se encuentra usando una versión anterior, necesitará incluir barras de cierre en sus URLs. Si es importante conocer la URL del recurso del cual proviene su documento (luego de que todas las redirecciones han sido procesadas), necesitará trabajar con la serie de cabeceras de respuesta devueltas por la secuencia.

<?php
$url 
'http://www.example.com/pagina_de_redireccion.php';

$da fopen($url'r');

/* Antes de PHP 4.3.0, use $http_response_header
   en lugar de stream_get_meta_data() */
$meta_datos stream_get_meta_data($da);
foreach(
$meta_datos['wrapper_data'] as $respuesta) {

  
/* ¿Fuimos redirigidos? */
  
if (substr(strtolower($respuesta), 010) == 'location: ') {
    
/* actualizar $url con la ubicación desde donde fuimos redirigidos */
    
$url substr($respuesta18);
  }

}

?>

La secuencia permite acceso al cuerpo del recurso; las cabeceras son almacenadas en la variable $http_response_header. A partir de PHP 4.3.0, las cabeceras están disponibles mediante el uso de stream_get_meta_data().

Las conexiones HTTP son de sólo-lectura; no puede escribir datos o copiar archivos hacia un recurso HTTP.

Note: HTTPS es soportado a partir de PHP 4.3.0, si ha compilado el soporte para OpenSSL.

Resumen de Envoltura
Atributo Soporte
Restricción por allow_url_fopen Si
Permite Lectura Si
Permite Escritura No
Permite Adición No
Permite Lectura y Escritura Simultánea N/D
Soporte stat() No
Soporte unlink() No
Soporte rename() No
Soporte mkdir() No
Soporte rmdir() No

Es posible enviar cabeceras personalizadas con una petición HTTP antes de la versión 5 aprovechando un efecto lateral en el manejo del parámetro INI user_agent. Defina user_agent con cualquier cadena válida (tal como el valor PHP/version predeterminado) seguido de una pareja retorno-de-carro/salto-de-línea y cualquier conjunto de cabeceras adicionales. Este método funciona en PHP 4 y todas las versiones posteriores.

Example #1 Envío de cabeceras personalizadas con una petición HTTP

<?php
ini_set
('user_agent'"PHP\r\nX-MiCabeceraPersonalizada: Foo");

$fp fopen('http://www.example.com/index.php''r');
?>

Resulta en el envío de la siguiente petición:

GET /index.php HTTP/1.0
Host: www.example.com
User-Agent: PHP
X-MiCabeceraPersonalizada: Foo



FTP y FTPS> <Lista de Protocolos/Envolturas Soportadas
Last updated: Fri, 22 Aug 2008
 
add a note add a note User Contributed Notes
HTTP y HTTPS
Nick Lewis
26-Jun-2008 12:17
A note on how to deal with Cookies

To receive a cookie:

$httphandle = fopen($url,"r");
$meta = stream_get_meta_data($httphandle);
for ($j = 0; isset($meta['wrapper_data'][$j]); $j++) {
   $httpline = $meta['wrapper_data'][$j];
   @list($header,$parameters) = explode(";",$httpline,2);
   @list($attr,$value) = explode(":",$header,2);
   if (strtolower(trim($attr)) == "set-cookie") {
      $cookie = trim($value);
      break;
   }
}
fclose($httphandle);
echo $cookie;

To send a cookie:

$user_agent = ini_get("user_agent");
ini_set("user_agent",$user_agent . "\r\nCookie: " . $cookie);
$httphandle = fopen($url,"r");
fclose($httphandle);
ini_set("user_agent",$user_agent);
spazdaq
24-Oct-2007 11:27
just an FYI about digest authentication.

While one of the above http examples has the username and password info supplied with the url, this must only be for basic authentication. it does not appear to work for digest authentication. you have to handle the digest followup request on your own.
NEA at AraTaraBul dot com
30-Jul-2007 12:06
HTTP post function;

<?php
function post_it($datastream, $url) {

$url = preg_replace("@^http://@i", "", $url);
$host = substr($url, 0, strpos($url, "/"));
$uri = strstr($url, "/");

     
$reqbody = "";
      foreach(
$datastream as $key=>$val) {
          if (!empty(
$reqbody)) $reqbody.= "&";
     
$reqbody.= $key."=".urlencode($val);
      }

$contentlength = strlen($reqbody);
    
$reqheader "POST $uri HTTP/1.1\r\n".
                  
"Host: $host\n". "User-Agent: PostIt\r\n".
    
"Content-Type: application/x-www-form-urlencoded\r\n".
    
"Content-Length: $contentlength\r\n\r\n".
    
"$reqbody\r\n";

$socket = fsockopen($host, 80, $errno, $errstr);

if (!
$socket) {
  
$result["errno"] = $errno;
  
$result["errstr"] = $errstr;
   return
$result;
}

fputs($socket, $reqheader);

while (!
feof($socket)) {
  
$result[] = fgets($socket, 4096);
}

fclose($socket);

return
$result;
}
?>
Sinured
28-Jun-2007 11:24
If you want to send more than one custom header, just make header an array:

<?php
$default_opts
= array(
   
'http' => array(
       
'user_agent' => 'Foobar',
       
'header' => array(
           
'X-Foo: Bar',
           
'X-Bar: Baz'
       
)
    )
);
stream_context_get_default($default_opts);
readfile('http://www.xhaus.com/headers');
?>
dwalton at acm dot org
17-Nov-2006 08:18
As it says on this page:

"The stream allows access to the body of the resource; the headers are stored in the $http_response_header variable. Since PHP 4.3.0, the headers are available using stream_get_meta_data()."

This one sentence is the only documentation I have found on the mysterious $http_response_header variable, and I'm afraid it's misleading.  It implies that from 4.3.0 onward, stream_get_meta_data() ought to be used in favor of $http_response_header. 

Don't be fooled!  stream_get_meta_data() requires a stream reference, which makes it ONLY useful with fopen() and related functions.  However, $http_response_header can be used to get the headers from the much simpler file_get_contents() and related functions, which makes it still very useful in 5.x.

Also note that even when file_get_contents() and friends fail due to a 4xx or 5xx error and return false, the headers are still available in $http_response_header.

FTP y FTPS> <Lista de Protocolos/Envolturas Soportadas
Last updated: Fri, 22 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites