PHP/File Directory/fread
Содержание
fopen( ) and fread( )
<?
$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";
}
?>
fread() function reads up to length bytes from the file, returning the file"s contents.
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);
?>
fread( ) is good for when you only care about a small part of the file.
<?
$zipfile = fopen("data.zip", "r");
if (fread($zipfile, 2) != "PK") {
print "Data.zip is not a valid Zip file!";
}
fclose($zipfile);
?>
fread.php
<?php
$file = "data.txt";
$fh = fopen($file, "rt");
$userdata = fread($fh, filesize($file));
fclose($fh);
?>
Reading a file
<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( "<pre>$text</pre>" );
?>
</body>
</html>
Reading and Writing Binary Data in a File
<?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.";
}
?>