Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    Regular Coder Element's Avatar
    Join Date
    Jul 2004
    Location
    Lynnwood, Washington, US
    Posts
    855
    Thanks
    2
    Thanked 2 Times in 2 Posts

    Reading & Writing Functions

    I wrote these simple, yet usefull functions for file handling. They were for someone, but he didn't want them, so I'm sharing them here. If you have anything to add to them, feel free to post the upgrade/modification/etc.

    If a moderator,/administrator feels this isn't usefull, and deletes it, please PM with your reason why, it makes it easier for future referense on what to post of mine.

    PHP Code:
    <?php

    function writeToFile($handle$data$openAs "w") {
      if(
    file_exists($handle) && is_file($handle) && is_writable($handle)) {
        if(
    $openAs !== "r" && $handle = @fopen($handle$openAs)) {
          if(@
    fputs($data$handle)) {
            @
    fclose($handle);
            return 
    true;
          } else {
            @
    fclose($handle);
            echo 
    "<b>fputs()</b> Error writing to file, or the setting was for reading!";
            return 
    false;
          }
        } else {
          echo 
    "<b>fopen()</b> Error opening file!";
          return 
    false;
        }
      } else {
        echo 
    "<b>is_writable()</b> The file is either not writable, or doesn't exist!";
        return 
    false;
      }
    }

    function 
    readFromFile($handle$array true) {
      if(
    is_readable($handle)) {
        if(
    $file = @fopen($handle"r")) {
          if(
    $array) {
            
    $return = array();
            while(!
    feof($file)) {
              
    $return[] = fgets($file);
            }
            @
    fclose($file);
            return 
    $return;
          } else {
            
    $return "";
            while(!
    feof($file)) {
              
    $return .= fgets($file);
            }
            @
    fclose($file);
            return 
    $return;
          }
        } else {
         echo 
    "<b>fopen(), flock()</b> The file could not be opened and locked!";
         return 
    false;
        }
      } else {
        echo 
    "<b>is_readable()</b> The file is either not readable, or doesn't exist!";
        return 
    false;
      }
    }

    // This example was for the useer, a compact piece of code to replace a file.
    $handle "/home/user/public_html/data/archive1-a-1.dat";
    @
    unlink($handle);
    $data "Temporarily unavailable.";
    if(
    writeToFile($handle$data"a+")) {
      echo 
    "File replacement, complete.";
    } else {
      echo 
    "File replacement failed, see above error.";
    }

    $file_contents readFromFile($handlefalse); // Read file into a string
    echo $file_contents;

    $file_contents readFromFile($handle); // Read file into array, like file() function
    print_r ($file_contents);

    ?>
    Planning on implementing the usage of ports, in the opening of files, for remote files, etc.
    Last edited by Element; 01-04-2006 at 06:57 PM.

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    a few notes:

    PHP Code:
    function readFromFile($handle$array == true) { // parse error, should be assignment and not equality
      
    if(file_exists($handle) && is_file($handle) && is_readable($handle)) { // shortenable to just is_readable($handle), because it doesn't throw an error on invalid filenames and if it's true it implies existence and filehood
        
    if($file = @fopen($filename"r")) { // causes function to always fail unless $filename become $handle
          
    if($array == true) { // redundant true == true
            
    $return = array();
            while(!
    feof($file)) {
              
    $return[] = fgets($file);
            }
            @
    fclose($file);
            return 
    $return;
          } else {
            
    $return "";
            while(!
    feof($file) { // parse error, missing )
              
    $return .= fgets($file);
            }
            @
    fclose($file);
            return 
    $return;
          }
        } else {
         
    trigger_error("The file could not be opened and locked!"); // I'd throw new Exception('msg', code) here so problems can (potentially) be caught and dealt with intelligently instead of halting execution
         
    return false;
        }
      } else {
        
    trigger_error("The file is either not readable, or doesn't exist!");
        return 
    false;
      }

    Also returning as an array is kind of pointless since regular strings can be accessed as a character array anyway. Ie, $string = 'test'; echo $string[0]; yields 't'.
    Last edited by ralph l mayo; 01-04-2006 at 05:45 AM.

  • #3
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Element, I must ask you to check your code works before posting, as ralph l mayo said, a parse error would have occured. Also, your reading file function is basically an alias for file() or file_get_contents(), and as the PHP.net Manual states:

    Quote Originally Posted by PHP.net
    Note: If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.
    (the code above is basically what you used).

    Also, you use trigger error but dont give any sensible error returns... IMO they should be warnings and not just notices.

  • #4
    Regular Coder Element's Avatar
    Join Date
    Jul 2004
    Location
    Lynnwood, Washington, US
    Posts
    855
    Thanks
    2
    Thanked 2 Times in 2 Posts
    Thanks, ralph on the tips. And as far as error triggering, I'd need an example, having problems with PHP.net CSS again and it wrather bothers me. My friend told me to put them in there instead of returning what was wrong so a user wouldn't have to do something like:

    PHP Code:
    if(writeToFile($handle$data"w")==true) { 
    To use it in a if/else statement.


    >> missing-score

    If thats not plain and obvious, missing-score. However, as I said I'm planning on adding the port support, because it would be able to work on example.com/somefile.php?a=a&b=b&c=c&so_on=so_on parse`, as file_get_contents() wouldn't work on files like that for me when I was fetching a remote profile from a site. That is my goal for that functon, and also I only wrote it so it wasn't just the writeToFile function.

  • #5
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    file_get_contents can operate on standard fopen wrappers, I can open any http:// and ftp:// URLs through file_get_contents, although it will depend on your php.ini setting.

  • #6
    WA
    WA is offline
    Administrator
    Join Date
    Mar 2002
    Posts
    2,596
    Thanks
    2
    Thanked 19 Times in 18 Posts
    I'm moving this over to the PHP forum, as due to the problems with the code this isn't suitable here...
    - George
    - JavaScript Kit- JavaScript tutorials and 400+ scripts!
    - JavaScript Reference- JavaScript reference you can relate to.

  • #7
    Regular Coder Element's Avatar
    Join Date
    Jul 2004
    Location
    Lynnwood, Washington, US
    Posts
    855
    Thanks
    2
    Thanked 2 Times in 2 Posts
    The code has been fixed and is suitable just fine. You also shouldn't move a file that is asking for no help which is also, not suitable for the PHP forum. The problems in the code were fixed last night besides the error messages, which I just switched around a bit.

    Also, missing score, can you give me an example of get_file_contents() ? I could care less that it can open http:// and ftp://, thats once again obvious, but with php files with dynamic content, it won't open the file at all, and you have to use fopen() and some crazy port in the higher end of the digits.

    Edit: I see now that Velox server can use file_get_contents() on the URL I was needing to use for my script, and it works on it. I guess it was either the two servers I was on, or some small error in the URL I didn't include in the fopen() method.
    Last edited by Element; 01-04-2006 at 10:00 PM.

  • #8
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,058
    Thanks
    10
    Thanked 96 Times in 94 Posts
    Element the code was moved since whilst wrapping up basic functionality has its uses this was not one suitable for the snippets section, as mentioned
    file_get_contents('http://blah.com:8080/blah?d=w&w=r');
    works fine for the file read operation as does fopen & file();

    If you are chmod()'ding and flock()'ing etc then abstraction of code can make sense and you are on the right tracks, error reporting of why a file operation did or did not work is very useful and not something you want to write every time you perform a file operation.

    That said your functions are not quite doing enough to be anything more than a basic wrapper, the fact that you are looking at error reporting is good, its just not handled that well in that regular PHP error messages will do pretty much the same.

    How to handle errors in file operations is something that I don't think anyone gets right ... because there is no right the problem is that whether a failed file operation is fatal or non-fatal depends on how and when it is called in the logic of the application.
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •