When we are working on some enormous projects, we usually link one file to another. Because we don’t want to add all our code in just one file. And we want to make it more structured and readable. If you are working on a PHP project, you may need to link External PHP file to HTML file For example, we have our separate files for the navbar, header, and footer named navBar.php, header.php, and footer.php, respectively. In our index.html, which is our landing page, we want to add these files to this html page. So, how to do that?
As we know that HTML and PHP are distinct languages, and we cannot directly link these files. In this article, you will learn two different ways to connect one or more external PHP files to HTML.
Table of Contents
Changing file extension:
Changing the file extension is the most common and easy solution you can adopt to accomplish this task.
Let us take a simple example of having two files index.html and nav.php. And we want to link the PHP file to the HTML.
You need to change that .html file to .php file. In this way, you can easily link one php file to another.
Here, we use the include() function. This statement takes all the code that is present in a given file and copies that into a file that calls this function.
You can also use require() function instead of include(). They both are the same except one thing, which is when the specified file is not found, then the include() function throws a warning but continues the code execution. Whereas the require() will cause a fatal error and stops further execution.
Creating a .htaccess file:
For some reason, if you don’t want to change your html file to php, there is one way to do so, you need to follow the following steps:
- Create a .htaccess file in the root directory of your project.
- Copy the following text in the file:
AddType application/x-httpd-php .html .htm
It will force the Apache server to parse HTML or HTM file as PHP script.
In this piece of code, you can see that we have our file in .html. This code will give us the same result without changing our file type.
In this article, we have seen two different methods to link External PHP file to HTML. If you are working on some small projects, you can change your html file to a php file. But if you don’t want to change your file type, you can follow the second method. I hope this helps you to find your answer.