Who still use PHP? Raise your hand! Hahaha. OK, because of self-explanatory title, here is how to do it. We will use several functions on PHP for this purpose, such as fopen
, feof
, fgets
, fwrite
and fclose
functions. Yes, that's lower level functions.
Scenario
Suppose we have remote text file stored on a website, let's called it
https://bolabanget.id/myfile.json
We want to create a PHP script that download that file (myfile.json
) to our local computer with name (myfile.local.json
).
Here is the script.
The Code
File: download_file.php
<?php // open the source file with read-only mode $source = fopen('https://bolabanget.id/myfile.json', "r") or die("Unable to open file!"); // prepare local file with write mode (if not exists it will try to create one) $target = fopen('myfile.local.json', 'w') or die("Unable to open file"); // prepare variable for content of the source file $content = ''; // tests for end-of-file on a source file pointer while(!feof($source)) { // fgets will get line from file pointer $content .= fgets($source); } // write the $content variable to target file handle fwrite($target, $content); // close all open files from our operation above fclose($source); fclose($target);
Run it like below.
php download_file.php
If everything OK, you should have file myfile.local.json
on your current folder.
Alternative Code
@hepisec comes with additional alternative on comments, we can do above task as well with the following code. This code using higher level functions such as file_get_contents
and file_put_contents
. Thank you!
<?php $src = file_get_contents('https://bolabanget.id/myfile.json'); file_put_contents('myfile.local.json', $src);
I hope you enjoy it and any additional code or comments are welcome.
Credits
- PHP Documentation at https://www.php.net/manual/en/
- Cover photo by Christina Morillo at https://www.pexels.com/photo/two-women-looking-at-the-code-at-laptop-1181263/
- Thanks to @hepisec for the additional code
Top comments (2)
You could also do it like this:
See
php.net/manual/en/function.file-ge...
php.net/manual/en/function.file-pu...
Hi hepisec,
Thanks for the comments, nice addition, I will add it on the article :)