PHP Programming Guide

Learn Technology in Simple English

What Is PHP?

PHP is an open-source server-side programming language commonly used to create dynamic websites, web applications and APIs. PHP code usually runs on a web server, which sends the resulting response to a browser or another application.

PHP originally stood for Personal Home Page. Today, PHP is commonly expanded as PHP: Hypertext Preprocessor.

Simple explanation: HTML describes webpage structure, CSS controls appearance, JavaScript adds browser-side interactivity, and PHP can process information on a server.

In This Guide

1. How PHP works 2. Your first PHP program 3. Variables and data types 4. Conditions and loops 5. Functions and arrays 6. HTML forms and requests 7. PHP and databases 8. PHP security 9. Object-oriented PHP 10. Composer and Laravel 11. PHP APIs and JSON 12. Beginner projects 13. Frequently asked questions

Why Learn PHP?

PHP is useful for building many types of web applications, including:

How Does PHP Work?

  1. A visitor opens a webpage or submits a form.
  2. The browser sends an HTTP request to a server.
  3. The server executes the relevant PHP code.
  4. PHP may read or update a database.
  5. The server sends a response back to the browser.
Visitors normally receive the output generated by PHP, not the server-side PHP source code itself.

What Do You Need to Run PHP?

To execute PHP code, you need PHP installed on a computer or a hosting service that supports PHP. A code editor helps you write the files.

For installation instructions, visit the official PHP installation guide.

A static HTML hosting service does not execute PHP files automatically. If you upload a PHP file to a static-only host, it will not behave like a PHP-enabled web server.

Your First PHP Program

Create a file called hello.php and add:

<?php
echo "Hello, world!";

The echo statement outputs text. You can run the file using PHP's local development server from the folder containing it:

php -S localhost:8000

Then open http://localhost:8000/hello.php in your browser.

The built-in PHP server is intended for local development and testing, not for public production hosting.

PHP Syntax

PHP code normally starts with <?php. In a PHP-only file, the closing ?> tag is often omitted to avoid accidental output after the PHP code.

<?php
$name = "Ahmed";
echo $name;

Variable names begin with $, and ordinary PHP statements commonly end with a semicolon.

PHP Variables

<?php
$name = "Ahmed";
$age = 20;
$price = 15.50;
$isStudent = true;

echo $name;
echo $age;

Variables allow a program to store and work with information. PHP determines a variable's type from its value in many ordinary assignments.

PHP Data Types

TypeExamplePurpose
String"Hello"Text
Integer25Whole numbers
Float25.5Decimal numbers
BooleantrueTrue or false values
Array[1, 2, 3]Multiple values
NullnullNo value
Objectnew User()An instance of a class

Strings and Joining Text

PHP uses the dot operator to concatenate strings.

<?php
$name = "Ahmed";
$message = "Hello " . $name;

echo $message;

You can also use double-quoted strings to interpolate many variable values:

<?php
$name = "Ahmed";
echo "Hello $name";

Numbers and Arithmetic

<?php
$a = 10;
$b = 5;

echo $a + $b;
echo $a - $b;
echo $a * $b;
echo $a / $b;
echo $a % $b;

The operators shown perform addition, subtraction, multiplication, division and remainder.

Constants

Constants store values that are intended to remain fixed during program execution.

<?php
define("SITE_NAME", "TechLearn Hub");
echo SITE_NAME;

If and Else

<?php
$age = 20;

if ($age >= 18) {
    echo "Adult";
} else {
    echo "Minor";
}

Conditional statements allow programs to choose what to do based on a condition.

Elseif Statements

<?php
$score = 75;

if ($score >= 80) {
    echo "Excellent";
} elseif ($score >= 60) {
    echo "Good";
} else {
    echo "Keep practicing";
}

Switch Statements

<?php
$day = "Monday";

switch ($day) {
    case "Monday":
        echo "Start of the week";
        break;
    case "Friday":
        echo "End of the work week";
        break;
    default:
        echo "Another day";
}

Loops in PHP

For loop

<?php
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}

While loop

<?php
$i = 1;
while ($i <= 5) {
    echo $i . " ";
    $i++;
}

Foreach loop

<?php
$names = ["Ahmed", "Ali", "Umar"];

foreach ($names as $name) {
    echo $name . " ";
}

Functions

Functions let you reuse code rather than writing the same instructions repeatedly.

<?php
function greet($name) {
    return "Hello " . $name;
}

echo greet("Ahmed");

Function Parameters and Return Values

<?php
function add(int $a, int $b): int {
    return $a + $b;
}

$result = add(5, 3);
echo $result;

Parameter and return type declarations can make code clearer and help detect incorrect values.

Indexed Arrays

<?php
$names = ["Ahmed", "Ali", "Umar"];

echo $names[0];

PHP arrays can hold multiple values. Indexed arrays use numeric indexes that commonly begin at zero.

Associative Arrays

<?php
$user = [
    "name" => "Ahmed",
    "age" => 20,
    "country" => "Nigeria"
];

echo $user["name"];

Associative arrays use keys such as name and country to access values.

PHP and HTML

PHP can generate dynamic content within an HTML page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Example</title>
</head>
<body>
    <h1>
        <?php echo "Welcome to TechLearn Hub"; ?>
    </h1>
</body>
</html>

HTML Forms and PHP

Forms allow visitors to send information to a server. The following example uses POST to send a name to a PHP file called process.php.

<form action="process.php" method="post">
    <label for="username">Your name</label>
    <input id="username" type="text" name="username" required>
    <button type="submit">Submit</button>
</form>

In process.php:

<?php
$username = trim($_POST["username"] ?? "");

if ($username === "") {
    http_response_code(400);
    exit("Please enter your name.");
}

$safeName = htmlspecialchars(
    $username,
    ENT_QUOTES | ENT_SUBSTITUTE,
    "UTF-8"
);

echo "Hello, " . $safeName;
Escaping output is important when displaying user-provided text in HTML. Validation and output escaping solve different problems, and both may be necessary.

GET and POST

GETPOST
Often used to retrieve informationOften used to submit information
Parameters may appear in the URLData is generally sent in the request body
Can be bookmarked with query parametersUsually not bookmarked as submitted form data
POST does not automatically encrypt information. Use HTTPS and appropriate application security. Never put passwords or other secrets in URLs.

Sessions

Sessions can preserve user-specific state across requests. On a typical page, call session_start() before sending output.

<?php
session_start();

$_SESSION["username"] = "Ahmed";

echo $_SESSION["username"];

Real login systems need secure cookie settings, session ID regeneration after authentication and appropriate logout handling.

Cookies

Cookies allow a website to store small pieces of information in a visitor's browser.

<?php
setcookie("theme", "dark", [
    "expires" => time() + 3600,
    "path" => "/",
    "secure" => true,
    "httponly" => true,
    "samesite" => "Lax"
]);
The secure option requires HTTPS. Cookie settings should be selected to match the application's security and deployment requirements.

PHP and Databases

PHP applications often use databases to store information such as user accounts, products, orders, messages, articles and application settings.

Popular database choices include MySQL, MariaDB, PostgreSQL and SQLite. The appropriate choice depends on the application's requirements and hosting environment.

Connecting to MySQL with PDO

PDO provides a consistent interface for accessing supported databases. The following example assumes that the database, table, credentials and $email variable have already been configured.

<?php
$pdo = new PDO(
    "mysql:host=localhost;dbname=mydatabase;charset=utf8mb4",
    "database_user",
    "database_password",
    [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
);

$stmt = $pdo->prepare(
    "SELECT id, email FROM users WHERE email = ?"
);

$stmt->execute([$email]);
$user = $stmt->fetch();
Use environment variables or a secure configuration system for database credentials. Do not publish real passwords in source code or public repositories.

SQL Injection

SQL injection can occur when an application inserts untrusted input into SQL queries unsafely.

Prepared statements separate query structure from supplied values and are an important defence against SQL injection.

// Safer: use a prepared statement.
$stmt = $pdo->prepare(
    "SELECT id FROM users WHERE email = ?"
);

$stmt->execute([$email]);

File Handling

PHP can read and write files when the server process has the required permissions.

<?php
$file = __DIR__ . "/notes.txt";

file_put_contents($file, "Hello from PHP");

$content = file_get_contents($file);
echo htmlspecialchars($content, ENT_QUOTES, "UTF-8");

Be careful when handling files supplied by users. File paths and permissions should be controlled.

File Uploads

PHP can handle uploaded files using forms with enctype="multipart/form-data" and the $_FILES array.

Do not trust a filename or MIME type supplied by the browser. Secure uploads require server-side validation and a suitable storage design.

PHP APIs and JSON

PHP can create APIs that exchange data with websites, mobile apps and other services. JSON is a common response format.

<?php
header("Content-Type: application/json; charset=utf-8");

$data = [
    "name" => "Ahmed",
    "country" => "Nigeria"
];

echo json_encode($data);

Production APIs should also validate input, use appropriate HTTP status codes, authenticate protected operations and avoid exposing private information.

Authentication and Password Hashing

PHP supports password hashing through built-in functions. Store password hashes, not plaintext passwords.

<?php
$password = "example-password";

$hash = password_hash(
    $password,
    PASSWORD_DEFAULT
);

// During login:
$isValid = password_verify($password, $hash);
This is a learning example, not a complete login system. Real authentication also requires safe database storage, session protection, rate limiting and secure password-reset handling.

PHP Security Best Practices

Read the official PHP security documentation for more information.

Error Handling

Exceptions allow applications to handle certain failures in a structured way.

<?php
try {
    throw new Exception("Something went wrong");
} catch (Exception $error) {
    echo "An error occurred.";
}

In production, log technical details securely rather than displaying sensitive exception messages to users.

Object-Oriented PHP

PHP supports classes, objects, properties, methods, inheritance and interfaces.

<?php
class User {
    public function __construct(
        public string $name
    ) {}

    public function greet(): string {
        return "Hello " . $this->name;
    }
}

$user = new User("Ahmed");
echo $user->greet();

This example uses constructor property promotion, available in modern PHP versions. Check your server's PHP version before using newer language features.

Namespaces

Namespaces help organize classes and reduce naming conflicts in larger applications.

<?php
namespace App\Models;

class User {
    // Add model logic here.
}

What Is Composer?

Composer is a dependency manager widely used in PHP projects. It installs packages and helps maintain the dependencies a project needs.

Visit the official Composer documentation to learn how to install and use it.

What Is Laravel?

Laravel is a PHP web framework that provides a structure and tools for building web applications and APIs.

Features include routing, request validation, database access, templates, queues and authentication integrations.

Start with the official Laravel documentation.

PHP vs JavaScript

PHPJavaScript
Commonly executes on the serverCommonly executes in the browser
Can generate HTML and API responsesCan update webpage content interactively
Can also run in command-line environmentsCan also run on servers through environments such as Node.js

Can PHP Build Mobile Apps?

PHP is mainly used for server-side programming rather than building native Android or iOS interfaces. A mobile app can communicate with a PHP backend through an API to retrieve and save data.

Advantages of PHP

Common Beginner Mistakes

Beginner PHP Projects

Practice what you learn by building small projects:

  1. Simple calculator
  2. Contact form with validation
  3. To-do list
  4. Student record system
  5. Blog with database storage
  6. Registration and login system
  7. Product catalogue
  8. Basic JSON API
Build each project in stages. First make it work, then improve validation, security, code organization and user experience.

PHP Learning Roadmap

  1. Understand basic programming concepts.
  2. Learn PHP syntax, variables and data types.
  3. Practice conditions, loops and functions.
  4. Learn arrays and working with strings.
  5. Understand HTML forms and HTTP requests.
  6. Learn sessions and cookies.
  7. Study SQL and database connections.
  8. Learn input validation and output escaping.
  9. Understand authentication and password hashing.
  10. Build and test APIs that return JSON.
  11. Learn Composer and dependency management.
  12. Explore a framework such as Laravel.
  13. Build complete projects and deploy them securely.

PHP Cheat Sheet

ConceptExample
PHP opening tag<?php
Variable$name = "Ahmed";
Outputecho "Hello";
Conditionif ($age >= 18) { }
Functionfunction greet() { }
Array["A", "B", "C"]
GET input$_GET["id"]
POST input$_POST["name"]
Session$_SESSION["user"]
JSON responsejson_encode($data)

Frequently Asked Questions

Is PHP free?

Yes. PHP is open-source and can be used without paying a language licence fee.

Can PHP build websites?

Yes. PHP is commonly used to build dynamic websites and web applications.

Can PHP connect to MySQL?

Yes. PHP can connect to MySQL through extensions and database interfaces such as PDO and MySQLi.

Can PHP build APIs?

Yes. PHP can provide API endpoints that exchange data with websites, mobile apps and other services.

Is PHP difficult to learn?

The basics are approachable for many learners. Database programming, security and frameworks require continued practice.

Should I learn SQL with PHP?

Yes, if you want to build applications that store, retrieve or update database information.

Does PHP work on static hosting?

PHP requires a server environment that executes PHP. Static hosting alone does not run PHP code.

What should I learn after PHP basics?

Learn forms, databases, security, APIs, Composer and then a framework such as Laravel.

Conclusion

PHP is a useful server-side programming language for creating dynamic websites, web applications, APIs and database-driven systems.

Start with syntax and small examples, then practise forms, databases, authentication, security and frameworks. Building real projects is one of the best ways to develop your skills.

Official resource: Continue learning through the PHP documentation.

Related Learning Resources

Some related pages may need to be created and linked on the website before they can be opened.