Is there a way I can echo the whole content of a .html file in PHP?
For example, I have some sample.html file, and I want to echo that filename, so its content should be displayed.
You should use readfile()
:
readfile("/path/to/file");
This will read the file and send it to the browser in one command. This is essentially the same as:
echo file_get_contents("/path/to/file");
except that file_get_contents()
may cause the script to crash for large files, while readfile()
won't.
file_exists()
can check whether a file or directory by that name exists, and is_file()
can be used to check that a file exists and is a regular file. In you case, is_file()
should probably be used.
echo readfile()
? Because readfile()
returns the length of the file (which seems to be 1191 bytes), if you add echo
before readfile()
, it will print the length after you print the file. Simply remove echo
and it should work. :)
Just use:
<?php
include("/path/to/file.html");
?>
That will echo it as well. This also has the benefit of executing any PHP in the file.
If you need to do anything with the contents, use file_get_contents(),
For example,
<?php
$pagecontents = file_get_contents("/path/to/file.html");
echo str_replace("Banana", "Pineapple", $pagecontents);
?>
This doesn't execute code in that file, so be careful if you expect that to work.
I usually use:
include($_SERVER['DOCUMENT_ROOT']."/path/to/file/as/in/url.html");
as then I can move files without breaking the includes.
readfile
works, but include
doesn't seem to work for images.....header('Content-Type: image/png'); include('test.png');exit;
shows a "broken" image.
include
for echoing the content of arbitrary files. If an attacker manages to upload a PHP file and you call include
on it, you've got yourself a remote code execution exploit. Use readfile()
instead.
If you want to make sure the HTML file doesn't contain any PHP code and will not be executed as PHP, do not use include
or require
. Simply do:
echo file_get_contents("/path/to/file.html");
Include
should do .) orreadfile()
.