Web development guide

PHP Basics for Beginners

PHP is a server-side language that powers a large share of websites, including WordPress. This guide covers the essentials you need to start.

Run PHP on your computer

Install PHP (or a bundle such as XAMPP), save a file called index.php and start the built-in server from that folder:

php -S localhost:8000

Then open http://localhost:8000 in your browser. PHP code goes inside <?php ... ?> tags.

Variables, arrays and loops

<?php
$name = "Asha";
$prices = ["pen" => 10, "book" => 150];

echo "Hello, " . $name . "<br>";

foreach ($prices as $item => $price) {
    echo "$item costs $price<br>";
}
?>

Functions

<?php
function addGst(float $amount, float $rate = 18): float {
    return $amount * (1 + $rate / 100);
}
echo addGst(1000);   // 1180
?>

Handle a form safely

Never print user input directly. Escape it with htmlspecialchars to prevent cross-site scripting.

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $name = trim($_POST["name"] ?? "");
    echo "Thanks, " . htmlspecialchars($name, ENT_QUOTES, "UTF-8");
}
?>
<form method="post">
  <label>Name <input name="name"></label>
  <button>Send</button>
</form>

Talk to a database with prepared statements

Prepared statements keep user input separate from the SQL and prevent SQL injection.

<?php
$pdo = new PDO("mysql:host=localhost;dbname=shop;charset=utf8mb4", $user, $pass);
$stmt = $pdo->prepare("SELECT * FROM orders WHERE city = :city");
$stmt->execute(["city" => $_GET["city"] ?? ""]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

Good habits

  • Keep credentials out of files that are publicly accessible.
  • Validate and escape all input and output.
  • Use require to reuse headers, footers and functions.
  • Keep PHP and your libraries updated.

New to the web side? Read HTML, CSS and JavaScript basics and WordPress for beginners.

Frequently asked questions

Is PHP still worth learning?

Yes, especially for WordPress work and many existing business websites.

Do I need a server to practice?

No. The built-in server shown above runs on your own computer.

What is the difference between echo and print?

Both output text. echo can take several values and is slightly more common.

← Back to Web Development