问题
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:
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;
回答2:
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.
回答3:
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.
回答4:
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.
回答5:
A complete example.
<?php
$fileip = file_get_contents("test.txt");
echo($fileip);
?>
回答6:
To output the text file contents:
$fh = fopen('myfile.txt', 'r');
$text = fread($fh, filesize('myfile.txt'));
echo $text;
来源:https://stackoverflow.com/questions/2408614/file-doesnt-open-using-php-fopen