Web20 University

Can PHP Be Embedded in HTML?

Yes, PHP can be embedded in HTML. It’s a common practice because PHP is a server-side language designed to create dynamic web content.

A PHP script is enclosed in special start and end processing instructions <?php and ?> that allow you to jump into and out of “PHP mode”.

Here are some examples:

Example 1: Basic PHP script in HTML

<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

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

</body>
</html> 

In this example, when the PHP section is processed by the server, it will output “Hello World!” to the HTML.

Example 2: PHP Variables in HTML

<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page</h1>
<p>Some text.</p>
<p>Some more text.</p>
<?php
$name = "John Doe";
echo "Hello, $name!";
?>

</body>
</html>

In this example, the PHP code declares a variable and then uses it in an echo statement. The resulting HTML sent to the client would include “Hello, John Doe!”.

Example 3: Dynamic HTML content with PHP

<!DOCTYPE html>
<html>
<body>

<h1>Today's Date:</h1>

<p>Today is: <?php echo date('Y-m-d'); ?></p>

</body>
</html>

This example outputs the current date in ‘Year-Month-Day’ format. Each time you load the page, the date will be up-to-date because it’s generated dynamically by the PHP date() function.

Remember, for these examples to work, your server must be set up to process PHP code and the files should typically have a .php extension.