Home arrow PHP arrow Page 5 - File And Directory Manipulation In PHP (part 1)

Weather Balloon - PHP

PHP comes with a powerful and flexible file manipulation API that allows developers (among other things) to read and write files, view and modify file attributes, read and list directory contents, alter file permissions, and retrieve file contents into a variety of native data structures. Find out more, inside.

TABLE OF CONTENTS:
  1. File And Directory Manipulation In PHP (part 1)
  2. Handle With Care
  3. Different Strokes
  4. Weapon Of Choice
  5. Weather Balloon
  6. A Matter Of Existence
  7. Permission Granted
  8. In Stat We Trust
  9. A Short Break
By: icarus, (c) Melonfire
Rating: starstarstarstarstar / 74
August 07, 2003

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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");

?>



 
 
>>> More PHP Articles          >>> More By icarus, (c) Melonfire
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: