How to know if a file has data in php?

2

I would like to know what is the correct way to know when a file has information inside it.

Current code:

$myfile = fopen("app/vista/html5/encabezado/encabezado.html", "r") or die("Unable to open file!");
if ($myfile == false) {
  echo "No tiene nada";
} else {
  echo "Tiene algo";
}
fclose($myfile);

The only thing I'm looking for is to know if it has at least one character or line as content.

    
asked by David 27.03.2018 в 20:02
source

2 answers

4

This can be achieved in the following way:

<?php
 $archivo = "url o direccion del archivo";
 if(filesize($archivo) > 0){
  echo "El archivo tiene contenido";

 } else {
  echo "El archivo esta vacio";
 }
?>

filesize returns the size of the file in bytes, or FALSE (and generates an error level E_WARNING) in case of an error.

If the file contains data, it must have a different size of 0 bytes, in the case of a plain text document.

    
answered by 27.03.2018 / 20:12
source
3

You can use the filesize function. It determines the size of the file, without having to read it completely.

Here is a code using a ternary operator to determine if the file is empty or not.

Can be used in combination with file_exists to avoid a Warning in error_log, when the file does not exist:

EDIT: You have to deny the checks to make it work. I had escaped

$nombre_fichero = 'archivo.txt';
$vacio=(!file_exists($nombre_fichero) || !filesize($nombre_fichero)) ? FALSE : TRUE;

/*Prueba de la variable*/
var_dump($vacio);

When empty, the value of the variable will be:

bool(false)

And when you have data:

bool(true)

The advantage of this method is that it will also check whether the file exists or not. When it does not exist, the value will always be false .

    
answered by 27.03.2018 в 20:16