PHP Download Commentary

Events happening in the community are now at Drupal community events on www.drupal.org.
Posted by mepcotterell on May 8, 2008 at 4:50pm

When the Pear module installs, it fetches three files from cvs.php.net: PEAR.php, Archive/Tar.php, and Console/Getopt.php. The reason these files aren't included with the module is because they're licensed under the PHP License and we're not allowed to host stuff that's not licensed under the GPL in the Drupal CVS repositories. When it came time to implement this part of the installation process, I came to a fork in the road.

Traditionally, whenever I wanted to download files using PHP, I used fsockopen() and fopen(), sent the HTTP headers myself, and did the whole read into buffer then write routine. It's not a bad idea. In fact, the go-pear script does just that. However, I came across two other solutions.

You can use file_get_contents() (with contexts if you're using PHP 5 or higher) to capture the contents into a variable, and then write that data into a file. This it a neat idea, but I did find a more elegant solution.

Before I continue, I'd like to comment on some assumptions. During module installation, we can make very little assumptions about what paths are writable by Drupal. This is why I chose to store all fetched files relative to file_directory_temp() and file_directory_path(), since, in a properly configured Drupal installation, one can assume that those two places are writable.

Now on to the elegant solution. Since PHP supports so many protocol wrappers for use with its filesystem functions, I found that the easiest solution to fetching files from another website was to use copy(). As long as the path to the source file is supported, the destination path is writable, and the server allows PHP to make requests on port 80 (which is should...) then copy() will just work. I like it. It's not many lines of code. It's not even two lines of code. It's one line of code, and it should work anywhere the other methods would have worked also.

Categories: , ,

AltStyle によって変換されたページ (->オリジナル) /