Advertisement:
Read Later
In this tutorial, I will show how to upload files from external servers into your server easily by using file_put_contents() and file_get_contents() functions. In that regard, you can even collect information from webpages on the web to collate data or scan related topics.
Usage:
file_get_contents():
This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance(1).
file_put_contents():
- If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename(2)
- Create the file if it does not exist
- Open the file
- Lock the file if LOCK_EX is set
- If FILE_APPEND is set, move to the end of the file. Otherwise, clear the file content
- Write the data into the file
- Close the file and release any locks
- Note: Use FILE_APPEND to avoid deleting the existing content of the file.
<-------------- PHP --------------->
<?php
// Get File from an external server. In this case, a Raspberry Pi picture from www.raspberrypi.org
$external_file_URL = "https://www.raspberrypi.org/homepage-9df4b/static/pi4-labelled-99c2e8935bb3cfdb27d23f634ea98a7e.png";
$external_file_content = file_get_contents($external_file_URL);
// Save File to the defined location.
$file_destination = "external_image.png";
file_put_contents($file_destination, $external_file_content);
// Show the recently uploaded file:
echo '<img src="external_image.png" style="display:block;margin:auto;width:80%;height:auto;border:2px solid white;"></img>';
?>
Result:
Save files from an external server. In this case, a Raspberry Pi picture from www.raspberrypi.org.
(1) https://www.w3schools.com/php/func_filesystem_file_get_contents.asp
(2) https://www.w3schools.com/php/func_filesystem_file_put_contents.asp