บทเรียนการสร้างเว็บไซต์พื้นฐาน

PHP Cheat Sheet - สรุปคำสั่ง PHP

พื้นฐาน PHP

<?php
// คอมเมนต์บรรทัดเดียว

/*
   คอมเมนต์
   หลายบรรทัด
*/

// แสดงผล
echo "Hello World";
print "Hello World";

// ตัวแปร (ขึ้นต้นด้วย $)
$name = "Alice";
$age = 25;
$price = 99.99;
$isActive = true;

// Constants
define("SITE_NAME", "My Website");
const API_KEY = "abc123";

// String Concatenation
echo "Hello " . $name;
echo "Age: $age";  // ใน double quotes
?>

ชนิดข้อมูล

<?php
// String
$text = "Hello";
$text2 = 'World';

// Integer
$number = 42;

// Float
$price = 19.99;

// Boolean
$isTrue = true;
$isFalse = false;

// Array
$fruits = array("apple", "banana");
$fruits = ["apple", "banana"];  // PHP 5.4+

// Associative Array
$person = [
    "name" => "Alice",
    "age" => 25
];

// Null
$empty = null;

// Type Checking
var_dump($variable);
gettype($variable);
is_string($var);
is_int($var);
is_array($var);
?>

Operators

<?php
// Arithmetic
$sum = 5 + 3;
$diff = 5 - 3;
$product = 5 * 3;
$quotient = 5 / 3;
$remainder = 5 % 3;
$power = 5 ** 3;

// Assignment
$x = 10;
$x += 5;
$x -= 3;
$x *= 2;
$x /= 4;
$x++;
$x--;

// Comparison
5 == "5"    // true
5 === "5"   // false
5 != "5"    // false
5 !== "5"   // true
5 > 3       // true
5 < 3       // false
5 >= 5      // true

// Logical
true && false   // false
true || false   // true
!true           // false
true and false  // false
true or false   // true

// Ternary
$result = $age >= 18 ? "Adult" : "Minor";

// Null Coalescing
$name = $_GET['name'] ?? 'Guest';
?>

Control Structures

<?php
// If-Else
if ($age >= 18) {
    echo "Adult";
} elseif ($age >= 13) {
    echo "Teenager";
} else {
    echo "Child";
}

// Switch
switch ($day) {
    case "Monday":
        echo "Start of week";
        break;
    case "Friday":
        echo "End of week";
        break;
    default:
        echo "Midweek";
}

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

// Foreach (Array)
foreach ($fruits as $fruit) {
    echo $fruit;
}

// Foreach (Associative Array)
foreach ($person as $key => $value) {
    echo "$key: $value";
}

// While
$i = 0;
while ($i < 5) {
    echo $i;
    $i++;
}

// Do-While
do {
    echo $i;
    $i++;
} while ($i < 5);
?>

Functions

<?php
// Function Declaration
function greet($name) {
    return "Hello, $name!";
}

// Default Parameters
function greet($name = "Guest") {
    return "Hello, $name!";
}

// Type Hints
function add(int $a, int $b): int {
    return $a + $b;
}

// Variable Functions
$funcName = "greet";
echo $funcName("Alice");

// Anonymous Functions
$greet = function($name) {
    return "Hello, $name!";
};

// Arrow Functions (PHP 7.4+)
$multiply = fn($a, $b) => $a * $b;
?>

String Functions

<?php
$str = "Hello World";

strlen($str)                    // 11
strtoupper($str)               // "HELLO WORLD"
strtolower($str)               // "hello world"
trim($str)                     // ตัดช่องว่าง
str_contains($str, "World")    // true (PHP 8+)
str_starts_with($str, "Hello") // true (PHP 8+)
str_ends_with($str, "World")   // true (PHP 8+)
strpos($str, "World")          // 6
substr($str, 0, 5)             // "Hello"
str_replace("World", "PHP", $str) // "Hello PHP"
explode(" ", $str)             // ["Hello", "World"]
implode(", ", $array)          // "Hello, World"
str_repeat($str, 3)            // "Hello WorldHello WorldHello World"
?>

Array Functions

<?php
$arr = [1, 2, 3, 4, 5];

// Add/Remove
array_push($arr, 6)        // เพิ่มท้าย
array_pop($arr)            // ลบท้าย
array_unshift($arr, 0)     // เพิ่มหน้า
array_shift($arr)          // ลบหน้า
array_splice($arr, 2, 1)   // ลบตำแหน่งที่ 2

// Search
in_array(3, $arr)          // true
array_search(3, $arr)      // 2
array_key_exists("name", $assoc)

// Transform
array_map(fn($x) => $x * 2, $arr)     // [2,4,6,8,10]
array_filter($arr, fn($x) => $x > 2)  // [3,4,5]
array_reduce($arr, fn($sum, $x) => $sum + $x, 0) // 15
sort($arr)                 // เรียงลำดับ
rsort($arr)                // เรียงกลับ
array_reverse($arr)        // กลับลำดับ
array_slice($arr, 1, 3)    // [2,3,4]
array_merge($arr1, $arr2)  // รวม array
implode(", ", $arr)        // "1, 2, 3, 4, 5"

// Keys & Values
array_keys($assoc)         // ["name", "age"]
array_values($assoc)       // ["Alice", 25]
count($arr)                // 5
?>

Superglobals

<?php
// $_GET - URL Parameters
$name = $_GET['name'];

// $_POST - Form Data
$username = $_POST['username'];

// $_REQUEST - GET + POST + COOKIE
$value = $_REQUEST['key'];

// $_SERVER - Server Info
$_SERVER['REQUEST_METHOD']
$_SERVER['HTTP_HOST']
$_SERVER['REQUEST_URI']
$_SERVER['REMOTE_ADDR']

// $_SESSION - Session Data
session_start();
$_SESSION['user_id'] = 123;
$userId = $_SESSION['user_id'];
session_destroy();

// $_COOKIE - Cookies
setcookie("name", "value", time() + 3600);
$value = $_COOKIE['name'];

// $_FILES - Uploaded Files
$_FILES['upload']['name']
$_FILES['upload']['tmp_name']
$_FILES['upload']['size']
$_FILES['upload']['type']
?>

Form Handling

<?php
// Check Request Method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Sanitize Input
    $username = htmlspecialchars($username);
    $username = trim($username);
    $username = stripslashes($username);

    // Validate
    if (empty($username)) {
        $error = "Username is required";
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email";
    }
}
?>

MySQL (mysqli)

<?php
// Connect
$conn = new mysqli("localhost", "root", "", "database");

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Select
$sql = "SELECT * FROM users WHERE age > 18";
$result = $conn->query($sql);

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

// Insert
$sql = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')";
$conn->query($sql);

// Update
$sql = "UPDATE users SET email = 'new@example.com' WHERE id = 1";
$conn->query($sql);

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

// Prepared Statements (ป้องกัน SQL Injection)
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$stmt->close();

// Close Connection
$conn->close();
?>

File Handling

<?php
// Read File
$content = file_get_contents("file.txt");
$lines = file("file.txt");  // Array of lines

// Write File
file_put_contents("file.txt", "Hello World");
file_put_contents("file.txt", "Append", FILE_APPEND);

// Check File
file_exists("file.txt")
is_file("file.txt")
is_dir("folder")
filesize("file.txt")

// Upload File
if (isset($_FILES['upload'])) {
    $target = "uploads/" . basename($_FILES['upload']['name']);
    move_uploaded_file($_FILES['upload']['tmp_name'], $target);
}

// Delete File
unlink("file.txt");
?>

Date & Time

<?php
// Current Date/Time
echo date("Y-m-d H:i:s");      // 2025-01-15 14:30:00
echo date("d/m/Y");            // 15/01/2025
echo time();                   // Unix timestamp

// Format Codes
// Y = ปี 4 หลัก, y = ปี 2 หลัก
// m = เดือน 2 หลัก, n = เดือน 1-2 หลัก
// d = วัน 2 หลัก, j = วัน 1-2 หลัก
// H = ชั่วโมง 24, h = ชั่วโมง 12
// i = นาที, s = วินาที

// Timestamp
$timestamp = strtotime("2025-12-31");
$timestamp = strtotime("+1 week");
$timestamp = strtotime("next Monday");

// DateTime Object
$date = new DateTime();
$date->format("Y-m-d");
$date->modify("+1 day");
?>

Security

<?php
// Password Hashing
$hash = password_hash($password, PASSWORD_DEFAULT);

// Password Verify
if (password_verify($password, $hash)) {
    echo "Password correct";
}

// Escape HTML
$safe = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');

// Prepared Statements (SQL Injection)
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);

// CSRF Token
session_start();
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// Validate CSRF
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("Invalid CSRF token");
}

// Sanitize Input
filter_var($email, FILTER_SANITIZE_EMAIL);
filter_var($url, FILTER_SANITIZE_URL);
filter_var($int, FILTER_SANITIZE_NUMBER_INT);
?>

Common Patterns

<?php
// Redirect
header("Location: page.php");
exit();

// JSON Response
header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => $data]);

// Include Files
include 'header.php';
require 'config.php';
include_once 'functions.php';
require_once 'database.php';

// Error Handling
try {
    // code
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

// Check if Variable is Set
if (isset($variable)) { }
if (!empty($variable)) { }

// Ternary & Null Coalescing
$name = isset($_GET['name']) ? $_GET['name'] : 'Guest';
$name = $_GET['name'] ?? 'Guest';  // PHP 7+
?>

💡 Tips:

  • ใช้ Prepared Statements เสมอเพื่อป้องกัน SQL Injection
  • ใช้ password_hash() สำหรับรหัสผ่าน
  • ใช้ htmlspecialchars() ก่อนแสดงผล user input
  • เปิด error reporting ในระหว่างพัฒนา: error_reporting(E_ALL);
  • ใช้ === แทน == เพื่อเปรียบเทียบแบบเข้มงวด