Tuesday, February 7, 2017

PHP require and include functions don't work

In almost all server side scripting, it is very common practice to include pages like header and footer into a page. Recently, while migrating a legacy PHP project, noticed that functions require_once, require and include don't work in some cases even after trying to include them either with absolute path or relative paths.

We observed that, the page that is being included, named as header.php contains HTML code embedded in tags as shown below. After removing  outer php tags, the page is successfully included and page is rendered successfully.


So, what caused the inclusion to fail? PHP processor tries to interpret all the code between php tags . As shown above in this case, the outer PHP tags contain HTML code which cannot be interpreted by PHP processor. Thus the inclusion fails. 

Use php tags only to process php code as shown in the code snippet to embed URLs for hyperlink tags. Don't embed HTML content inside these tags.