How to Read a Text File to Web Page Using PHP
PHP offers many ways to allow you to read a text file and to print its contents to a Web page. If the text file does not already exist on your Web server, use an HTML form and the PHP "move_uploaded_file" function to prompt a user to upload a file. To write the contents of text files on your server to a Web page, use the PHP "fopen" and "fread" functions to load the file into a string, then use the "echo" function to print it.
Instructions
-
-
1
Open a new text file, name it "read-file.php" and save it.
-
2
Type the following:
<?php
if(!isset($_FILES["file"]["type"])) {
?>
The first and last lines open and close a PHP tag. The middle line checks to see if the user has not already uploaded a text file.
-
-
3
Type the following to create a Web form that prompts the user to upload a text file from his computer:
<form action="" method="post" enctype="multipart/form-data">
Filename: <input type="file" name="file" id="file" /><br/>
<input type="submit" name="submit" value="Submit" />
</form>
-
4
Type the following:
<?php
} else {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
These lines happen after the user attempts to upload a text file. It informs the user if an error occurs during the upload.
-
5
Type the following:
else {
move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);
$readFile = $_FILES["file"]["name"];
$fh = fopen($readFile, 'r');
$printData = fread($fh, filesize($readFile));
fclose($fh);
echo $printData;
}
}
?>
These lines complete the file upload, then print the contents of the file on the Web page. It then closes the open statements and the PHP tag.
-
6
Save the file and upload it to your Web server.
-
1