php tags

Part of the course: php for beginners

php tags open and close

1. Introduction to PHP Tags

What are PHP tags?
PHP tags are special “start” and “end” markers that tell the server where the PHP code begins and ends. They look like this:

<?php
// your PHP code goes here
?>

Anything written between <?php and ?> is treated as PHP code and will be executed by the server — not shown directly to the user.

Why does PHP need tags to run code?
Because PHP is a server-side language that is often mixed with HTML.
The browser cannot understand PHP directly — only HTML, CSS, and JavaScript.

So PHP needs tags to clearly separate itself from the normal HTML:

  • The server reads the file and looks for <?php ... ?>

  • Only the code inside these tags is processed (executed) by the PHP interpreter

  • Everything outside is treated as plain HTML and sent to the browser unchanged

In simple words:
PHP tags act like “doors” that open and close a PHP mode inside an HTML file.

2. Different Types of PHP Opening Tags

PHP supports several ways to start (open) a PHP code block. Some are recommended, while others are outdated or dependent on server settings.

✅ 1. Standard PHP Tag — Recommended and Always Safe

<?php
echo "Hello, world!";
?>
  • This is the official and most widely supported format.

  • Works on all servers, all PHP versions.

  • Best practice — always use this in modern PHP.

✅ 2. Short Echo Tag (<?= ... ?>) — Shortcut for echo

<?= "Hello, world!" ?>
  • This is just a shortcut for echo, same as writing:

    <?php echo "Hello, world!"; ?>
  • Very popular in templates and frameworks like Laravel, WordPress, etc.

  • Safe to use in PHP 5.4+ (enabled by default)

⚠️ 3. Short Open Tag (<? ... ?>) — Not recommended

<? echo "Hello"; ?>
  • This is shorter, but depends on server settings (short_open_tag in php.ini).

  • Might not work on some servers — not reliable.

  • Avoid using this for professional or portable code.

❌ 4. ASP-style Tags — Deprecated / Removed

<% echo "Hello"; %>
<%= "Hello" %>
  • Inspired by old ASP.NET syntax.

  • Removed in modern PHP versions — no longer supported.

  • Do not use.

✅ Summary (Best Practice)

Tag Type Status Should You Use It?
<?php ... ?> ✅ Fully supported ✅ Yes — Recommended
<?= ... ?> ✅ Safe (PHP 5.4+) ✅ Yes — For quick output
<? ... ?> ⚠️ Depends on server ❌ Better avoid
<% ... %> ❌ Deprecated ❌ Never use

3. How PHP Tags Work Inside HTML

PHP is most commonly used inside HTML files — this is what makes PHP ideal for creating dynamic web pages.

✅ Embedding PHP inside HTML pages

Example:

<!DOCTYPE html>
<html>
<head>
<title>My PHP Page</title>
</head>
<body>
<h1>Welcome!</h1>

<?php
echo "<p>This text is generated by PHP.</p>";
?>

<p>This text is normal HTML.</p>
</body>
</html>

or

<?php
$mypagetitle=”Hello World! php Schools.com”;
$intro_message=”wellcome to my website !you can edite this message in the \$intro_message variable”;
$my_message=”this text is generated by php variable \$my_message .you can edit it”;

echo “<!DOCTYPE html> <html><head> <title>{$mypagetitle}</title></head>
<h1 class=\”myclassname\”>{$intro_message}</h1><p class=\”myclass-2\”>{$my_message}</p>
</body></html>”

?>

 

output:

php tags open and close

  • The browser sees both HTML and the result of the PHP code.

  • Anything outside <?php ... ?> is treated as normal HTML.

  • Anything inside <?php ... ?> is processed by the server first — then the result is sent to the browser.

✅ Switching Between HTML and PHP Blocks

You can jump in and out of PHP mode whenever you want:

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

Or even alternate multiple times:

<?php if (true): ?>
<p>This is HTML shown because condition is true.</p>
<?php else: ?>
<p>This is alternative HTML.</p>
<?php endif; ?>
  • PHP lets you mix logic + HTML very easily.

  • This style is common in WordPress, Laravel, and template engines.

Key Idea

PHP tags act like an on/off switch:

Area Interpreted as
Outside <?php ?> HTML (sent directly to browser)
Inside <?php ?> PHP code (processed first, then output sent)

 

 

4. Echo vs Short Echo Tag (<?= ?>)

PHP gives you two main ways to output data to the browser:

✅ Method 1: Standard echo statement (full syntax)

<?php
echo "Hello, world!";
?>
  • This is the traditional and original way.

  • Always available — works in every PHP version and every server.

  • Supports multiple values:

<?php
echo "Hello ", $name, "! Welcome to ", $site;
?>

✅ Method 2: Short Echo Tag (<?= ?>) — Shortcut for faster output

<?= "Hello, world!" ?>
  • This is 100% equal to:

    <?php echo "Hello, world!"; ?>
  • Much shorter and cleaner — commonly used in HTML templates.

  • Safe to use in PHP 5.4+ (it’s always enabled by default).

✅ When to Use Short Echo <?= ?>

Situation Recommended?
Quickly printing a value or variable ✅ Yes
Inside HTML (like templates or view files) ✅ Yes
In WordPress, Laravel, Blade, etc. ✅ Yes
In logic-heavy PHP (like classes or loops) ⚠️ Better use full echo

🔧 Examples with Variables and Strings

<?php
$username=”Hosein”;
$total=100;
$age=25;

?>
<?= “Hello, ” . $username . “!”; ?> <p>Your total is: <?= $total ?> USD</p> <p>Age: <?= $age ?></p>

output:

php tags open and close

  • Clean, fast, and readable

  • Perfect for printing values directly inside HTML layout

Final Rule

Syntax Best for Notes
echo Any situation Always safe, ideal for PHP logic
<?= ?> Fast HTML output Best for display, not complex code

 

 

5. PHP Closing Tag — Do We Always Need It?

In PHP, every code block is usually wrapped like this:

<?php
// PHP code here
?>

The ?> is called the closing tag — but in many cases, you shouldn’t use it at all.

✅ When You Can Omit the Closing Tag

If your file is pure PHP only (no HTML after the PHP code),
it is best practice to completely leave out the ?> closing tag.

Example — ✅ Recommended (no closing tag):

<?php
echo "This is a pure PHP file.";

// end of file — no closing tag needed

  • This is common in modern PHP, frameworks, and APIs.

  • Used in Laravel, WordPress, Composer packages, etc.

⚠️ Why Should You Omit It? — Avoid This Problem

Sometimes unwanted spaces or line breaks appear after the closing tag:

<?php
echo "Hello";
?> ← a space or newline here will be sent to the browser!

This can cause serious problems like:

  • “Headers already sent” error

  • Broken JSON or API responses

  • Invisible output being sent accidentally

Summary

Situation Should You Write ?>?
PHP file contains HTML after PHP block ✅ Yes (because you return to HTML)
File is pure PHP only (e.g., class, config, functions) ❌ No — recommended to leave it out

6. Best Practices for Using PHP Tags

Following best practices is essential for writing clean, secure, and professional PHP code, especially when working on modern applications or collaborating with others.

✅ 1. Always Use the Standard Tag <?php ... ?>

<?php
// Always use this format
  • Most compatible, works everywhere

  • Required in PSR-12 and all modern PHP frameworks

  • Do not rely on <? ... ?> short tags (may not work on all servers)

✅ 2. Use <?= ?> Only for Output (Safe in PHP 5.4+)

<p>Username: <?= $username ?></p>
  • Clean and perfect for views/templates

  • Use it only for output, not logic

  • Recommended in Laravel, Blade, WordPress themes

✅ 3. Omit the Closing Tag ?> in Pure PHP Files

<?php
function test() {
return "Hello";
}
// No closing tag — best practice
  • Required by PSR-12 standard

  • Prevents accidental whitespace output

  • Avoids “Headers already sent” errors

✅ 4. Follow PSR-12 Coding Standard (Modern PHP)

  • Standardizes formatting for all professional PHP projects

  • Examples of PSR-12 rules:

    • Use 4 spaces for indentation (not tabs)

    • One class/function per file

    • Use strict typing and proper spacing

    • Opening braces on new line

✅ 5. Maintain Readability and Clean Formatting

  • Keep PHP and HTML separated logically

  • Use meaningful variable names

  • Avoid deeply mixing HTML and PHP logic

Bad example (messy):

<p><?php if($user) echo "Hi ".$user; ?></p>

Better approach (cleaner):

<?php if ($user): ?>
<p>Hello, <?= $user; ?></p>
<?php endif; ?>

Summary of Best Practices

Best Practice Status
Use <?php instead of <? ✅ Required
Use <?= ?> for simple output ✅ Allowed
Avoid closing ?> in pure PHP files ✅ Recommended
Follow PSR-12 formatting ✅ Professional standard
Focus on readability and structure ✅ Always important

7. Common Mistakes and How to Avoid Them

Developers — especially beginners — often make small mistakes with PHP tags that lead to frustrating and hard-to-debug errors. Here are the two most common ones and how to prevent them.

❌ Mistake 1: “Headers already sent” error

This error appears when PHP sends output to the browser before functions like header(), session_start(), or cookies are used.

Example of the mistake:

<?php
echo "Hello"; // Output sent to browser

header("Location: home.php"); // ❌ ERROR: headers already sent

Or even worse — unwanted spaces before PHP starts:

<?php // ← Even a single space before this can break things!
session_start(); // ❌ This will trigger the error

How to avoid it:

  • Do NOT output anything before using header(), session_start(), or cookies.

  • Never leave spaces or empty lines before <?php or after ?>.

  • Best practice: Remove the ?> closing tag entirely in pure PHP files.

❌ Mistake 2: Unintended HTML whitespace or output

Even invisible spaces or line breaks can be sent to the browser — and that can corrupt JSON, PDFs, or cause UI issues.

Example:

<?php
echo "Hello";
?> ← These spaces or new lines will be sent to the browser!
<html>
<!-- This HTML will be affected -->
</html>

How to avoid it:

  • NEVER put extra space after the closing tag ?>.

  • Better: COMPLETELY OMIT the closing tag in PHP-only files.

  • Keep formatting clean and intentional.

Quick Safety Rules

Problem How to Prevent
“Headers already sent” No output before header/session. No space before <?php.
Random whitespace in page Remove all space after ?> — or don’t write ?> at all (!)
Broken JSON / APIs Avoid ANY accidental output. PHP-only files should end without ?>.

 

8. PHP Version Notes and Compatibility

Understanding how PHP versions affect tag behavior is important — especially if your code will run on different servers or hosting environments.

✅ Short Tags (<? ... ?>) and php.ini Settings

Short tags like this:

<? echo "Hello"; ?>

might not work on all servers because they depend on a PHP setting called:

short_open_tag = On/Off
  • In older PHP versions (before PHP 5.4), short tags were disabled by default.

  • In modern PHP versions (5.4+), short echo <?= ?> is always enabled, but short open tags <? ?> still depend on settings.

  • Many hosting providers disable short tags for security and compatibility.

Safe rule → Always use:

<?php // standard tag (always works)

✅ And short echo is safe:

<?= "Hello"; ?> // always works in PHP 5.4+

✅ Features Available in PHP 7 and PHP 8+

Modern PHP versions improved speed, security, and coding standards — especially for tag usage and mixing PHP with HTML.

PHP Version Important Notes
PHP 5.3 and older Short tags often disabled. Outdated — not recommended.
PHP 5.4+ <?= ?> short echo is always enabled — safe to use.
PHP 7 Major performance boost, supports scalar type hints and return types.
PHP 8+ Adds modern features like match, attributes, named arguments, constructor property promotion, etc.

✅ Modern Best Practice (PHP 7 & 8+)

  • Use <?php and <?= ?> only

  • Avoid <? ... ?> and never use ASP-style <% %> tags

  • Omit closing ?> in pure PHP files

  • PHP 7 and 8 are recommended for clean, modern, and secure code

 

 

9. Practical Examples and Mini Projects

Let’s now see how PHP tags are used in real, practical situations — this helps you understand why tags matter.

✅ Example 1: Mixing PHP with a Basic HTML Form

This is a classic example of PHP + HTML working together:

<!DOCTYPE html>
<html>
<body>

<form method="POST">
<input type="text" name="username" placeholder="Enter your name">
<button type="submit">Submit</button>
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
echo "<p>Hello, " . htmlspecialchars($_POST['username']) . "!</p>";
}
?>

</body>
</html>

What’s happening here?

  • The form is HTML

  • When the user submits it, PHP runs inside <?php ... ?> and displays a message

  • This is the most common real-world use of PHP tags

✅ Example 2: Simple Dynamic Page Using PHP Tags

<!DOCTYPE html>
<html>
<body>

<h1>Welcome to My Website</h1>

<p>Current time:</p>
<?php
echo date("Y-m-d H:i:s");
?>

</body>
</html>

PHP is generating a dynamic value (the current date and time)

  • Everything else is static HTML

  • Only the part inside <?php ... ?> is dynamic

What You Learned Practically

Example Purpose
HTML Form + PHP PHP responds to user input
Dynamic Time PHP adds live, changing content

 

10. Summary and Next Steps

After going through all the sections on PHP tags, here’s a recap of what you’ve learned and what you can focus on next.

✅ What You Learned

  1. PHP Tags Basics

    • PHP code runs only inside <?php ... ?>

    • PHP tags separate PHP from HTML so the server knows what to execute

  2. Different Types of PHP Tags

    • Standard <?php ... ?> → always safe

    • Short echo <?= ... ?> → quick output

    • Avoid <? ... ?> and ASP-style tags <% ... %>

  3. Mixing PHP with HTML

    • You can switch between PHP and HTML seamlessly

    • Dynamic content is generated inside PHP blocks

  4. Echo vs Short Echo

    • echo works anywhere

    • <?= ?> is a shortcut for output in templates

  5. Closing Tag Rules

    • Omit ?> in pure PHP files to prevent whitespace and errors

  6. Best Practices

    • Use standard tags, clean formatting, follow PSR-12, and focus on readability

  7. Common Mistakes

    • “Headers already sent” errors

    • Unintended whitespace or output

  8. Version Notes & Compatibility

    • PHP 5.4+ supports <?= ?>

    • Avoid server-dependent short tags

    • Modern PHP (7/8) offers better features and stability

  9. Practical Usage

    • Forms, dynamic content, templates, and mini projects demonstrate real-world applications

✅ What to Learn After PHP Tags

Once you are comfortable with PHP tags, the next steps to become proficient in PHP are:

  1. Variables, Data Types, and Operators

    • Learn how to store, manipulate, and compare data

  2. Conditional Statements & Loops

    • if, else, switch, for, while, foreach

  3. Functions and Reusable Code

    • Writing functions, passing parameters, returning values

  4. Arrays and Array Functions

    • Indexed, associative, and multidimensional arrays

  5. Working with Forms & Superglobals

    • $_POST, $_GET, $_SESSION, $_COOKIE

  6. File Handling and Include/Require

    • Including other files, reading/writing files

  7. Object-Oriented PHP

    • Classes, objects, inheritance, interfaces, traits

  8. Database Basics

    • Using MySQL/MariaDB with PDO or MySQLi

  9. PHP Frameworks (Optional)

    • Laravel, Symfony, CodeIgniter for professional web development