Php script inside a *.php file or inside *.html file

Hi everyone,
This is a php script I wrote and saved inside a “test.php” file:


<?php
echo "Hello World!";
?>

When I run it, I get:

“Hello world”

on my screen.
I tried to run the same code from within a “*.html” file whereby the following code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>vegan food catering</title>
	</head>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>

When I ran that html file nothing showed up on the screen.
Can anyone tell me please where I went wrong in my html file?
Thanks

The only way you’ll get that to work is to change your web server to send .html files to the PHP parser. By default .html files are processed the same as .htm files.

Or simply save the file as a PHP file by changing the extension. Eg, save as “my_script.php” rather than “my_script.html”.

Thanks !

Thats even more practical :slight_smile: Thanks a lot SamA74 ! I think i’ll start with what you suggegted !

I thought that was TOO obvious, and assumed the OP wanted HTML files processed as PHP. :slight_smile:

I feel it’s a good point to follow the chain of operation here (as i understand it.);

When you call to www.yourserver.com/index.php;
The Webserver (most likely Apache, so i’ll call it that) receives the request.
Apache sees an extension of .php; in it’s config files, it knows that .php files need to be sent into the PHP module to be processed first (hence, PHP: Hypertext Pre-processor. Dont ask me why it’s a recursive acronym.). So it sends it there.
The PHP component kicks in, and parses all RELEVANT code segments (things encased in <?php ?>, or if you have short tags, <? ?>, etc.). It then sends the fully formed HTML back to Apache.
Apache receives the HTML, and kicks it out to the browser, which then interprets it into the webpage display.

The PHP component ignores everything outside it’s own tags - which means it’s fully acceptable to have HTML, JS, CSS, etc in a “.php” file. Which is why simply renaming your file will work.

I don’t think anyone knows the answer to that. :wink:

There was a time when some people thought showing the .php extension was a poor idea, though I don’t see any reason why, especially nowadays.

Anyway, if you feel comfortable editing your httpd.conf file you can send all types of extensions to the PHP engine if you wanted to

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