File And Directory Manipulation In PHP (part 1) - Weather Balloon (Page 5 of 9 )
Let's consider some more realistic examples. This next piece of code connects to a MySQL database, retrieves a result set and either displays it in a browser or writes it to a file based on a configuration variable.
<?php
// user-defined output handler
function myOutputHandler($buf)
{
global $output;
// either dump the buffer to a file
if ($output != "www")
{
$fp = fopen ("weather.html", "w");
fwrite($fp, $buf);
fclose($fp);
}
// ... or return it for printing to the browser
else
{
return $buf;
}
}
// start buffering the output
// specify the callback function
ob_start("myOutputHandler");
// output format - either "www" or "file"
$output = "www";
// send some output
?>
<html>
<head><basefont face="Arial"></head>
<body>
<?
// open connection to database
$connection = mysql_connect("localhost", "joe", "nfg84m")
or die ("Unable to connect!");
mysql_select_db("weather") or die ("Unable to select database!");
// get data
$query = "SELECT * FROM weather";
$result = mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
// if a result is returned
if (mysql_num_rows($result) > 0)
{
// iterate through resultset
// print data
while (list($temp, $forecast) = mysql_fetch_row($result))
{
echo "Outside temperature is $temp";
echo "<br>";
echo "Forecast is $forecast";
echo "<p>";
}
}
else
{
echo "No data available";
}
// close database connection
mysql_close($connection);
// send some more output
?>
</body>
</html>
<?php
// end buffering
// this will invoke the user-defined callback
ob_end_flush();
?>
This example uses PHP's output buffering functions to create a custom output buffer handler. When ob_end_flush() is called, PHP will invoke the user-defined function myOutputHandler(), and will pass the entire contents of the buffer to it as a string. It is now up to the function to decide what to do with the buffer - either print it to the Web browser or write it to a static HTML file for later use.
Sometimes, overwriting file contents is not exactly what you need - in some cases, what you really want to do is append to an existing file. This is common when dealing with log files, as in the example below:
<?php
// set log file
function writeLog($msg)
{
// set file to write
$filename = "error.log";
// open file
$fh = fopen($filename, "a") or die("Could not open log");
// create the data string to be written
$str = date("[Y-m-d h:i:s] ", mktime()) . $msg . "\r\n";
// write to log
fwrite($fh, $str) or die("Could not write to log");
// close file
fclose($fh);
}
writeLog("NOTIFY: Initiating database connection");
// open connection to database
$connection = mysql_connect("localhost", "joe", "nfg84m")
or
writeLog("FATAL: Unable to connect!");
mysql_select_db("weather") or writeLog("FATAL: Unable to select
database!");
// get data
$query = "SELECT * FROM books";
$result = mysql_query($query) or writeLog("FATAL: Error in query: $query.
" . mysql_error());
// if a result is returned
if (mysql_num_rows($result) > 0)
{
// iterate through resultset
// print data
while (list($title, $author) = mysql_fetch_row($result))
{
echo "$title - $author <br>";
}
}
else
{
echo "No data available";
}
// close database connection
mysql_close($connection);
writeLog("NOTIFY: Terminating database connection");
?>
In this case, every call to the writeLog() function will add to the existing log file contents, rather than overwriting them.
How about copying a file? With the new file_get_contents() and
file_put_contents() functions - both of which are binary-safe - it's a snap!
<?php
// set source file
$src = "/bin/ls";
// set destination file
$dst = "/tmp/list";
// read source
$contents = file_get_contents($src) or die ("Could not read source file");
// write destination
file_put_contents($dst, $contents) or die("Could not write destination
file");
?>
Next: A Matter Of Existence >>
More PHP Articles
More By icarus, (c) Melonfire