PHP File and Syntax Overview
A PHP file can contain HTML, JavaScript, jQuery, and PHP code, allowing you to create dynamic web pages. The syntax of PHP is easy, and you can start your PHP code with <?php
and end it with ?>
. Since PHP scripts run on the server, they output plain HTML text, which the browser then displays. PHP files should be saved with a .php
extension.
Basic PHP Example
<?php
$var = "Hello";
echo $var;
?>
Output:
Hello
In the example above, we use <?php
to start the PHP code and ?>
to end it. However, ending the PHP script with ?>
is optional; even without it, the script will run correctly.
PHP Without Closing Tag Example
<?php
$var = "Hello";
echo $var;
Output:
Hello
As shown, both scripts provide the same output, and omitting the closing tag can help avoid potential errors caused by extra whitespace or characters after the closing ?>
.
Important Note on PHP Open Tags
When using the opening <?php
tag, be careful of adding whitespace after it. The correct tag is <?php
, but adding unnecessary characters like a space (<?php
) will not work properly.
Examples:
<?php/*it would not work*/ echo "Whitespace Test 1"?>
<?php /*php followed by space*/ echo "Whitespace Test2<br>"?>
<?php
/*php followed by end-of-line*/ echo "Whitespace Test3<br>"?>
<?php /*php followed by tab*/ echo "Whitespace Test4"?>
Output:
Whitespace Test2
Whitespace Test3
Whitespace Test4
As shown, there must be some whitespace character (like space, tab, or newline) after <?php
for the code to function properly.
Short Open Tags (<?=
)
Short open tags, such as <?=
, were introduced in PHP version 5.4.0. These tags are shorthand for <?php echo
. Before using them, make sure the short_open_tag
setting is enabled in your PHP configuration (php.ini
). You can enable this in XAMPP/WAMP by configuring short_open_tag = On
in the php.ini
file, usually located at C:\xampp\php\php.ini
.
Short Open Tag Example
<?php
$var = "Hello";
?>
<?= $var ?>
Output:
Hello
Using PHP with HTML
PHP can be easily integrated with HTML, allowing you to add dynamic content directly into your HTML structure.
<!DOCTYPE html>
<html>
<head>
<title>PHP With HTML</title>
</head>
<body>
<h2>This is PHP with HTML</h2>
<?php
echo "<h2>Hello PHP with HTML</h2>";
?>
</body>
</html>
Output:
This is PHP with HTML
Hello PHP with HTML
This example demonstrates how PHP can be embedded within HTML to create dynamic content for your web pages.