PHP Introduction | Using Text Files | You Can Also Read Files on the Internet?
So far, we have briefly summarized PHP file access functions. Finally, here is an important secret.
In fact, PHP’s file-related functions can access not only files stored on a local volume, but also files on the Internet in the same way.
However, you cannot modify or write to those files. Basically, you can only read data. Even so, being able to freely read data from a web site is quite powerful.
Usage is simple. In the argument where each function specifies the file, write a URL instead of a file name or file path. For example:
$lines = file("http://www.google.com/");
With code like this, you can retrieve all of the HTML code from Google’s top page.
Here is a simple usage example.
<?php
if ($_POST != null){
$url = $_POST['text1'];
$lines = file($url);
$result = implode($lines);
}
?>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>sample page</title>
</head>
<body>
<h1>Hello PHP!</h1>
<form method="post" action="./index.php">
<input type="text" name="text1" size="40"
value="<?php echo htmlspecialchars($url); ?>"><br>
<input type="submit">
</form>
<hr>
<?php echo htmlspecialchars($result); ?>
</body>
</html>
If you enter a URL in the input field and submit it, the contents of that page are downloaded and written below. Try it yourself. You will see that data from another site can be fetched easily.
When loading files over the network, however, loading may fail or take a long time, so you need to consider how to handle those cases. Still, if web data can be retrieved this easily, there should be many possible applications.