Archivo PHP Abrir/Leer/Cerrar
En este capítulo le enseñaremos cómo abrir, leer y cerrar un archivo en el servidor.
Abrir archivo PHP - fopen()
Un mejor método para abrir archivos es con la fopen()
función. Esta función le ofrece más opciones que la readfile()
función.
Usaremos el archivo de texto, "webdictionary.txt", durante las lecciones:
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
El primer parámetro de fopen()
contiene el nombre del archivo que se abrirá y el segundo parámetro especifica en qué modo se debe abrir el archivo. El siguiente ejemplo también genera un mensaje si la función fopen() no puede abrir el archivo especificado:
Ejemplo
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Sugerencia: Las funciones fread()
y fclose()
se explicarán a continuación.
El archivo se puede abrir en uno de los siguientes 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 |
Archivo de lectura PHP - fread()
La fread()
función lee de un archivo abierto.
El primer parámetro de fread()
contiene el nombre del archivo desde el que leer y el segundo parámetro especifica el número máximo de bytes para leer.
El siguiente código PHP lee el archivo "webdictionary.txt" hasta el final:
fread($myfile,filesize("webdictionary.txt"));
PHP Cerrar archivo - fclose()
La fclose()
función se utiliza para cerrar un archivo abierto.
Es una buena práctica de programación cerrar todos los archivos una vez que haya terminado con ellos. ¡No desea que un archivo abierto se ejecute en su servidor y consuma recursos!
El fclose()
requiere el nombre del archivo (o una variable que contenga el nombre del archivo) que queremos cerrar:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....
fclose($myfile);
?>
PHP Leer una sola línea - fgets ()
La fgets()
función se utiliza para leer una sola línea de un archivo.
El siguiente ejemplo genera la primera línea del archivo "webdictionary.txt":
Ejemplo
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Nota: después de una llamada a la fgets()
función, el puntero del archivo se ha movido a la siguiente línea.
PHP Verifica el final del archivo - feof ()
La feof()
función comprueba si se ha alcanzado el "fin de archivo" (EOF).
La feof()
función es útil para recorrer datos de longitud desconocida.
El siguiente ejemplo lee el archivo "webdictionary.txt" línea por línea, hasta que se alcanza el final del archivo:
Ejemplo
<?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 Leer un solo carácter - fgetc ()
La fgetc()
función se utiliza para leer un solo carácter de un archivo.
El siguiente ejemplo lee el archivo "webdictionary.txt" carácter por carácter, hasta que se alcanza el final del archivo:
Ejemplo
<?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: Después de una llamada a la fgetc()
función, el puntero del archivo se mueve al siguiente carácter.
Referencia completa del sistema de archivos PHP
Para obtener una referencia completa de las funciones del sistema de archivos, vaya a nuestra referencia completa del sistema de archivos PHP .