dexter
dexter

Reputation: 1207

file doesn't open using PHP fopen

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

Upvotes: 8

Views: 22517

Answers (6)

vdbuilder
vdbuilder

Reputation: 12994

A complete example.

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

    echo($fileip);
?>

Upvotes: 2

Bee
Bee

Reputation: 21

To output the text file contents:

$fh   = fopen('myfile.txt', 'r');
$text = fread($fh, filesize('myfile.txt'));
echo $text;

Upvotes: 0

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124878

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;

Upvotes: 16

Steve Hill
Steve Hill

Reputation: 2321

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.

Upvotes: 2

wimvds
wimvds

Reputation: 12850

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.

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382881

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.

Upvotes: 3

Related Questions