note 72521 deleted from function.fopen by danbrown

From: Date: Mon, 08 Jun 2009 23:36:07 +0000
Subject: note 72521 deleted from function.fopen by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-156551@lists.php.net to get a copy of this message
Note Submitter: download dot function at nospam dot com ---- Thanks very much to flobee (15-Jan-2006) who provided a download() function with realtime writing instead of buffering the result, very clever. However, your function is too basic, it has almost zero error checking, and also forgets to close file handles in one case(!). Not only that, but you have mixed up the meaning of return values, where you have made false = no errors and true = error occured. I've added full error checking, optimized the code, and of course corrected the return values. True = Success. Here are the changes: 1. If the file that we are saving to already exists it removes any read-only flag so that it can be overwritten. 2. Correctly formats the URL we are downloading from so that fopen() understands it. For instance, if you pass a URL with spaces, those have to be encoded to %20, and any html entities such as & have to be decoded to & or the fopen() call fails, I've added these transformations so that the user does not have to pre-format the URL before passing it to download(). 3. I've added the closing of file handles at a point where you forgot to. 4. The error messages are all handled by fopen/fwrite, so if the function has returned false for an error, you need to enable "Display_Errors" in the INI to see what happened, or alternatively use "ini_set('display_errors', 1);" at the top of your PHP file. I don't think there is _anything_ else that can be improved, but if you can think of something then you are welcome to submit your version. function download ($file_source, $file_target) { // Preparations $file_source = str_replace(' ', '%20', html_entity_decode($file_source)); // fix url format if (file_exists($file_target)) { chmod($file_target, 0777); } // add write permission // Begin transfer if (($rh = fopen($file_source, 'rb')) === FALSE) { return false; } // fopen() handles if (($wh = fopen($file_target, 'wb')) === FALSE) { return false; } // error messages. while (!feof($rh)) { // unable to write to file, possibly because the harddrive has filled up if (fwrite($wh, fread($rh, 1024)) === FALSE) { fclose($rh); fclose($wh); return false; } } // Finished without errors fclose($rh); fclose($wh); return true; }

« previous php.notes (#156551) next »