PHP
  Home arrow PHP arrow Page 5 - File And Directory Manipulation In PHP...
Dev Shed Forums 
Administration  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Download TestComplete 
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: 4 stars4 stars4 stars4 stars4 stars / 64
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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

    Dell PowerEdge Servers

    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

    - Setting Up a Web-based Image Hosting Service
    - Comparing Files and Databases with PHP Bench...
    - Setting Up a Web-Based Image Gallery
    - Using Timers to Benchmark PHP Applications
    - Benchmarking Applications with PHP
    - Setting Up a Web-Based File Manager: PHPfile...
    - Developing a Modular Class For a PHP File Up...
    - Setting Up a Web-Based File Manager: bfExplo...
    - Defining a Custom Function for File Uploader...
    - Parsing Child Nodes with the DOM XML extensi...
    - Creating an Error Handling Module for a PHP ...
    - Accessing Attributes and Cloning Nodes with ...
    - Retrieving Information on Selected Files wit...
    - Handling HTML Strings and Files with the DOM...
    - Building File Uploaders with PHP 5

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     




    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 3 hosted by Hostway