PHP/File Directory/fwrite
Содержание
Appending to a file
<source lang="html4strict">
<?php
# for Linux use... # $filename = "/home/mike/Desktop/newfile.txt"; # for Windows use... $filename = "C:\\newfile.txt"; $file = fopen( $filename, "a" ); $string = "\t\t\tOctober 13,2010"; fwrite( $file, $string ); fclose( $file );
?> <html>
<head> <title>Appending to a file</title> </head> <body> <?php $file_length = filesize( $filename ); echo( "$filename is now $file_length bytes" ); ?> </body>
</html>
</source>
A simple access counter
<source lang="html4strict">
<?
$access = "data.txt"; $visits = @file($access); $current_visitors = $visits[0]; ++$current_visitors; $fh = fopen($access, "w"); @fwrite($fp, $current_visitors); fclose($fh);
?>
</source>
fwrite() function writes string to the file.
<source lang="html4strict">
Its syntax is: int fwrite (int filepointer, string string [, int length]) Writing stops either after length characters have been written or after the end of string has been reached. <? $data = "data"; $filename = "data.txt"; if ( is_writeable($filename) ) :
$fh = fopen($filename, "a+"); $success = fwrite($fh, $data); fclose($fh);
else :
print "Could not open $filename for writing";
endif; ?>
</source>
fwrite.php
<source lang="html4strict">
<?php
$subscriberInfo = "data"; $fh = fopen("/data.txt", "at"); fwrite($fh, $subscriberInfo); fclose($fh);
?>
</source>
Storing user information in a text file
<source lang="html4strict">
<html>
<body>
<?
$form ="<form action=\"index.php\" method=\"post\">
<input type=\"hidden\" name=\"seenform\" value=\"y\">
Give us your personal info!
Your Name:
<input type=\"text\" name=\"name\" value=\"\">
Your Email:
<input type=\"text\" name=\"email\" value=\"\">
Your Preferred Language:
<select name=\"language\">
<option value=\"\">Choose a language:
<option value=\"English\">English
<option value=\"Spanish\">Spanish
</select>
Your Occupation:
<select name=\"job\">
<option value=\"\">What do you do?:
<option value=\"student\">Student
<option value=\"programmer\">Programmer
</select>
<input type=\"submit\" value=\"submit!\">
</form>";
if ($seenform != "y") :
print "$form";
else :
$fd = fopen("user_information.txt", "a"); $name = str_replace("|", "", $name); $email = str_replace("|", "", $email); $user_row = $name."|".$email."|".$language."|".$job."\n"; fwrite($fd, $user_row) or die("Could not write to file!"); fclose($fd); print "Thank you!";
endif; ?> </body> </html>
</source>
<source lang="html4strict">
<?php $fh = fopen("/tmp/cookie-data","w") or die("can"t open: $php_errormsg"); if (-1 == fwrite($fh,$_COOKIE["flavor"])) { die("can"t write: $php_errormsg") }; fclose($fh) or die("can"t close: $php_errormsg"); ?>
</source>
Writing data to a file
<source lang="html4strict">
<?php $fh = fopen("/tmp/cookie-data","w") or die("can"t open file"); if (-1 == fwrite($fh,$_COOKIE["flavor"])) { die("can"t write data"); } fclose($fh) or die("can"t close file"); ?>
</source>