PHP Cheatsheet

Here is a comprehensive PHP cheat sheet for beginners that covers many common topics.

Variables:

Variables are declared with a dollar sign ($).

// code example
$name = value;

Data Types

This is classification of data that defines the type of values that can be stored in a variable. There are various types of data-types. 

  • String:  Strings can be defined using single or double quotes. To concatenate strings, use the dot (.) operator. 

    //code example
    $greeting = "Hello, " . $name;
  • Integer: A number by numerical value without a decimal point. 

    //code example
    $integer = 10;
  • Float: A number with a decimal point. It is also known as a “floating-point number”.

    //code example
    $float = 10.5;
  • Boolean: A value that can only be either true or false. 

    //code example
    $boolean = true;
  • Array: Array is a special variable to store a collection of multiple values. Two types of arrays are there. Indexed Array and Associative Array. 

    //code example for indexed array
    $fruits = array("apple", "banana", "cherry"); 
    
    //code example for associative array
    $person = array("name" => "John Doe", "age" => 30);
  • NULL: A value that represents a variable with no value

Loops:

There are several types of loops in PHP:

  • for loop

  • while loop

  • foreach loop.

for loop: It is used to execute a block of code for a specified number of times.

//code example
for($i = 0; $i < 5; $i++) {
   echo $i;
}

while loop: It is used to execute a block of code repeatedly jado tak condition is true.

//code example
while($i < 5) {
   echo $i;
   $i++;
}

foreach loop: It is used to iterate through arrays.

foreach($fruits as $fruit) { 
   echo $fruit;
}

Functions

Functions are blocks of code that can be called multiple times.

To define a function, code syntax is:

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

Functions can return a value using the return keyword.

CREATE AN IMAGE FOR REDIRECTION ON PHP PREDEFINED FUNCTIONS. 

Conditional Statements

Conditional statements are used to perform different actions based on different conditions.

PHP supports if statements, if-else statements, and switch statements.

  • If statement code example

    if ($age >= 18) {
       echo "You are an adult";
    }
  • If-else statement code example:

    if ($age >= 18) { 
       echo "You are an adult";
    } else {
       echo "You are not an adult";
    }
  • switch statement code example: 

    switch ($fruit) {
       case "apple": echo "You chose an apple";
       break;
       case "banana": echo "You chose a banana";
       break; 
    }

include and require statements

include and require statements are used to include the contents of one PHP file into another.

The difference between include and require

include statement

require statement

//syntax
include "header.php";
//syntax
require "config.php";

If the file mentioned in the include statement cannot be found, the script will continue to execute

If file mentioned in the require statement cannot be found, the script will stop executing

$_GET and $_POST

$_GET and $_POST are superglobals arrays in PHP that are used to retrieve data from GET and POST requests, respectively.

To access a value from the $_GET or $_POST array, use the array key in square brackets. Examples are below:

$_GET["name"];
$email = $_POST["email"];

 $_SESSION and $_COOKIE arrays

$_SESSION and $_COOKIE are also superglobals arrays in PHP that are used to store and retrieve session and cookie data, respectively.

$_SESSION

$_COOKIES

To start a session, use the session_start() function

To set a cookie, use the setcookie() function.

To set a session variable, assign a value to an element in the $_SESSION array. For Example: 

session_start();
$_SESSION["name"] = "John Doe";

Example:

setcookie("email", "[email protected]", time() + 86400);

 File Handling:

PHP provides several functions for reading, writing, and manipulating files.

  • To open a file, use the fopen() function.

    $file = fopen("data.txt", "r");
  • To read from a file, use the fread() or fgets() functions.

    while (!feof($file)) { echo fgets($file) . "<br>"; }
  • To write to a file, use the fwrite() function.

    fwrite($file, "Hello, World!");
  • To close a file, use the fclose() function.

    fclose($file);

Regular Expressions

It helps for pattern matching and manipulation in PHP. PHP provides several functions for working with regular expressions, including preg_match(), preg_replace(), and preg_split().

Regular expressions are defined using a special syntax that uses characters and special symbols to define a pattern. Here are few examples:

preg_match("/[A-Za-z]+/", "Hello, World!", $matches);
preg_replace("/[0-9]+/", "", "1 2 3 4 5");
preg_split("/[\s,]+/", "Hello, World!");

 Error Handling

There are several functions for handling errors in PHP, including trigger_error(), set_error_handler(), and try-catch blocks.

To raise an error, use the trigger_error() function.

trigger_error("An error occurred", E_USER_ERROR);

To handle errors, use the set_error_handler() function or a try-catch block.

set_error_handler(function ($errno, $errstr, $errfile, $errline) { echo "$errstr in $errfile on line $errline"; });
try { $result = 1/0; } catch (Exception $e) { echo $e->getMessage(); }

Database Connections

There are several functions for connecting to and working with databases, including MySQL, PostgreSQL, and SQLite.

To connect to a database, use the mysqli_connect() or PDO::__construct() function.

$conn = mysqli_connect("localhost", "username", "password", "database");
$conn = new PDO("mysql:host=localhost;dbname=database", "username", "password");
while ($row = mysqli_fetch_assoc($result)) { echo $row["name"] . "<br>"; }

To perform a query, use the mysqli_query() or PDO::prepare() and PDO::execute() functions.

$result = mysqli_query($conn, "SELECT * FROM users");
$stmt = $conn->prepare("SELECT * FROM users");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
   echo $row["name"] . "<br>";
}

To retrieve data, use the mysqli_fetch_assoc() or PDO::fetch() functions.

Classes and Objects

PHP supports object-oriented programming through the use of classes and objects. 

To define a class, use the class keyword followed by the class name.

//For Example
class Car {
   public $make; public $model;
   public function honk() {
      echo "Honk honk!";
   }
}

Object is an instance of data structure defined by a class that contains data and functions. We can create multiple objects of a single class. 

//Example
$car = new Car();
$car->make = "Toyota";
$car->model = "Camry";
$car->honk();

Namespaces:

Namespaces are used to organize and prevent naming collisions in large PHP projects.

To define namespaces, use the namespace keyword followed by the namespace name.

namespace App\Models; class User { /* ... */ }

To use a class or function in a namespace, use the namespace name followed by the class or function name.

use App\Models\User; $user = new User();

Interfaces:

PENDING 

Traits:

Traits are used to share common code between multiple classes. It is a unit of reusable code that can be used in multiple classes.

trait Logger {
   public function log(string $message) {
      file_put_contents("log.txt", $message . PHP_EOL, FILE_APPEND);
   }
}
class User {
   use Logger; /* ... */
}

Magic Methods:

Magic methods always start and end with two underscores. 

  • __construct

  • __destruct

  • __get

  • __set

  • __call

  • __toString

class User {
   public function __construct(string $name) {
      $this->name = $name;
   }
   public function __toString() {
      return $this->name;
   }
}

Debugging:

Debugging is an important part of any software development process.

error_reporting(): This PHP function is used to debug and display error messages

error_reporting(E_ALL); 
ini_set("display_errors", "1");

var_dump(): Use this function to inspect variables. 

var_dump($x);

die() or exit(): Use to stop execution when necessary.

die("An error occurred");

Security:

A very important consideration in PHP programming. There are some pre-built PHP functions to prevent SQL injections, cross-site scripting or some other attacks. Here are a few.

To prevent SQL injection attacks, use prepared statements or escape user input using the mysqli_real_escape_string() function.

$name = mysqli_real_escape_string($conn, $_POST["name"]);

To prevent cross-site scripting (XSS) attacks, escape user input using the htmlspecialchars() function.

$name = htmlspecialchars($_POST["name"]);

To prevent cross-site request forgery (CSRF) attacks, use tokens or check the HTTP referer header.

if ($_SERVER["HTTP_REFERER"] !== "https://example.com") {
   die("Invalid request");
}

To prevent file inclusion attacks, check the file extension and/or use an .htaccess file to restrict access to sensitive files.

if (strtolower(pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION)) !== "txt") {
   die("Invalid file type");
}

Topic

Download your free Ebook

Download a free copy of our newest E-book on "Metadata HTML Elements".


Awesome!

Download a free copy of our newest E-book on "Metadata HTML Elements".