|
|
 |
CapÃtulo 39. Usando archivos remotos
Siempre que allow_url_fopen esté habilitado
en php.ini, se pueden usar URLs HTTP y
FTP con la mayorÃa de las funciones que
toman un archivo como parámetro. Además URLs pueden
ser usadas con include(),
include_once(), require() y
require_once(). Consultar Apéndice M para más información sobre los
protocolos soportados por PHP.
Nota:
En PHP 4.0.3 y versiones anteriores, para usar envolturas URL,
habia que configurar PHP usando la opción de
configuración --enable-url-fopen-wrapper.
Por ejemplo, se puede usar este para abrir un archivo en un servidor
web remoto, analizar en la salida la información que se quiera,
y entonces, usar la información en una consulta a base de
datos, o simplemente para sacarlas en un estilo que coincida con el
resto de su sitio web.
Ejemplo 39-1. Obtener el tÃtulo de una página remota |
<?php
$file = fopen ("http://www.example.com/", "r");
if (!$file) {
echo "<p>Unable to open remote file.\n";
exit;
}
while (!feof ($file)) {
$line = fgets ($file, 1024);
if (eregi ("<title>(.*)</title>", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>
|
|
También se puede escribir a archivos en un servidor FTP
(siempre que se conecte como un usuario con los correctos derechos
de acceso). Solamente se pueden crear nuevos ficheros usando este
método; si se intenta sobreescribir un fichero ya existente,
la función fopen() fallará
Para conectar como un usuario distinto de 'anonymous', se necesita
especificar el nombre de usuario (y posiblemente contraseña)
dentro de la URL, tales como
'ftp://usuario:clave@ftp.example.com/ruta/hacia/archivo'. (Se puede
usar la misma clase de sintaxis para acceder a archivos via HTTP
cuando se requerÃa una autenticació de same sort of
syntax to access files via HTTP when they require Basic
authentication.)
Ejemplo 39-2. Almacenando datos en un servidor remoto |
<?php
$file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!$file) {
echo "<p>Unable to open remote file for writing.\n";
exit;
}
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>
|
|
Nota:
Podeis creer por el ejemplo anterior, que podeis usar esta tecnica
para escribir en un fichero de registro remoto. Desgraciadamente
no funcionaria porque la llamada fopen()
fallaria si el fichero remoto existe. Para usar registros
distribuidos de esa manera podeis consultar la funcion
syslog().
add a note
User Contributed Notes
Usando archivos remotos
geoffrey at nevra dot net
06-May-2006 03:53
Really, you should not send headers terminated by \n - it's not per-rfc supported by a HTTP server.
Instead, send as \r\n which is what the protocol specifies, and that regular expression would be matched anywhere, so match for something like /^Content-Length: \d+$/i on each header-line (headers are terminated by the regular expression /(\r\n|[\r\n])/ - so preg_split on that. Remeber to use the appropriate flags, I can't be arsed to look them up)
heck at fas dot harvard dot edu
14-Sep-2004 12:06
The previous post is part right, part wrong. It's part right because it's true that the php script will run on the remote server, if it's capable of interpreting php scripts. You can see this by creating this script on a remote machine:
<?php
echo system("hostname");
?>
Then include that in a php file on your local machine. When you view it in a browser, you'll see the hostname of the remote machine.
However, that does not mean there are no security worries here. Just try replacing the previous script with this one:
<?php
echo "<?php system(\"hostname\"); ?>";
?>
I'm guessing you can figure out what that's gonna do.
So yes, remote includes can be a major security problem.
geoffrey at nevra dot net
04-Aug-2003 05:25
ok, here is the story:
I was trying to download remote images, finding urls throught apache indexs with regexps and fopen()ing them to get the datas. It didn't work. I thought about binary considerations. Putting the 'b' in the second argument of fopen didn't help much, my browser still didn't want to display the images. I finally understood by watching the datas i was getting from the remote host: it was an html page ! hey, i didn't know apache sent html pages when requesting images, did you ?
the right way is then to send an http request via fsockopen. Here comes my second problem, using explode("\n\n", $buffer); to get rid of the headers. The right way is to get the value of the Content-Lenght field and use it in substr($buffer, -$Content-Lenght);
finally, here is my own function to download these files:
<?php
function http_get($url)
{
$url_stuff = parse_url($url);
$port = isset($url_stuff['port']) ? $url_stuff['port'] : 80;
$fp = fsockopen($url_stuff['host'], $port);
$query = 'GET ' . $url_stuff['path'] . " HTTP/1.0\n";
$query .= 'Host: ' . $url_stuff['host'];
$query .= "\n\n";
fwrite($fp, $query);
while ($tmp = fread($fp, 1024))
{
$buffer .= $tmp;
}
preg_match('/Content-Length: ([0-9]+)/', $buffer, $parts);
return substr($buffer, - $parts[1]);
?>
}
ho, maybe you'll say i could have parsed the page to get rid of the html stuff, but i wanted to experience http a little ;)
| |
| | Citas célebres | Nadie fue jamás un gran poeta sin ser al mismo tiempo un profundo filósofo. Samuel Taylor Coleridge Poeta, filósofo y periodista inglés (1772-1834) | | Citas en tu mail | | ©Contenidos Gratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|