PHP Velho Oeste 2024

Usando arquivos remotos

Enquanto allow_url_fopen estiver disponível no arquivo php.ini, você pode usar URLs HTTP e FTP com a maioria das funções que recebem um nome de arquivo como parâmetro. Além disso, URLs podem ser usadas com as funções include, include_once, require e require_once (allow_url_include precisa estar habilitado para isto). Veja Protocolos e Wrappers suportados para mais informações sobre protocolos suportados pelo PHP.

Por exemplo, você pode usar isso para abrir um arquivo em um web server remoto, avaliar a saída para a informação que você precisa, e então usar a informação em uma query de banco de dados, ou simplesmente mostrar em um estilo que combine com o resto do seu website.

Exemplo #1 Pegando o título de uma página remota

<?php
$file
= fopen ("http://www.example.com/", "r");
if (!
$file) {
echo
"<p>Incapaz de abrir arquivo remoto.\n";
exit;
}
while (!
feof ($file)) {
$line = fgets ($file, 1024);
/* Isso só funciona se o título e suas tags estiverem na mesma linha */
if (eregi ("<title>(.*)</title>", $line, $out)) {
$title = $out[1];
break;
}
}
fclose($file);
?>

Você também pode escrever arquivos em um servidor FTP (presumindo que você se conectou como um usuário com os direitos de acesso corretos). Você só pode criar arquivos novos usando esse método. Se você tentar sobrescrever um arquivo que já existe, a chamada para fopen() falhará.

Para conectar como um usuário diferente de 'anonymous', você precisa especificar o nome de usuário (e possivelmente a senha) dentro da URL, como 'ftp://user:password@ftp.example.com/path/to/file'. (Você pode usar o mesmo tipo de sintaxe para acessar arquivos via HTTP quando eles requerem autenticação Basic).

Exemplo #2 Guardando informação em um servidor remoto

<?php
$file
= fopen ("ftp://ftp.example.com/incoming/outputfile", "w");
if (!
$file) {
echo
"<p>Incapaz de abrir arquivo remoto para escrita.\n";
exit;
}
/* Escreva informação aqui. */
fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n");
fclose ($file);
?>

Nota:

Você talvez tenha tido a idéia, pelo exemplo acima, de usar essa técnica para escrever para um arquivo de log remoto. Infelizmente isso não funcionaria porque a chamada a fopen() falhará se o arquivo remoto já existir. Para fazer logs distribuídos dessa maneira, você deve dar uma olhada na função 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