PHP

PHP for Beginners: From Zero to Your First Dynamic Website

Published on January 28, 2026

Written by: Code Arc Studio Editorial Team

PHP code on a server background

PHP (Hypertext Preprocessor) is one of the most widely-used, open-source scripting languages, especially suited for web development. It was one of the first server-side languages that could be embedded directly into HTML, making it incredibly easy to create dynamic web pages. Despite the rise of other technologies, PHP remains a dominant force on the web, powering everything from personal blogs to massive platforms like WordPress, Facebook, and Wikipedia. Its gentle learning curve, vast community, and extensive documentation make it an excellent starting point for anyone looking to dive into backend development.

The core strength of PHP lies in its simplicity for server-side tasks. It can generate dynamic page content, create, open, read, write, and close files on the server, collect form data, send and receive cookies, and interact with databases. This article will guide you through the absolute basics, helping you set up a development environment, understand the fundamental syntax, and build your first simple dynamic application.

Setting Up Your Development Environment

To start writing PHP, you need a server environment that can interpret PHP code. While you can install Apache (a web server), PHP, and a database like MySQL individually, the easiest way to get started is by using an all-in-one package. These packages create a local development server on your computer with a single installation.

  • XAMPP: A free and open-source cross-platform web server solution stack package, consisting mainly of the Apache HTTP Server, MariaDB database, and interpreters for scripts written in the PHP and Perl programming languages. (Available for Windows, macOS, and Linux).
  • MAMP: Similar to XAMPP, but originally created for macOS (macOS, Apache, MySQL, PHP). It's also available for Windows.
  • WAMP: A Windows-specific web development environment.

Once you've installed one of these, you can place your .php files in the appropriate web root directory (often called htdocs in XAMPP) and access them through your browser at an address like http://localhost/your-file.php.

PHP Syntax Fundamentals

A PHP script is executed on the server, and the plain HTML result is sent back to the browser. PHP code is enclosed in special start and end processing instructions, <?php and ?>, which allow you to jump into and out of "PHP mode."


<!DOCTYPE html>
<html>
<body>

<h1>My first PHP page</h1>

<?php
// Variables start with the \$ sign
\$greeting = "Hello World!";
// The 'echo' statement outputs data to the page
echo \$greeting;

// This is a single-line comment

/*
  This is a
  multi-line comment
*/
?>

</body>
</html>
      

In PHP, every statement must end with a semicolon (;). This is a common source of errors for beginners.

PHP Data Types

Type Description Example
String A sequence of characters. \$name = "John";
Integer A non-decimal number. \$age = 30;
Float A number with a decimal point. \$price = 19.99;
Boolean Represents two possible states: TRUE or FALSE. \$is_logged_in = true;
Array Stores multiple values in one single variable. \$colors = array("Red", "Green", "Blue");
NULL A special data type which can have only one value: NULL. \$var = null;

Control Structures

Like any programming language, PHP has structures for controlling the flow of execution. These include conditional statements and loops.


<?php
\$hour = date('H'); // Get the current hour in 24-hour format

if (\$hour < 12) {
    echo "Good morning!";
} elseif (\$hour < 18) {
    echo "Good afternoon!";
} else {
    echo "Good evening!";
}

echo "<br>";

// A 'for' loop
for (\$i = 1; \$i <= 5; \$i++) {
    echo "The number is: \$i <br>";
}

// A 'foreach' loop for arrays
\$fruits = array("Apple", "Banana", "Cherry");
foreach (\$fruits as \$fruit) {
    echo "I like " . \$fruit . "<br>"; // String concatenation is done with a period '.'
}
?>
      

Working with Forms

PHP shines when it comes to handling HTML form data. When a form is submitted, the data is sent to the server in a request, and PHP provides superglobal variables (\$_GET and \$_POST) to access it.

Here is a simple HTML form:


<!-- form.html -->
<form action="welcome.php" method="post">
  Name: <input type="text" name="name"><br>
  Email: <input type="text" name="email"><br>
  <input type="submit">
</form>
      

And here is the PHP script (welcome.php) to process it:


<!-- welcome.php -->
<html>
<body>

Welcome <?php echo htmlspecialchars(\$_POST["name"]); ?>!<br>
Your email address is: <?php echo htmlspecialchars(\$_POST["email"]); ?>

</body>
</html>
      

Important Security Note: It is crucial to sanitize user input to prevent security vulnerabilities like Cross-Site Scripting (XSS). The htmlspecialchars() function is a basic but essential first step. It converts special characters to HTML entities, so a user cannot inject malicious HTML or JavaScript into your page.

Connecting to a MySQL Database with PDO

Most web applications need to store data persistently. PHP offers several ways to connect to databases, but the modern, recommended approach is to use PDO (PHP Data Objects). PDO provides a data-access abstraction layer, which means you can use the same functions to issue queries and fetch data regardless of which database you're using.


<?php
\$servername = "localhost";
\$username = "your_username";
\$password = "your_password";
\$dbname = "your_database";

try {
    // 1. Create a PDO connection object
    \$conn = new PDO("mysql:host=\$servername;dbname=\$dbname", \$username, \$password);
    
    // Set the PDO error mode to exception
    \$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 2. Prepare and execute a SQL statement
    \$stmt = \$conn->prepare("SELECT id, firstname, lastname FROM Users");
    \$stmt->execute();

    // Set the resulting array to associative
    \$stmt->setFetchMode(PDO::FETCH_ASSOC);
    \$results = \$stmt->fetchAll();

    // 3. Loop through the results and display them
    foreach (\$results as \$row) {
        echo "ID: " . \$row['id'] . " - Name: " . \$row['firstname'] . " " . \$row['lastname'] . "<br>";
    }

} catch(PDOException \$e) {
    echo "Connection failed: " . \$e->getMessage();
}

// 4. Close the connection
\$conn = null;
?>
      

Using prepared statements (\$conn->prepare()) is the most critical security practice when working with databases. It prevents SQL injection attacks by separating the SQL query from the data.

10 Common PHP Beginner Errors and Their Fixes

# Common Error Why It Happens Solution
1 Parse error: syntax error, unexpected T_STRING... (Missing Semicolon) Forgetting to put a semicolon ; at the end of a line. PHP requires it. Carefully check the line reported in the error message (and the line before it) for a missing semicolon.
2 "Headers already sent" warning. You are trying to modify HTTP headers (e.g., using header(), session_start()) after some HTML or even whitespace has been output to the browser. Make sure all header-modifying functions are called at the very top of your script, before any echo statements or HTML.
3 Undefined index/variable notice. You're trying to access an array key or variable that doesn't exist. Very common with \$_POST or \$_GET if a form field wasn't filled. Always check if a variable or array key exists before using it, with isset() or the null coalescing operator (??). Ex: \$name = \$_POST['name'] ?? 'Guest';
4 Confusing = (assignment) and == (comparison). Using a single equals sign in an if statement (e.g., if (\$a = 5)) assigns a new value and always evaluates to true. Use == for loose comparison or === for strict comparison (value and type) inside conditional statements.
5 Forgetting the \$ on variables. Unlike JavaScript, all variables in PHP must be prefixed with a dollar sign. This is a syntax requirement. Always use \$ when declaring or using variables.
6 Incorrect string concatenation. Using + to join strings like in JavaScript. PHP uses the period . for concatenation. Use the period for concatenation: echo "Hello " . \$name;.
7 SQL Injection Vulnerabilities. Directly inserting user input from \$_POST into a database query string. Always use prepared statements with placeholders when interacting with a database. This is non-negotiable for security.
8 File permission errors. The web server (e.g., Apache) doesn't have the necessary permissions to read or write to a file or directory you're targeting with functions like file_put_contents(). Adjust the file/directory permissions on your server. The web server user (often www-data or apache) needs write access.
9 Not checking form submission method. Accessing \$_POST variables when the page is first loaded via a GET request will cause "Undefined index" notices. Wrap your form processing logic in a check: if (\$_SERVER["REQUEST_METHOD"] == "POST") { ... }.
10 Seeing raw PHP code in the browser. The server is not processing the PHP file; it's just serving it as plain text. This means PHP is not installed correctly or the server isn't configured to handle .php files. Ensure your development stack (XAMPP/MAMP) is running. Make sure your file has a .php extension. Check the server configuration.