PHP/File Directory/fread
Содержание
fopen( ) and fread( )
<source lang="html4strict">
<?
$filename = "data.txt"; $fh_flowers = fopen("data.txt", "r") OR die ("Can"t open the file!\n"); $fh_logfile = fopen("$appname-log.log", "w") OR die ("Log file not writeable!\n"); $handle = fopen($filename, "a"); if (!$handle) { print "Failed to open $filename for appending.\n"; }
?>
</source>
fread() function reads up to length bytes from the file, returning the file"s contents.
<source lang="html4strict">
Its syntax is: string fread (int filepointer, int length) Reading stops either when length bytes have been read or when the end of the file has been reached. <?
$fh = fopen("data.txt", "r") or die("Can"t open file!"); $file = fread($fh, filesize($fh)); print $file; fclose($fh);
?>
</source>
fread( ) is good for when you only care about a small part of the file.
<source lang="html4strict">
<?
$zipfile = fopen("data.zip", "r"); if (fread($zipfile, 2) != "PK") { print "Data.zip is not a valid Zip file!"; } fclose($zipfile);
?>
</source>
fread.php
<source lang="html4strict">
<?php
$file = "data.txt"; $fh = fopen($file, "rt"); $userdata = fread($fh, filesize($file)); fclose($fh);
?>
</source>
Reading a file
<source lang="html4strict">
<html>
<head> <title>Reading a file</title> </head> <body> <?php $filename = "data.txt"; $filesize = filesize($filename); $file = fopen( $filename, "r" ); $text = fread( $file, $filesize ); fclose( $file ); echo( "File Size: $filesize bytes" );echo( "
$text" );
?> </body>
</html>
</source>
Reading and Writing Binary Data in a File
<source lang="html4strict">
<?php $binfile = "data.txt"; if (file_exists ($binfile)){
try { if ($readfile = fopen ($binfile, "rb+")){ $curtext = fread ($readfile,100); echo $curtext; //Hello World! fwrite ($readfile, "Hi World!"); fclose ($readfile); } } catch (exception $e) { echo $e->getmessage(); }
} else {
echo "Sorry, file does not exist.";
} ?>
</source>