Skip to content

Latest commit

 

History

History
394 lines (326 loc) · 6.7 KB

File metadata and controls

394 lines (326 loc) · 6.7 KB

PHP

Hello World

echo "Hello, World!";

Variables and constants

$variable = 10;
define("CONSTANT_VALUE", 5);

Data types

$integer = 42;
$float = 3.14;
$string = "Hello, PHP!";
$boolean = true;
$array = array(1, 2, 3);
$object = new stdClass();
$null = null;

Arrays

$fruits = ["Apple", "Banana", "Orange"];
array_push($fruits, "Mango");

Associative arrays

$person = ["name" => "John", "age" => 25];
$person["city"] = "New York

Conditional statements

if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}

For loop

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

While loop

$count = 0;
while ($count < 5) {
    echo $count;
    $count++;
}

Functions

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

Include and require

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

Working with files

$file = fopen("data.txt", "r");
$content = fread($file, filesize("data.txt"));
fclose($file);

Error handling

try {
    // Code that may throw an exception
} catch (Exception $e) {
    echo "An error occurred: " . $e->getMessage();
}

Cookies

setcookie("username", "John", time() + 3600, "/");
$username = $_COOKIE["username"];

Sessions

session_start();
$_SESSION["user_id"] = 123;

Forms and POST Data

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST["username"];
    $password = $_POST["password"];
}

MySQL Database Connection

$servername = "localhost";
$username = "root";
$password = "password";
$database = "mydb";

$conn = new mysqli($servername, $username, $password, $database);

SQL Queries

$sql = "SELECT * FROM users WHERE username='$username'";
$result = $conn->query($sql);

Fetching data from MySQL

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

Inserting data into MySQL

$sql = "INSERT INTO users (username, password) VALUES ('$username', '$password')";
$conn->query($sql);

Updating data in MySQL

$sql = "UPDATE users SET email='$email' WHERE id=$user_id";
$conn->query($sql);

Deleting data from MySQL

$sql = "DELETE FROM users WHERE id=$user_id";
$conn->query($sql);

Object-oriented programming

class Person {
    public $name;
    public $age;
    
    public function greet() {
        echo "Hello, my name is $this->name.";
    }
}

Inheritance

class Student extends Person {
    public $studentID;
}

Namespaces

namespace MyProject;

Composer (Dependency Manager)

// Install a package
composer require vendor/package

// Autoload packages
require 'vendor/autoload.php';

Regular Expressions

$pattern = "/[0-9]{4}-[0-9]{2}-[0-9]{2}/";
$validDate = preg_match($pattern, "2023-09-04");

Sending emails

$to = "recipient@example.com";
$subject = "Hello";
$message = "This is a test email.";
$headers = "From: sender@example.com";

mail($to, $subject, $message, $headers);

RESTful api

// Handle GET request
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $data = ["message" => "GET request received"];
    echo json_encode($data);
}

File upload

if ($_FILES["file"]["error"] == 0) {
    move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);
}

JSON Handling

$data = '{"name": "John", "age": 30}';
$decodedData = json_decode($data);

Date and time

$currentDate = date("Y-m-d H:i:s");

Templating with PHP

// Include a template file
include "template.php";

URL parameters

$id = $_GET["id"];

File writing

$file = fopen("data.txt", "w");
fwrite($file, "Hello, PHP!");
fclose($file);

Sessions and User Authentication

session_start();
if (!isset($_SESSION["user_id"])) {
    // Redirect to login page
}

URL redirection

header("Location: https://example.com");

Content-Type Headers

header("Content-Type: application/json");

Creating and Using Classes

class Car {
    private $make;
    private $model;
    
    public function __construct($make, $model) {
        $this->make = $make;
        $this->model = $model;
    }
    
    public function getInfo() {
        return "Make: $this->make, Model: $this->model";
    }
}

File deletion

if (file_exists("oldfile.txt")) {
    unlink("oldfile.txt");
}

Working with XML

$xml = simplexml_load_string("<book><title>PHP Basics</title></book>");
$title = $xml->title;

Namespaces in Autoloading

// Autoloading classes within a namespace
spl_autoload_register(function ($className) {
    $className = str_replace("\\", DIRECTORY_SEPARATOR, $className);
    require_once __DIR__ . "/{$className}.php";
});

Exception handling and custom exception classes

class MyCustomException extends Exception {}

try {
    // Some code that may throw an exception
    throw new MyCustomException("This is a custom exception.");
} catch (MyCustomException $e) {
    echo "Caught exception: " . $e->getMessage();
}

Dependency injection in classes

class Database {
    public function __construct($hostname, $username, $password, $database) {
        // Database connection setup
    }
}

$database = new Database("localhost", "username", "password", "mydb");

Namespaces for code organization

namespace MyNamespace;

class MyClass {
    // Class code here
}

PDO (PHP Data objects) for database access

try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydb", "username", "password");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

Dependency injection in functions

function calculateTotal($price, $taxRate) {
    return $price * (1 + $taxRate);
}

$total = calculateTotal(100, 0.1);

Namespaces for third-party libraries

use Vendor\Library\Class;

$instance = new Class();

Composer autoload

require 'vendor/autoload.php';

Singleton pattern

class Singleton {
    private static $instance;
    
    private function __construct() {}
    
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

File download

$file = 'example.txt';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
readfile($file);