PHP
  Home arrow PHP arrow Page 5 - File And Directory Manipulation In PHP (part 1)
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

File And Directory Manipulation In PHP (part 1)
By: icarus, (c) Melonfire
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 65
    2003-08-07


    Table of Contents:
  • File And Directory Manipulation In PHP (part 1)
  • Handle With Care
  • Different Strokes
  • Weapon Of Choice
  • Weather Balloon
  • A Matter Of Existence
  • Permission Granted
  • In Stat We Trust
  • A Short Break

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


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

    ?>



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

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 hosted by Hostway
    Stay green...Green IT