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.
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 questionsWhy Learn PHP?
PHP is useful for building many types of web applications, including:
- Business websites and blogs
- Content management systems
- Online stores
- User registration and login systems
- Database-driven dashboards
- Backend services and APIs
- Forums, directories and booking systems
How Does PHP Work?
- A visitor opens a webpage or submits a form.
- The browser sends an HTTP request to a server.
- The server executes the relevant PHP code.
- PHP may read or update a database.
- The server sends a response back to the browser.
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.
- PHP runtime
- A text editor or code editor
- A browser for viewing web output
- Optional: a database such as MySQL or MariaDB
For installation instructions, visit the official PHP installation guide.
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.
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
| Type | Example | Purpose |
|---|---|---|
| String | "Hello" | Text |
| Integer | 25 | Whole numbers |
| Float | 25.5 | Decimal numbers |
| Boolean | true | True or false values |
| Array | [1, 2, 3] | Multiple values |
| Null | null | No value |
| Object | new 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;
GET and POST
| GET | POST |
|---|---|
| Often used to retrieve information | Often used to submit information |
| Parameters may appear in the URL | Data is generally sent in the request body |
| Can be bookmarked with query parameters | Usually not bookmarked as submitted form data |
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"
]);
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();
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.
- Set reasonable upload size limits.
- Validate file content and allowed types.
- Generate safe server-side filenames.
- Store uploads outside executable public directories when possible.
- Check upload errors and permissions.
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);
PHP Security Best Practices
- Use HTTPS in production.
- Validate input on the server.
- Escape output according to its context.
- Use prepared statements for database queries.
- Hash passwords with PHP's password functions.
- Keep PHP and third-party packages updated.
- Protect session cookies and authentication routes.
- Store credentials outside publicly accessible source files.
- Limit upload types, sizes and storage permissions.
- Do not show detailed error messages to visitors in production.
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
| PHP | JavaScript |
|---|---|
| Commonly executes on the server | Commonly executes in the browser |
| Can generate HTML and API responses | Can update webpage content interactively |
| Can also run in command-line environments | Can 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
- Open-source and widely documented.
- Supported by many web hosting providers.
- Works with popular databases.
- Has a large ecosystem of packages and frameworks.
- Can build websites, APIs and backend systems.
- Offers tools for many common web development tasks.
Common Beginner Mistakes
- Forgetting semicolons.
- Using variables before setting their values.
- Displaying user input without proper escaping.
- Building SQL queries by concatenating untrusted values.
- Storing passwords in plain text.
- Publishing database credentials.
- Ignoring errors during development.
- Using an outdated PHP version.
Beginner PHP Projects
Practice what you learn by building small projects:
- Simple calculator
- Contact form with validation
- To-do list
- Student record system
- Blog with database storage
- Registration and login system
- Product catalogue
- Basic JSON API
PHP Learning Roadmap
- Understand basic programming concepts.
- Learn PHP syntax, variables and data types.
- Practice conditions, loops and functions.
- Learn arrays and working with strings.
- Understand HTML forms and HTTP requests.
- Learn sessions and cookies.
- Study SQL and database connections.
- Learn input validation and output escaping.
- Understand authentication and password hashing.
- Build and test APIs that return JSON.
- Learn Composer and dependency management.
- Explore a framework such as Laravel.
- Build complete projects and deploy them securely.
PHP Cheat Sheet
| Concept | Example |
|---|---|
| PHP opening tag | <?php |
| Variable | $name = "Ahmed"; |
| Output | echo "Hello"; |
| Condition | if ($age >= 18) { } |
| Function | function greet() { } |
| Array | ["A", "B", "C"] |
| GET input | $_GET["id"] |
| POST input | $_POST["name"] |
| Session | $_SESSION["user"] |
| JSON response | json_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.
Related Learning Resources
Some related pages may need to be created and linked on the website before they can be opened.