PHP Fundamentals

PHP Syntax & First Script

13 min Lesson 2 of 45

PHP Syntax & First Script

Now that you understand what PHP is, it's time to write your first PHP script! In this lesson, we'll cover PHP syntax basics, how to embed PHP in HTML, and create your first working PHP file.

PHP Tags

PHP code must be enclosed within special PHP tags. When the PHP interpreter sees these tags, it knows to process the code inside them.

Standard PHP Tags (Recommended): <?php // Your PHP code here ?> Short Echo Tag (PHP 5.4+): <?= "This is output" ?> Short Open Tag (Not Recommended): <? // Requires short_open_tag enabled ?>
Best Practice: Always use the standard <?php ?> tags for maximum compatibility. Short tags may not work on all servers.

Basic Syntax Rules

PHP has specific syntax rules you need to follow:

1. Statements end with semicolons: <?php echo "Hello World"; // Semicolon required $name = "John"; // Semicolon required ?> 2. PHP is case-sensitive for variables: <?php $name = "John"; // Different from $Name = "Jane"; // These are two different variables ?> 3. PHP is case-insensitive for keywords and functions: <?php ECHO "Hello"; // Works echo "Hello"; // Works (preferred) Echo "Hello"; // Works ?>
Important: While keywords are case-insensitive, variable names ARE case-sensitive. $name and $Name are different variables!

Comments in PHP

Comments help document your code and are ignored by the PHP interpreter:

<?php // Single-line comment # Another single-line comment (Unix style) /* Multi-line comment Can span multiple lines Great for documentation */ echo "Hello"; // Inline comment /** * PHPDoc comment block * Used for documenting functions and classes * @param string $name * @return void */ ?>
Best Practice: Use // for single-line comments and /* */ for multi-line comments. Use PHPDoc /** */ for documenting functions and classes.

Your First PHP Script

Let's create a complete PHP file. Save this as hello.php:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My First PHP Script</title> </head> <body> <h1>Welcome to PHP!</h1> <?php echo "<p>This paragraph is generated by PHP!</p>"; echo "<p>The current date is: " . date("Y-m-d") . "</p>"; ?> <p>This is regular HTML.</p> </body> </html>
Important: PHP files must be processed by a web server with PHP installed. You cannot simply open them in a browser like HTML files.

The echo and print Statements

PHP provides two ways to output data: echo and print. Both are used to display output, but have subtle differences:

echo Statement: <?php echo "Hello World"; echo "Hello", " ", "World"; // Can take multiple parameters echo "<h1>Title</h1>"; // Can output HTML ?> print Statement: <?php print "Hello World"; print("Hello World"); // Parentheses optional // print "Hi", "There"; // ERROR: print takes only one parameter ?> Differences: - echo: No return value, slightly faster, accepts multiple arguments - print: Returns 1, can be used in expressions, accepts one argument
Recommendation: Use echo for most cases. It's faster and more flexible. Use print only when you need its return value (rare).

Mixing PHP with HTML

One of PHP's strengths is seamless integration with HTML. You can switch between PHP and HTML freely:

<!DOCTYPE html> <html> <head> <title>PHP and HTML</title> </head> <body> <h1>User Information</h1> <?php $username = "JohnDoe"; $email = "john@example.com"; ?> <p>Username: <?= $username ?></p> <p>Email: <?= $email ?></p> <?php if ($username == "JohnDoe"): ?> <p>Welcome back, John!</p> <?php endif; ?> </body> </html>

Whitespace and Formatting

PHP ignores extra whitespace, allowing you to format code for readability:

All of these are equivalent: <?php echo "Hello"; ?> <?php echo "Hello"; ?> <?php echo "Hello" ; ?>
Best Practice: Use consistent indentation (4 spaces or 1 tab) and put opening braces on the same line as statements for better readability.

PHP File Structure

A well-structured PHP file typically follows this pattern:

<?php // 1. File-level comment (optional but recommended) /** * Description of what this file does * @author Your Name * @date 2024-01-15 */ // 2. PHP configuration (if needed) error_reporting(E_ALL); // 3. Include/require statements // require_once 'config.php'; // 4. Variable declarations $siteName = "My Website"; $year = date("Y"); // 5. Functions (we'll learn these later) // function greet($name) { ... } // 6. Main code logic ?> <!-- 7. HTML output --> <!DOCTYPE html> <html> <head> <title><?= $siteName ?></title> </head> <body> <h1><?= $siteName ?></h1> <p>Copyright &copy; <?= $year ?></p> </body> </html>

Running Your PHP Script

To run your PHP script, you need a web server. Here are the common methods:

Method 1: Built-in PHP Server (Quick Testing) 1. Open terminal/command prompt 2. Navigate to your project folder 3. Run: php -S localhost:8000 4. Visit: http://localhost:8000/hello.php Method 2: XAMPP/WAMP/MAMP 1. Save file in htdocs folder (XAMPP) or www folder (WAMP) 2. Start Apache server 3. Visit: http://localhost/hello.php Method 3: Production Server Upload via FTP and access through your domain
Common Mistake: Opening PHP files directly in a browser (file:///path/to/file.php) will NOT work. PHP must be processed by a server!

Viewing PHP Output

Understanding what the browser receives vs. what you write:

What You Write (hello.php): <?php $greeting = "Hello"; echo "<h1>" . $greeting . " World!</h1>"; ?> What Browser Receives (View Source): <h1>Hello World!</h1> What Browser Displays: [Large heading showing: Hello World!]
Key Point: The browser never sees your PHP code - only the HTML output that PHP generates!

Common Syntax Errors

Avoid these common mistakes beginners make:

❌ Forgetting Semicolon: <?php echo "Hello" // ERROR: Missing semicolon ?> ✓ Correct: <?php echo "Hello"; ?> ❌ Missing Closing Tag (in mixed PHP/HTML): <?php echo "Hello"; // Missing ?> <p>HTML here</p> ✓ Correct: <?php echo "Hello"; ?> <p>HTML here</p> ❌ Wrong Quote Usage: <?php echo 'He said "Hello"'; // Works but avoid mixing ?> ✓ Correct: <?php echo "He said \"Hello\""; // Escaped quotes // or echo 'He said "Hello"'; // Single quotes with double inside ?>

Practice Exercise:

Task: Create a file called about.php that displays:

  • Your name in an <h1> tag (using PHP echo)
  • Your favorite programming language in a <p> tag (using PHP)
  • The current year (using PHP date("Y") function)
  • A footer with "Made with PHP" (in HTML)

Solution:

<!DOCTYPE html> <html> <head> <title>About Me</title> </head> <body> <?php $name = "Your Name"; $language = "PHP"; ?> <h1><?= $name ?></h1> <p>My favorite language is <?= $language ?></p> <p>Year: <?= date("Y") ?></p> <footer>Made with PHP</footer> </body> </html>

Summary

In this lesson, you learned:

  • PHP code must be enclosed in <?php ?> tags
  • Statements end with semicolons
  • Variable names are case-sensitive
  • Use echo to output data
  • PHP can be seamlessly mixed with HTML
  • Comments help document your code
  • PHP files must be processed by a web server
Next Up: In the next lesson, we'll dive into variables and data types - the building blocks of any PHP program!

ES
Edrees Salih
7 hours ago

We are still cooking the magic in the way!