PHP Velho Oeste 2024

Empleo de ficheros remotos

Siempre que allow_url_fopen esté habilitado en php.ini, se pueden usar los URL de HTTP y FTP con la mayoría de las funciones que toman un nombre de fichero como parámetro. Además, los URL se pueden emplear con las sentencias include, include_once, require y require_once (desde PHP 5.2.0, allow_url_include debe estar habilitado para ello). Véanse Protocolos y Envolturas soportados para más información sobre los protocolos admitidos por PHP.

Por ejemplo, se puede emplear para abrir un fichero en un servidor web remoto, analizar la salida de los datos deseados, y usar dichos datos en una consulta a una base de datos, o simplemente para mostrarlos en un estilo que haga juego con el del sitio web.

Ejemplo #1 Obtener el título de una página remota

<?php
$fichero
= fopen ("http://www.example.com/", "r");
if (!
$fichero) {
echo
"<p>Imposible abrir el fichero remoto.\n";
exit;
}
while (!
feof ($fichero)) {
$línea = fgets ($fichero, 1024);
/* Esto solo funciona si el título y sus etiquetas están en una línea */
if (preg_match ("@\<title\>(.*)\</title\>@i", $línea, $salida)) {
$título = $salida[1];
break;
}
}
fclose($fichero);
?>

También se puede escribir en ficheros de un servidor FTP (siempre que se esté conectado como un usuario con los permisos de acceso correctos). Con este método solamente se pueden crear ficheros nuevos. Si se intenta sobreescribir un fichero que ya existe, la llamada a la función fopen() fallará.

Para conectarse como un usuario distinto a 'anonymous', es necesario especificar el nombre de usuario (y posiblemente la contraseña) dentro del URL, tal como 'ftp://usuario:contraseña@ftp.example.com/ruta/al/fichero'. (Se puede utilizar la misma sintaxis para acceder a ficheros mediante HTTP cuando se requiera autenticación básica).

Ejemplo #2 Almacenar datos en un servidor remoto

<?php
$fichero
= fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!
$fichero) {
echo
"<p>Imposible abrir el fichero remoto para escritura.\n";
exit;
}
/* Escribir los datos aqui. */
fwrite ($fichero, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($fichero);
?>

Nota:

Con el ejemplo anterior, se podría tener la idea de que se puede emplear esta técnica para escribir un fichero de registro remoto. Desafortunadamente esto no funcionaría porque la llamada a la función fopen() fallará si el fichero remoto ya existe. Para realizar registros distribuidos como ese, debería echar un vistazo a syslog().

add a note add a note

User Contributed Notes 4 notes

up
8
slva dot web dot sit at gmail dot com
10 years ago
If  allow_url_fopen is disabled in php.ini you can use CURL function for check file exist:

<?php
$ch
= curl_init("http://www.example.com/favicon.ico");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode >= 400 -> not found, $retcode = 200, found.
curl_close($ch);
?>
up
-4
anon
4 years ago
The following functions can't access external files if allow_url_fopen is disabled:

- fopen
- file_put_contents
- copy

I don't know if this is documented anywhere else, but I couldn't find it. Feel free to delete this post if so.
up
-33
kalidass dot jst at gmail dot com
8 years ago
public function get_url($request_url) {

$curl_handle = curl_init();
    curl_setopt($curl_handle, CURLOPT_URL, $request_url);
    curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 0);
    curl_setopt($curl_handle, CURLOPT_TIMEOUT, 0);
    curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, FALSE); 
    curl_setopt($curl_handle, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
    $JsonResponse = curl_exec($curl_handle);
    $http_code = curl_getinfo($curl_handle);

  return($JsonResponse);
}
get_url("http://www.example.com");
up
-70
heck at fas dot harvard dot edu
19 years ago
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.
To Top