Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file doesn't open using PHP fopen

Tags:

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

like image 571
dexter Avatar asked Mar 09 '10 11:03

dexter


4 Answers

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;
like image 110
Tatu Ulmanen Avatar answered Nov 06 '22 01:11

Tatu Ulmanen


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.

like image 37
Sarfraz Avatar answered Nov 06 '22 02:11

Sarfraz


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.

like image 36
wimvds Avatar answered Nov 06 '22 01:11

wimvds


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.

like image 2
Steve Hill Avatar answered Nov 06 '22 02:11

Steve Hill