Web Technology IIUnit 36 min read

PHP Basics: Syntax, Variables, Control Flow & Scripting

Unit 3 of Web Technology II introduces PHP as a server-side scripting language, covering its basic syntax, variable types, control structures, and how it integrates with HTML to build dynamic web pages. Learn how PHP executes on the server, processes data, and generates HTML output—with real-world examples from Nepales

What is PHP?

PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed for web development. Unlike HTML (which runs in the browser) or JavaScript (which runs client-side), PHP code is executed on the web server before sending the final HTML to the user’s browser.

How PHP Works

  1. A user requests a .php file (e.g., index.php) from a web server.
  2. The server parses the PHP code, executes it, and generates dynamic HTML.
  3. The final HTML is sent to the user’s browser, which renders it.
sequenceDiagram
    participant User
    participant Browser
    participant WebServer
    participant PHP
    User->>Browser: Requests index.php
    Browser->>WebServer: Sends HTTP request
    WebServer->>PHP: Executes PHP code
    PHP->>WebServer: Returns HTML
    WebServer->>Browser: Sends HTML
    Browser->>User: Displays webpage

Basic PHP Syntax

PHP code is embedded within HTML using <?php ... ?> tags. Example:

<?php
    echo "Hello, Nepal!";
?>
  • echo outputs text to the browser.
  • PHP ignores everything outside <?php ... ?> tags.

Key Syntax Rules

Feature Example Notes
Comments // Single-line or /* Multi-line */ Ignored by PHP.
Variables $name = "Ramesh"; Always start with $. Case-sensitive.
Output echo $name; Displays variable value.
Statements echo "Welcome!"; End with ; (optional in some cases).

Variables and Data Types

PHP is loosely typed, meaning you don’t declare variable types explicitly.

Common Data Types

classDiagram
    class String { Text (e.g., "Nepal") }
    class Integer { Whole numbers (e.g., 42) }
    class Float { Decimals (e.g., 3.14) }
    class Boolean { true/false }
    class Array { Ordered lists (e.g., [1, 2, 3]) }
    class NULL { No value assigned }

Example:

$age = 25;          // Integer
$name = "Hari";     // String
$isStudent = true;  // Boolean
$marks = [85, 90];  // Array

Control Structures

PHP uses if, else, for, while, and switch to control program flow.

1. Conditional Statements (if-else)

$score = 85;
if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 80) {
    echo "Grade: B";  // Output: Grade: B
} else {
    echo "Grade: C";
}

Real-World Example: Daraz Order Status Daraz uses PHP (or similar backend logic) to check order status:

$orderStatus = "shipped";
if ($orderStatus == "shipped") {
    echo "Your order is on the way!";
} else {
    echo "Order processing...";
}

2. Loops (for, while)

// Print numbers 1 to 5
for ($i = 1; $i <= 5; $i++) {
    echo $i . "<br>";
}

// While loop example
$i = 1;
while ($i <= 3) {
    echo "Iteration $i<br>";
    $i++;
}

Functions in PHP

Functions group reusable code. Example:

// Define a function
function greet($name) {
    return "Hello, $name!";
}

// Call the function
echo greet("Sita");  // Output: Hello, Sita!

Common Built-in Functions:

Function Purpose Example
strlen() Get string length strlen("Nepal") → 5
strtolower() Convert to lowercase strtolower("PHP") → php
date() Get current date/time date("Y-m-d") → 2024-05-20
isset() Check if variable exists isset($var) → true/false

Working with Forms and PHP

PHP processes form data submitted via GET or POST.

Example: Login Form

<!-- HTML Form (index.html) -->
<form action="login.php" method="POST">
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Login</button>
</form>
<!-- PHP Script (login.php) -->
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];
    if ($username == "admin" && $password == "1234") {
        echo "Login successful!";
    } else {
        echo "Invalid credentials.";
    }
}
?>

In the Real World

  1. eSewa (Nepal)

    • Uses PHP (or similar backend) to validate user credentials when logging in. The server checks the submitted username/password against a database and returns a success/error message.
    • Example: When you enter your phone number and password, PHP verifies your details before granting access to your wallet.
  2. Khalti (Nepal)

    • PHP processes payment requests by checking transaction details (amount, merchant ID, user ID) and generating a secure response. For example:
      $amount = $_POST["amount"];
      if ($amount > 0 && is_numeric($amount)) {
          // Proceed with payment
          echo "Payment of Rs. $amount initiated.";
      } else {
          echo "Invalid amount!";
      }
      
  3. Daraz (Nepal)

    • Uses PHP to manage inventory. When you add an item to cart, PHP checks stock availability:
      $productId = $_GET["id"];
      $stock = getStock($productId); // Hypothetical function
      if ($stock > 0) {
          echo "Item added to cart!";
      } else {
          echo "Out of stock!";
      }
      

Common Pitfalls and Best Practices

Mistake Fix Example
Forgetting ; Always end statements with ; echo "Hello" ❌ → echo "Hello"; ✅
Using == instead of === Use === for strict type comparison $a = "5"; $b = 5; $a === $b → false
Uninitialized variables Use isset() to check if (isset($var)) { ... }
SQL injection (Unit 5!) Use prepared statements $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");

Exam Tip

  1. Syntax Matters: Memorize <?php ... ?>, echo, if-else, and loop syntax. Exams often test small code snippets.
  2. Variable Scope: Know the difference between $globalVar (global) and $localVar (local to a function).
  3. Form Handling: Be ready to write a simple POST/GET example. Assume a form with name="email" and process $_POST["email"].
  4. Error Handling: Use if (isset()) to avoid undefined variable errors.
  5. Real-World Scenarios: Expect questions like:
    • "Write PHP code to check if a user’s age is ≥18."
    • "How would you validate a Daraz order amount before processing?"

Based on the TU BIM syllabus for Web Technology II (IT239), unit 3.

Discussion

Loading…