PHP gets commented out in HTML

To run PHP scripts, you have to save the file as a .php file. You will also need to execute it on a server. You can't run php directly from your browser, since PHP is a HTML preprocessor - your browser has nothing to do with PHP, it only gets the HTML that is generated by the server.

So because PHP tags are not valid in HTML files, when not preprocessed by the server, the browser doesn't recognise it, so it automatically converts it to comments since it doesn't know what else to do with it.

Edit for additional information:

If you want to see the result of the processed php file, you'll need to run it from some kind of server (using Apache through XAMPP for example, but there's loads of options). If you then view the resulting page on the localhost server, it'll give you the processed php code, which should be the desired output. You can check the manual for whichever program you're using to run your server for more details on how to do this.

Note that even if you have a server running, opening the .php file locally in your browser still doesn't show you the processed result (ie. it will still show your php code as comments). You need to view the page through something like http://localhost/mypage.php, or whichever location is set as default url for your specific localhost server.


What am I doing wrong?

If the file is being served by Apache, you have not enabled the php interpreter to run on html files. Apache (by default) does not run the php interpreter on html files.

why is it being commented out?

As others have noted, a browser does not know what to do with the php tag.



If you want to interpret php in html files instead of renaming the files to .php then you can to add the .html extension to the php interpreter as below:

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

This line is in the httpd.conf file.

I'm not suggesting this is a proper way to do it but I believe it does answer your first question.

Tags:

Html

Php