CACS254 Scripting Language

Scripting LanguageUnit 59 min read

PHP Basics: Syntax, Scripts, and Web Integration

Unit 5 of Scripting Language covers PHP’s core concepts—server-side execution, syntax rules, embedding in HTML, and dynamic content generation—with hands-on examples of form handling, variable types, and basic control structures. Learn how PHP powers real-world apps like eSewa’s payment validation and Daraz’s order pro

TAKEAWAYS:

  • PHP runs on the server (unlike JavaScript, which runs in the browser) and generates dynamic HTML, making it ideal for back-end tasks like database queries and form validation.
  • PHP scripts are embedded in HTML using <?php ... ?> tags and execute only when the page is requested by a client (e.g., a user’s browser).
  • Variables in PHP start with $, are loosely typed, and can hold strings, numbers, arrays, or objects—critical for storing user input (e.g., a Daraz order’s product details).
  • Control structures (if, for, while) enable logic like validating a Kathmandu traffic route’s start/end points before displaying directions.
  • PHP interacts with databases (e.g., MySQL) via functions like mysqli_connect() and mysqli_query(), used by Ncell’s billing system to fetch customer data.
  • Security is paramount: PHP’s htmlspecialchars() prevents XSS attacks (e.g., protecting eSewa’s transaction pages from malicious script injection).

1. What is PHP?

PHP (PHP: Hypertext Preprocessor) is a server-side scripting language designed for web development. Unlike client-side languages (e.g., JavaScript), PHP executes on the web server and sends plain HTML to the browser. This separation ensures sensitive operations (e.g., password hashing, database queries) happen securely on the server.

How PHP Works: The Lifecycle of a Dynamic Web Page

flowchart TD
    A["User requests a PHP page\n(e.g., Daraz checkout page)"] --> B["Web Server\n(Apache/Nginx)"]
    B --> C["PHP Interpreter\nExecutes PHP code"]
    C --> D["Database\n(MySQL, PostgreSQL)"]
    D --> C
    C --> E["Generates HTML\n(Sent to browser)"]
    E --> F["Browser renders\nDynamic content"]

Example: When you submit an order on Daraz, PHP validates your payment details on the server before confirming the order.


2. PHP Syntax Basics

PHP code is embedded in HTML using <?php ... ?> tags. Key syntax rules:

  • Case-insensitive: echo and Echo are the same.
  • Statements end with ; (unlike Python).
  • Variables start with $ and are loosely typed.

Example: Embedding PHP in HTML

<!DOCTYPE html>
<html>
<head><title>eSewa Payment Form</title></head>
<body>
    <h1>Pay Your Bill</h1>
    <?php
        $amount = 500; // Variable declaration
        echo "<p>Your bill amount: \$$amount</p>"; // Dynamic content
    ?>
</body>
</html>

Output:

Your bill amount: $500

Variable Types in PHP

Type Example Use Case
String $name = "Ramesh" User input (e.g., Daraz order name)
Integer $age = 25 Age validation
Float $price = 19.99 Product pricing (e.g., NTC bill)
Boolean $isLoggedIn = true Session management (e.g., eSewa login)
Array $products = ["Laptop", "Phone"] Storing multiple items (e.g., Daraz cart)
NULL $user = NULL Uninitialized data

3. PHP vs. JavaScript: Key Differences

Feature PHP JavaScript
Execution Server-side (hidden from user) Client-side (runs in browser)
Use Case Database queries, form validation Dynamic UI updates (e.g., WhatsApp typing indicators)
Example in Nepal eSewa’s payment processing Pathao’s real-time ride tracking
Security More secure (hidden from user) Vulnerable to XSS attacks

Why Use Both?

  • PHP handles back-end logic (e.g., Ncell’s billing system).
  • JavaScript enhances user experience (e.g., Daraz’s live chat).

4. Control Structures

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

Example: Validating a Kathmandu Traffic Route

<?php
$start = "Thamel";
$end = "Kirtipur";

if ($start === "Thamel" && $end === "Kirtipur") {
    echo "Route: Thamel → Ring Road → Kirtipur (Distance: 12 km)";
} elseif ($start === "Kirtipur" && $end === "Thamel") {
    echo "Route: Kirtipur → Ring Road → Thamel (Distance: 12 km)";
} else {
    echo "Invalid route. Try again.";
}
?>

Output:

Route: Thamel → Ring Road → Kirtipur (Distance: 12 km)

Loop Example: Displaying NEPSE Stock Prices

<?php
$stocks = ["NTC", "Ncell", "NMB", "Global IME"];
foreach ($stocks as $stock) {
    echo "Stock: $stock<br>";
}
?>

Output:

Stock: NTC
Stock: Ncell
Stock: NMB
Stock: Global IME

5. Handling User Input (Forms)

PHP processes HTML form data using $_POST or $_GET.

Example: eSewa-Style Payment Form

HTML Form (payment_form.html):

<form action="process_payment.php" method="POST">
    <input type="text" name="amount" placeholder="Enter amount">
    <input type="submit" value="Pay">
</form>

PHP Script (process_payment.php):

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $amount = $_POST["amount"];
    if (is_numeric($amount) && $amount > 0) {
        echo "<h1>Payment of \$$$amount successful!</h1>";
    } else {
        echo "<h1>Invalid amount. Please try again.</h1>";
    }
}
?>

6. Security Best Practices

PHP is vulnerable to attacks like SQL injection and XSS. Mitigate them with:

  1. Sanitize Input: Use htmlspecialchars() to escape user data.
    $safe_name = htmlspecialchars($_POST["name"]);
    
  2. Prepared Statements: Prevent SQL injection.
    $stmt = $conn->prepare("INSERT INTO users (name) VALUES (?)");
    $stmt->bind_param("s", $safe_name);
    
  3. Password Hashing: Use password_hash().
    $hashed_password = password_hash($_POST["password"], PASSWORD_DEFAULT);
    

Real-World Tie-In:

  • eSewa uses PHP to validate transactions securely before processing payments.
  • Ncell’s billing system sanitizes user input to prevent fraud.

7. Common PHP Functions

Function Purpose Example
echo/print Output data echo "Hello, Daraz!";
isset() Check if variable is set if (isset($_POST["email"]))
empty() Check if variable is empty if (empty($name))
strtolower() Convert string to lowercase strtolower("NEPSE") → "nepse"
date() Get current date/time date("Y-m-d") → "2023-10-15"

In the Real World

  1. eSewa’s Payment Validation

    • Idea Used: PHP form handling + database integration.
    • How: When you pay a bill, PHP validates your transaction details (amount, account number) on the server before deducting funds. The script uses $_POST to receive data and mysqli_query() to update your account balance in the database.
  2. Daraz’s Order Processing

    • Idea Used: PHP arrays + loops.
    • How: Daraz stores your cart items in a PHP array (e.g., $cart = ["Laptop", "Mouse"]). When you checkout, a foreach loop iterates through the array to calculate the total price and generate an invoice.
  3. Ncell’s Billing System

    • Idea Used: PHP control structures + security.
    • How: PHP checks if your phone number exists in the database using an if statement. If valid, it generates a bill using echo and sends it via SMS (via a PHP-to-SMS gateway).

Exam Tip

  1. Syntax Matters: Always use <?php ... ?> tags and end statements with ;. Missed semicolons are a common mistake in exams.
  2. Form Handling: Remember to check $_SERVER["REQUEST_METHOD"] before processing $_POST or $_GET data.
  3. Security: Questions often ask about preventing SQL injection or XSS. Always mention htmlspecialchars() or prepared statements.
  4. Real-World Scenarios: Exams may ask how PHP is used in apps like eSewa or Daraz. Link your answers to form validation, database queries, or dynamic content generation.
  5. Code Traces: For questions like "Write a PHP program to validate a form," trace the flow:
    • HTML form → PHP script → Database interaction → Output.

Worked Example for Exam Practice: Question: Write a PHP script to validate a user’s email and store it in a database if valid. Solution:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = $_POST["email"];
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $conn = mysqli_connect("localhost", "user", "password", "users_db");
        $stmt = $conn->prepare("INSERT INTO users (email) VALUES (?)");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        echo "Email registered successfully!";
    } else {
        echo "Invalid email format.";
    }
}
?>

Trace:

Step Action
1 User submits form with email=test@example.com
2 PHP checks $_SERVER["REQUEST_METHOD"] == "POST"
3 filter_var() validates the email
4 If valid, connects to MySQL and inserts the email
5 Outputs "Email registered successfully!"

Visual Summary:

mindmap
  root((PHP Basics))
    Server-Side Execution
      Runs on Web Server
      Generates HTML
    Syntax
      <?php ... ?>
      Variables: $var
    Control Structures
      if/else
      for/while
    Security
      htmlspecialchars()
      Prepared Statements
    Real-World Use
      eSewa Payments
      Daraz Order Processing
      Ncell Billing

Based on the TU BCA syllabus for Scripting Language (CACS254), unit 5.

Discussion

Loading…