Language: EN

cheatsheet-php

PHP Cheatsheet

PHP (Hypertext Preprocessor) is a general-purpose programming language, primarily designed for web development.

It runs on the server and generates dynamic HTML for the client.

Installation and Configuration

Installing PHP on Windows

Visit php.net/downloads and download the latest version of PHP for Windows.

Installing PHP on Linux

Install PHP on a Linux system using apt.

sudo apt update
sudo apt install php

Check PHP Version

Check the installed PHP version.

php -v

Run a PHP Script from Terminal

You can run PHP scripts directly from the command line.

php script.php

Introduction

Basic Syntax of PHP

A PHP script is enclosed between <?php ... ?> tags in a .php file.

<?php
echo "Hello, world!";
?>

Comments in PHP

You can add comments using //, #, or /* */ for block comments.

// Single line comment
# Single line comment
/* Multi-line
   comment */

Variables and Data Types

Variable Declaration

Variables in PHP are declared with the $ sign followed by the variable name.

$variable = "value";

Data Types in PHP

PHP is a loosely typed language. The main data types are:

  • int (integers)
  • float (decimal numbers)
  • string (text strings)
  • bool (boolean)
  • array
  • object

Check Variable Type

Use gettype() to check the type of a variable.

echo gettype($variable);

Type Casting

To explicitly convert one data type to another, casting is used.

$integer = (int) "10";  // Convert string to integer

Operators in PHP

Arithmetic Operators

PHP supports basic operators for addition, subtraction, multiplication, and division.

$a + $b;  // Addition
$a - $b;  // Subtraction
$a * $b;  // Multiplication
$a / $b;  // Division
$a % $b;  // Modulus

Comparison Operators

Compares two values. Returns true or false.

$a == $b;   // Equal
$a === $b;  // Equal and of the same type
$a != $b;   // Not equal
$a !== $b;  // Not equal and of a different type
$a > $b;    // Greater than
$a < $b;    // Less than

Logical Operators

Used to perform logical operations.

$a && $b;   // Logical AND
$a || $b;   // Logical OR
!$a;        // Negation

Control Structures

Conditionals: if, else, elseif

PHP uses if, else, and elseif to control the program flow.

if ($a > $b) {
    echo "$a is greater than $b";
} elseif ($a == $b) {
    echo "$a is equal to $b";
} else {
    echo "$a is less than $b";
}

Switch Case

To evaluate multiple conditions.

$color = "red";
switch ($color) {
    case "red":
        echo "The color is red";
        break;
    case "blue":
        echo "The color is blue";
        break;
    default:
        echo "Unknown color";
}

Loops

Loops allow you to execute a block of code repeatedly.

For Loop

for ($i = 0; $i < 10; $i++) {
    echo $i;
}

While Loop

$i = 0;
while ($i < 10) {
    echo $i;
    $i++;
}

Foreach Loop

$array = array(1, 2, 3, 4);
foreach ($array as $value) {
    echo $value;
}

Functions

Define a Function

Functions in PHP are defined with the function keyword.

function sum($a, $b) {
    return $a + $b;
}

echo sum(2, 3);  // Prints 5

Anonymous Functions and Callbacks

PHP also allows defining anonymous functions.

$anonymous = function($name) {
    return "Hello, " . $name;
};

echo $anonymous("World");  // Prints "Hello, World"

Pass by Reference

Parameters can be passed by reference using &.

function increment(&$number) {
    $number++;
}

$a = 5;
increment($a);
echo $a;  // Prints 6

Array Handling

PHP has several types of arrays: indexed and associative.

Indexed Array

An array in PHP can be created with the array() function or with [].

<?php
    $fruits = ["apple", "banana", "orange"];
    echo $fruits[0];  // apple
?>

Associative Array

An associative array uses keys instead of numeric indices.

<?php
    $person = ["name" => "John", "age" => 21];
    echo $person["name"];  // John
?>

Loop Through Arrays

Use foreach to loop through arrays.

foreach ($array as $value) {
    echo $value;
}

Useful Array Functions

PHP includes several built-in functions for working with arrays.

  • Add an element to the end of the array
array_push($array, "new");
  • Remove the last element
array_pop($array);
  • Count elements in the array
echo count($array);

Object-Oriented Programming (OOP)

Classes and Objects

PHP supports object-oriented programming with classes, objects, inheritance, and more.

class Person {
    public $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function greet() {
        echo "Hello, I am " . $this->name;
    }
}

$person = new Person("John");
$person->greet();  // Prints "Hello, I am John"

Inheritance

Classes can inherit from other classes.

class Student extends Person {
    public $major;

    public function __construct($name, $major) {
        parent::__construct($name);
        $this->major = $major;
    }

    public function study() {
        echo $this->name . " is studying " . $this->major;
    }
}

$student = new Student("Ana", "Engineering");
$student->study();  // Prints "Ana is studying Engineering"

Encapsulation

Access to properties and methods can be controlled with access modifiers public, private, protected.

class Person {
    private $age;

    public function setAge($age) {
        $this->age = $age;
    }

    public function getAge() {
        return $this->age;
    }
}

Interfaces

Interfaces allow you to define which methods classes must implement.

interface Shape {
    public function area();
}

class Square implements Shape {
    public $side;
    
    public function __construct($side) {
        $this->side = $side;
    }

    public function area() {
        return $this->side * $this->side;
    }
}

Forms

Get Data from a Form

PHP can handle data sent (GET/POST) from an HTML form.

// Get data with POST method
$name = $_POST['name'];

// Get data with GET method
$age = $_GET['age'];

Data Validation

Validating data is essential for security.

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Valid email";
} else {
    echo "Invalid email";
}

Data Sanitization

Used to clean inputs and prevent injection attacks.

$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);

Sessions and Cookies

Start Session

Sessions allow storing data on the server between requests.

session_start();
$_SESSION['user'] = 'John';

End Session

Destroys all session variables.

session_destroy();

Cookies

Cookies allow storing data in the user’s browser.

setcookie("user", "John", time() + 3600);

Read Cookies

To get the value of a cookie.

echo $_COOKIE['user'];

File Handling

Read a File

Use fopen, fread, or file_get_contents to read files.

<?php
    $content = file_get_contents("file.txt");
    echo $content;
?>

Write to a File

Use fwrite to write to files.

<?php
    $file = fopen("file.txt", "w");
    fwrite($file, "New content");
    fclose($file);
?>

Database Connection

Connect to a MySQL Database

Use mysqli to connect to a database.

<?php
    $conn = new mysqli("localhost", "user", "password", "database");
    
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
?>

Execute SQL Queries

Run an SQL query and get results.

<?php
    $result = $conn->query("SELECT * FROM users");

    while ($row = $result->fetch_assoc()) {
        echo $row["name"];
    }
?>

Close Connection

Always close the connection after finishing.

<?php
    $conn->close();
?>

Connect to a MySQL Database using PDO

PHP uses PDO to connect to databases.

try {
    $pdo = new PDO('mysql:host=localhost;dbname=my_database', 'user', 'password');
   

 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $stmt = $pdo->query("SELECT * FROM table");
    while ($row = $stmt->fetch()) {
        echo $row['column'];
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

Errors and Debugging

Display Errors

Configure PHP to display all errors during development.

<?php
    error_reporting(E_ALL);
    ini_set("display_errors", 1);
?>

Log Errors to a File

Log errors to a log file.

<?php
    ini_set("log_errors", 1);
    ini_set("error_log", "/path/error_log.txt");
?>