How do I add PHP code/file to HTML(.html) files?

2018-12-31 02:57发布

I can't use PHP in my HTML pages. For example, index.html. I've tried using both:

<? contents ?> 

and

<?php contents ?> 

Neither of these work. My server offers PHP, and when I use a the .php extension, it works properly. Is this a problem or do I have to change the preferences in php.ini?

标签: php html
10条回答
低头抚发
2楼-- · 2018-12-31 03:33

For having .html files parsed as well, you need to set the appropriate handler in your server config.

For Apache httpd 2.X this is the following line

AddHandler application/x-httpd-php .html

See the PHP docu for information on your specific server installation.

查看更多
浪荡孟婆
3楼-- · 2018-12-31 03:33

For combining HTML and PHP you can use .phtml files.

查看更多
回忆,回不去的记忆
4楼-- · 2018-12-31 03:43

If you only have php code in one html file but have multiple other files that only contain html code, you can add the following to your .htaccess file so it will only serve that particular file as php.

<Files yourpage.html>
AddType application/x-httpd-php .html 
//you may need to use x-httpd-php5 if you are using php 5 or higher
</Files>

This will make the PHP executable ONLY on the "yourpage.html" file and not on all of your html pages which will prevent slowdown on your entire server.

As to why someone might want to serve php via an html file, I use the IMPORTHTML function in google spreadsheets to import JSON data from an external url that must be parsed with php to clean it up and build an html table. So far I haven't found any way to import a .php file into google spreadsheets so it must be saved as an .html file for the function to work. Being able to serve php via an .html file is necessary for that particular use.

查看更多
步步皆殇っ
5楼-- · 2018-12-31 03:45

I think writing PHP into an .html file is confusing and anti-natural. Why would you do that??

Anyway, if what you want is to execute PHP files and show them as .html in the address bar, an easiest solution would be using .php as normal, and write a rule in your .htaccess like this:

RewriteRule ^([^.]+)\.html$ $1.php [L]
查看更多
余生请多指教
6楼-- · 2018-12-31 03:49

By default you can't use PHP in HTML pages.

To do that, modify your .htacccess file with the following:

AddType application/x-httpd-php .html
查看更多
步步皆殇っ
7楼-- · 2018-12-31 03:49

Create an empty file using notepad and name it .htaccess ,Then copy that file in your project directory and add this line and save.

AddType application/x-httpd-php .htm .html

else save the .html file using .php as php can support html,and save it in computer/var/www/html path(linux)

查看更多
登录 后发表回答