Hello. I understand the wisdom of working with files in php. In the process I came across such a problem: I open the file with fopen, write it with fwrite, read it as strings with the help of fgets and output everything to the screen. Everything works great. But I came across a problem when you need to check whether there is something in the file (orders, for example) and, if there are no order lines in the file, display "No orders", otherwise display the contents. I thought everything was simple, it turned out that not everything is so obvious to me. Help, please, satisfy curiosity. Thank.

Code:

<?php //открываем файл для записи (если его нет - создается автоматически @$fp = fopen("$DOCUMENT_ROOT/../vovan/orders/orders.txt", 'r'); if (!$fp) { echo "<p><strong>Какие-то проблемы с файлом? А если найду?<strong></p>"; exit; } while (!feof($fp)) { $order = fgets($fp, 999); echo $order . "<br /><br />"; } fclose($fp); ?> 
  • By the way, I understand that you can push all the lines into an array, then check it for emptiness. But I would like to know how to solve the issue in the case described above. - Bogdan Ostapchuk

3 answers 3

 <?php //определяем константу для имени файла define('FILENAME', 'orders.log'); // проверяем наличие содержимого в файле, считывая содержимое файла в строку if (!file_get_contents(FILENAME)) echo "Заказов нет!"; else{ // заказы существуют, обрабатываем их } ?> 

    Hello!
    To check whether the file is empty or not, you can use the filesize function ($ file_name) - it will return 0 if the file is empty.
    If you need to find a specific string in the file, then read and compare with the standard. It would be nice if the file will have a certain structure to facilitate the search for the desired content. There you look and you can make a regular season:

     (preg_match('наше регулярное выражение', file_get_contents($file_name), $resultat)) 

    something like that.

      Of course, it is better to check filesize() , but if you just need to unzip the functions of working with files, then I can say:

       file_put_contents('test.txt', ''); // case 1 //file_put_contents('test.txt', '1'); // case 2 //file_put_contents('test.txt', '12'.chr(0).'34'); // case 3 $fp = fopen('test.txt', 'r'); fseek($fp, 0, SEEK_SET); $i = 0; while ($i < 1000) // защитимся на всякий случай { if (feof($fp)) { echo 'empty'; break; } else { echo 'NOT empty: '.ord(fread($fp, 1)); } echo '<br>'; $i++; } 

      Checking the different variants of the first 3 lines, you will see that at the end of any (even empty) file it always costs 0. That is, in order to see if the beginning is the end, you need to read 1 byte () and then check feof.

      Not sure that the presence of this zerobit does not depend on the file system or the OS.