Skip to content
PHP Basics — Complete Beginner's Guide to Server-Side Scripting

PHP Basics — Complete Beginner's Guide to Server-Side Scripting

DodaTech Updated Jun 6, 2026 11 min read

PHP is a server-side scripting language that runs on the web server before sending HTML to the browser, enabling dynamic content generation and database interaction for over 75% of websites worldwide.

What You’ll Learn

By the end of this tutorial, you’ll understand PHP syntax, create variables and constants, work with data types and operators, handle strings, and write your first dynamic PHP page.

Why PHP Basics Matters

PHP powers major platforms like WordPress, Facebook (original), and Wikipedia. At DodaTech, our tools like Durga Antivirus Pro use PHP-based dashboards for real-time threat monitoring, while Doda Browser relies on PHP backends for sync services. Even DodaZIP’s cloud storage layer uses PHP for file management APIs. Mastering PHP opens doors to building everything from contact forms to enterprise security panels.

PHP Learning Path

    flowchart LR
  A[PHP Basics] --> B[Control Flow]
  B --> C[Functions]
  C --> D[Arrays]
  D --> E[Forms & Validation]
  E --> F[Advanced OOP]
  F --> G[Frameworks]
  A --> H{You Are Here}
  style H fill:#f90,color:#fff
  
Prerequisites: Basic HTML knowledge. Familiarity with JavaScript helps but isn’t required. No server setup needed — PHP has a built-in dev server.

How PHP Works — The “Wait, Why Does This Run on the Server?”

Think of PHP as a kitchen chef and your browser as a diner. When you visit a website, the browser (diner) places an order (HTTP request). The kitchen chef (PHP on the server) prepares the meal, plates it as HTML, and serves it. You never see the messy kitchen — just the finished meal.

Unlike JavaScript, which runs in the browser after the page loads, PHP runs before the page is sent. That’s why PHP can access databases, read files, and handle secrets — the browser never sees the raw PHP code.

    flowchart LR
  A[Browser] -->|HTTP Request| B[Web Server]
  B --> C[PHP Interpreter]
  C --> D[Executes PHP Code]
  D --> E[Generates HTML]
  E --> B
  B -->|HTTP Response| A
  

Setting Up Your PHP Environment

You don’t need a full Apache server to start. PHP comes with a built-in development server:

# Check if PHP is installed
php --version    # e.g., PHP 8.3.0

# Run a PHP file directly (like a script)
php file.php

# Start the built-in dev server
php -S localhost:8000

For a full stack, install XAMPP (cross-platform), WAMP (Windows), MAMP (macOS), or LAMP (Linux). These bundle Apache, MySQL, and PHP together — everything you need for production-like development.

PHP Syntax — Your First Dynamic Page

PHP code is embedded inside HTML using <?php ... ?> tags. The server processes everything between these tags and replaces it with the output.

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

Output:

Hello, World!

Here’s what’s happening:

  • The browser requests this .php file
  • The server finds <?php ... ?> and hands it to the PHP interpreter
  • echo tells PHP to output the string "Hello, World!"
  • PHP replaces the entire <?php ... ?> block with that output
  • The browser receives pure HTML and renders it

Every PHP statement must end with a semicolon (;). Think of it like a period at the end of a sentence — it tells PHP “this instruction is complete.”

PHP Tags — Which One Should You Use?

<?php
// Standard PHP tag — always works, use this
echo "Hello";
?>

<?=
// Short echo tag — same as <?php echo
?>
<h1><?= "Hello" ?></h1>

Rule of thumb: Use <?php ?> for blocks of code and <?= ?> for quick inline echoes. Never use the short <? ?> tag — it requires special configuration.

Variables — Labeled Boxes for Your Data

Variables in PHP always start with $ followed by the name. Think of them as labeled boxes: you write a label ($name) and put something inside ("Alice").

Each line here creates a variable and stores a value in it. $name = "Alice" stores text — the quotes tell PHP “this is a string, not code.” $age = 25 stores a whole number without quotes (PHP knows it’s an integer). $price = 19.99 is a decimal number (a float), $isActive = true stores a true/false flag (a boolean), and $color = null means “this box exists but it’s empty.” The last line echo $name prints the value back — that’s how you get data out of a variable and show it on the page.

<?php
$name = "Alice";        // string — text
$age = 25;              // integer — whole number
$price = 19.99;         // float — decimal number
$isActive = true;       // boolean — true or false
$color = null;          // null — empty, nothing

echo $name;  // Alice
?>

Why PHP Doesn’t Need Type Declarations

PHP is loosely typed. You don’t tell PHP “this box holds numbers.” PHP figures it out from what you put in. The type can even change:

<?php
$value = "42";   // string
$value = 42;     // now it's an integer — PHP doesn't mind
?>

This flexibility makes PHP easy to start with, but you’ll learn about strict typing later for production code.

Variable Scope — Where Can You Use Your Variables?

<?php
$x = 5;  // global scope — outside functions

function test() {
    $y = 10;  // local scope — only inside this function
    global $x;  // "I need the global $x, please"
    echo $x + $y;  // 15
}

test();
// echo $y;  // Error! $y doesn't exist here
?>

Variables inside functions are in a different room — they can’t see variables in the main room unless you explicitly bring them in with global.

Superglobals — PHP’s Built-In Magic Arrays

PHP provides superglobal arrays that are available everywhere — no global keyword needed:

<?php
$_GET      // URL parameters (/?name=Alice)
$_POST     // Form data submitted via POST
$_SERVER   // Server info (browser, IP, request method)
$_SESSION  // User session data (login state)
$_COOKIE   // Browser cookies
$_FILES    // Uploaded files
$GLOBALS   // All global variables
?>

Data Types — The 8 Kinds of Values

TypeDescriptionExample
stringText"hello", 'world'
intWhole number42, -5
floatDecimal3.14
boolTrue/falsetrue, false
arrayOrdered collection[1, 2, 3]
objectClass instancenew Car()
nullNo valuenull
resourceExternal handlefile, DB connection

Type Juggling — PHP’s Automatic Conversion

PHP automatically converts types when you use operators. This is called type juggling — PHP switches between types behind the scenes so your code keeps working.

Watch how each line behaves differently based on the operator. $sum = "10" + 5 uses + (addition), so PHP converts the string "10" to the number 10 and adds 5 — result: 15. But $concat = "10" . 5 uses . (concatenation), which joins text, so PHP converts the number 5 to the string "5" and glues it together — result: "105". The last two lines show explicit casting: instead of letting PHP guess, you force the conversion yourself with (int) or (string).

<?php
$sum = "10" + 5;         // 15 — PHP converts "10" string to number
$concat = "10" . 5;      // "105" — . is concatenation, converts 5 to string

// Explicit casting — you take control
$num = (int) "42";       // 42 — force string to integer
$str = (string) 42;      // "42" — force integer to string
?>

Common Mistakes Beginners Make

1. Missing Semicolons

Every statement ends with ;. Forgetting one causes a confusing error:

Parse error: syntax error, unexpected end of file

The error often points to the next line, not the line with the mistake. If you see this, check the line before the one mentioned.

2. Variable Name Case-Sensitivity

$name and $Name are different variables. A typo creates a new undefined variable:

error_reporting(E_ALL);  // Enable this during development
ini_set("display_errors", 1);

3. Single vs Double Quotes Confusion

Variables are only interpolated inside double quotes:

$name = "Alice";
echo 'Hello, $name';  // Prints: Hello, $name (literal)
echo "Hello, $name";  // Prints: Hello, Alice (interpolated)

4. Forgetting the $ on Variables

$count = 5;
// WRONG: count = 10;     → PHP looks for constant "count"
// RIGHT: $count = 10;

5. Loose Comparison Surprises

var_dump("0" == false);   // true — string "0" is considered falsy
var_dump("php" == 0);     // true! — PHP converts "php" to 0

Use === (identical) when you need to compare both value AND type.

Practice Questions

1. What does <?= "Hello" ?> do?

It’s shorthand for <?php echo "Hello"; ?>. It outputs the string directly into HTML. Available in all modern PHP versions.

2. What’s the difference between $name = "Alice" and $Name = "Bob"?

They are two separate variables. PHP variable names are case-sensitive. $name and $Name hold different values.

3. Why does "10" + 5 give 15 but "10" . 5 give “105”?

The + operator is arithmetic — PHP converts strings to numbers for math. The . operator is concatenation — PHP converts numbers to strings for joining text.

4. What will var_dump("0" === false) output?

bool(false). The === operator checks both value AND type. "0" is a string, false is boolean, so they’re not identical.

5. Challenge: Write a PHP script that displays “Good morning” if the hour is before 12, “Good afternoon” if between 12 and 18, and “Good evening” otherwise. Use date("H") to get the current hour.

<?php
$hour = (int)date("H");
if ($hour < 12) {
    echo "Good morning";
} elseif ($hour < 18) {
    echo "Good afternoon";
} else {
    echo "Good evening";
}
?>

FAQ

What is PHP used for?
PHP is used for server-side web development — generating dynamic HTML, handling forms, managing sessions, interacting with databases like MySQL, and building APIs for applications like Durga Antivirus Pro dashboards.
Do I need Apache to run PHP?
No. PHP runs as a CLI script (php file.php) or with the built-in server (php -S localhost:8000). Apache/Nginx are for production.
What’s the difference between echo and print?
echo is slightly faster, takes multiple arguments, and returns nothing. print takes one argument and returns 1. Use echo 99% of the time.
How do I check a variable’s type?
Use var_dump($var) for full type + value info, or gettype($var) for just the type name.
What does the null coalescing operator do?
$x ?? $y returns $x if it exists and is not null, otherwise $y. It prevents “undefined index” errors.

Try It Yourself

Create a file called profile.php:

<?php
$name = "Alex Rivera";
$age = 28;
$title = "Web Developer";
$skills = ["PHP", "JavaScript", "MySQL", "Linux"];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Profile</title>
</head>
<body>
    <h1><?= $name ?></h1>
    <p><strong>Title:</strong> <?= $title ?></p>
    <p><strong>Age:</strong> <?= $age ?></p>
    <ul>
        <?php foreach ($skills as $skill): ?>
            <li><?= $skill ?></li>
        <?php endforeach; ?>
    </ul>
</body>
</html>

Run with php -S localhost:8000 and visit http://localhost:8000/profile.php.

Mini Project: Build a Personal Info Card

Now that you know variables, echo, and concatenation, let’s build something real — a Personal Info Card that displays a person’s details in a styled page.

Step 1: Create the File

Create a new file called info-card.php.

Step 2: Declare Your Variables

Store the person’s information in variables:

<?php
$fullName = "Maria Chen";
$age = 24;
$city = "Mumbai";
$profession = "Graphic Designer";
$bio = "Self-taught designer who loves creating brand identities and digital art.";
?>

Step 3: Build the Card HTML

Use those variables inside HTML with <?= ?> short echo tags:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Personal Info Card</title>
    <style>
        .card { max-width: 400px; margin: 50px auto; padding: 20px;
                border: 1px solid #ddd; border-radius: 8px; font-family: Arial; }
        .card h1 { margin: 0 0 10px; color: #333; }
        .card p { margin: 5px 0; color: #666; }
    </style>
</head>
<body>
    <div class="card">
        <h1><?= $fullName ?></h1>
        <p><strong>Age:</strong> <?= $age ?></p>
        <p><strong>City:</strong> <?= $city ?></p>
        <p><strong>Profession:</strong> <?= $profession ?></p>
        <p><strong>Bio:</strong> <?= $bio ?></p>
        <p><em>— Built with PHP basics</em></p>
    </div>
</body>
</html>

Step 4: Run It

php -S localhost:8000

Visit http://localhost:8000/info-card.php in your browser.

Expected Output

A styled card showing:

Maria Chen
Age: 24
City: Mumbai
Profession: Graphic Designer
Bio: Self-taught designer who loves creating brand identities and digital art.
— Built with PHP basics

✅ Validation Check

  • All variables start with $ (no missing dollar signs)
  • Every statement ends with ;
  • You used <?= ?> short echo tags inside HTML
  • The card displays correctly in the browser
  • Change $city = "Delhi" and refresh — the card updates automatically

What’s Next

LessonDescription
PHP Control FlowMaster if/else, switch, match, and loops
PHP FunctionsWrite reusable code with functions
PHP ArraysWork with indexed and associative arrays
MySQLDatabase integration with PHP
LaravelModern PHP framework for web apps

What’s Next

Congratulations on completing this Php Basics tutorial! Here’s where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Apply what you learned by building something real
  • Explore related topics — Check out other tutorials in the same category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro