Wednesday, October 05, 2005

PHP Tips -- File & Output Buffer Functions

File
/* Creates a file with a unique filename in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.
*/
string tempnam ( string dir, string prefix)

/* Given a string containing a path to a file, this function will return the base name of the file. If the filename ends in suffix this will also be cut off.
*/
string basename ( string path [, string suffix])

/* Given a string containing a path to a file, this function will return the name of the directory.
*/
string dirname ( string path)

bool file_exists("file_name");

is_file("file_name");
is_dir("dir_name");
is_readable();
is_writable();
is_executable();
int filesize(); // bytes
timestamp fileatime("file_name"); // when a file was last accessed
timestamp filemtime("file_name"); // when a file was last modified
timestamp filectime("file_name"); // when a file was last changed(unix) / created(other platform)

//Deletes filename
bool unlink ( string filename [, resource context]);

// Attempts to set the access and modification
// time of the file named by filename to the value given by time.
// If the file does not exist, it is created.
bool touch ( string filename [, int time [, int atime]])

// Reading ends when length - 1 bytes have been read,
// on a newline (which is included in the return value),
// or on EOF (whichever comes first).
// If no length is specified, the length defaults to 1k(1024 bytes).
string fgets ( resource handle [, int length]);

string fread ( resource handle, int length);

flock( $fp, LOCK_SH/LOCK_EX/LOCK_UN);

Output Buffer
bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]])

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

Example:

<?php
// Buffer the current html page so we can write it to file later
ob_start();
$var = "Generated html script";
?>

<html>
<head>
<title>HTMLGEN</title>
</head>
<body>
Loading.... <br />
<?php echo $var; ?>
More contents!<br />
</body>
</html>

<?php
// Write the buffered HTML file
$fp = fopen($htmlFile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
?>

No comments: