Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation of fgets() function in PHP

Tags:

php

I'm usinng Windows operating system and new to PHP. Namely I'm trying to implement php function fgets() in php file:

$file = fopen("$DOCUMENT_ROOT/Chapter02/test.txt","r");

while(! feof($file))
  {
  echo fgets($file). "<br />";
  }

fclose($file);

I have created test.txt file with the following content:

Hello, this is a test file.
There are three lines here.
This is the last line.

as example from http://www.w3schools.com/

Both files, .php and .txt are located in a directory:

C:/wamp/www/Chapter02/

but after execution this php file, is not showing anything, and shall show:

Hello, this is a test file.
There are three lines here.
This is the last line.

I suppose, I'm making a mistake in a path "$DOCUMENT_ROOT/Chapter02/test.txt", but I really don't know where the mistake is...

I would highly appreciate your help:)

kind regards,

Ivana

like image 442
Ivana Avatar asked Aug 05 '26 12:08

Ivana


1 Answers

Possible pitfalls:

  • Your document not existing (your $DOCUMENT_ROOT variable may not be set)
  • Your document being empty

fgets() works in exactly the same way across all main PHP platforms, so I am pretty sure that your problem is on the existence of the file rather than the actual reading code (which looks good)

Try to var_dump($DOCUMENT_ROOT) and manually check if the file exists (using file_exists()). This might uncover the bug.

By the way, W3Schools is a horrible website to learn from, as much as I hate to say this. A lot of their info is either out of date, broken, or completely ambiguous.

like image 52
Sébastien Renauld Avatar answered Aug 07 '26 00:08

Sébastien Renauld