Search code examples
phphtml

PHP gets commented out in HTML


I created a simple HTML webpage that includes the following PHP code in the HTML code.

<?php echo date('l, F jS, Y'); ?>

When I run the HTML page and I view the source code it shows:

<!--?php echo date('l, F jS, Y'); ?-->

What am I doing wrong? Why is it being commented out?

The HTML webpage file has the extension .html.


Solution

  • 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.