tags:

views:

270

answers:

6

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

+1  A: 

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.

Sarfraz
+1  A: 

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.

wimvds
+1  A: 

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.

Stephen Orr
+7  A: 

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;
Tatu Ulmanen
if you want to print the contents directly, you do not need to save it into a variable first, just use readfile("test.txt");
Tobias
@Tobias, or you can also just do `echo file_get_contents(...` but I added the variables because OP had it in his question.
Tatu Ulmanen
A: 

To output the text file contents:

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