file doesn't open using PHP fopen

dexter picture dexter · Mar 9, 2010 · Viewed 19.8k times · Source

i have tried this:

    <?php
$fileip = fopen("test.txt","r");

?>

this should have opened the file in read only mood but it doesn't the test.txt file is in same folder as that of index.php (main project folder)

the file doesn't open

and when i put echo like :

echo $fileip;

it returned

Resource id #3

Answer

Tatu Ulmanen picture Tatu Ulmanen · Mar 9, 2010

The file did open just fine, you cannot echo it like that because it's a file pointer, not the contents of the file itself. You need to use fread() to read the actual contents, or better yet, use file_get_contents() the get the content straight away.

Doing it your way:

$handle = fopen("test.txt", "r");
$fileip = fread($handle, filesize($filename));
fclose($handle);

echo $fileip;

Or, using file_get_contents():

$fileip = file_get_contents("test.txt");

echo $fileip;