Question

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

Was it helpful?

Solution

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;

OTHER TIPS

From php.net:

Returns a file pointer resource on success, or FALSE on error.

Since a resource was returned, your file has successfully opened, you need further operations such as fwrite, etc on your file. So there is no error, the file is there to be manipulated.

If you get a resource id as result of the fopen call, then it succeeded, because it will return FALSE if it fails. So what exactly makes you doubt that the file is actually open?

Check http://www.php.net/fopen for more information.

You've only opened a file handle, not the file itself.

If you're using PHP5 - which you really should be for new development, you could instead use $fileip = file_get_contents("test.txt") which will read the contents of this file into the buffer.

A complete example.

<?php
    $fileip = file_get_contents("test.txt");

    echo($fileip);
?>

To output the text file contents:

$fh   = fopen('myfile.txt', 'r');
$text = fread($fh, filesize('myfile.txt'));
echo $text;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top