Arquivo PHP Abrir/Ler/Fechar
Neste capítulo, ensinaremos como abrir, ler e fechar um arquivo no servidor.
Arquivo aberto PHP - fopen()
Um método melhor para abrir arquivos é com a fopen()
função. Esta função oferece mais opções do que a readfile()
função.
Usaremos o arquivo de texto, "webdictionary.txt", durante as aulas:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
O primeiro parâmetro de fopen()
contém o nome do arquivo a ser aberto e o segundo parâmetro especifica em qual modo o arquivo deve ser aberto. O exemplo a seguir também gera uma mensagem se a função fopen() não conseguir abrir o arquivo especificado:
Exemplo
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Dica: As funções fread()
e fclose()
serão explicadas abaixo.
O arquivo pode ser aberto em um dos seguintes modos:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn't exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
Arquivo de leitura do PHP - fread()
A fread()
função lê de um arquivo aberto.
O primeiro parâmetro de fread()
contém o nome do arquivo a ser lido e o segundo parâmetro especifica o número máximo de bytes a serem lidos.
O código PHP a seguir lê o arquivo "webdictionary.txt" até o final:
fread($myfile,filesize("webdictionary.txt"));
PHP Fechar Arquivo - fclose()
A fclose()
função é usada para fechar um arquivo aberto.
É uma boa prática de programação fechar todos os arquivos depois de terminá-los. Você não quer um arquivo aberto rodando em seu servidor consumindo recursos!
O fclose()
requer o nome do arquivo (ou uma variável que contém o nome do arquivo) que queremos fechar:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Ler Linha Única - fgets()
A fgets()
função é usada para ler uma única linha de um arquivo.
O exemplo abaixo gera a primeira linha do arquivo "webdictionary.txt":
Exemplo
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Nota: Após uma chamada para a fgets()
função, o ponteiro do arquivo foi movido para a próxima linha.
PHP Verifique o Fim do Arquivo - feof()
A feof()
função verifica se o "fim de arquivo" (EOF) foi atingido.
A feof()
função é útil para percorrer dados de comprimento desconhecido.
O exemplo abaixo lê o arquivo "webdictionary.txt" linha por linha, até chegar ao final do arquivo:
Exemplo
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Ler Caractere Único - fgetc()
A fgetc()
função é usada para ler um único caractere de um arquivo.
O exemplo abaixo lê o arquivo "webdictionary.txt" caractere por caractere, até chegar ao final do arquivo:
Exemplo
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
Nota: Após uma chamada para a fgetc()
função, o ponteiro do arquivo se move para o próximo caractere.
Referência completa do sistema de arquivos PHP
Para uma referência completa das funções do sistema de arquivos, acesse nossa Referência completa do sistema de arquivos PHP .