...

View Full Version : Reading & Writing Functions



Element
01-04-2006, 05:13 AM
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

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($handle, false); // 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.

ralph l mayo
01-04-2006, 05:41 AM
a few notes:



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'.

missing-score
01-04-2006, 06:23 AM
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:


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.

Element
01-04-2006, 07:44 AM
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:


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.

missing-score
01-04-2006, 08:22 AM
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.

WA
01-04-2006, 01:00 PM
I'm moving this over to the PHP forum, as due to the problems with the code this isn't suitable here...

Element
01-04-2006, 06:53 PM
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.

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.

firepages
01-05-2006, 02:29 AM
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.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum