PHP 示例
基础PHP代码示例,包括Web开发、现代PHP 8+特性和框架
💻 PHP Hello World php
🟢 simple
⭐
PHP Hello World程序和基础Web开发概念
⏱️ 12 min
🏷️ php, web development, server-side
Prerequisites:
Basic programming concepts, HTML basics
<?php
// PHP Hello World Examples
// 1. Basic Hello World
<?php
echo "Hello, World!";
?>
// 2. Hello World with variable
<?php
$message = "Hello, World!";
echo $message;
?>
// 3. Hello World with function
<?php
function sayHello() {
return "Hello, World!";
}
echo sayHello();
?>
// 4. Hello World with parameters
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
echo greet("World");
echo greet("PHP");
?>
// 5. Hello World with class
<?php
class Greeter {
private $message;
public function __construct($message = "Hello, World!") {
$this->message = $message;
}
public function greet() {
return $this->message;
}
}
$greeter = new Greeter();
echo $greeter->greet();
?>
// 6. Hello World with user input
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'] ?? 'World';
echo "Hello, " . htmlspecialchars($name) . "!";
} else {
?>
<form method="post" action="">
Name: <input type="text" name="name">
<input type="submit" value="Say Hello">
</form>
<?php
}
?>
// 7. Hello World with date and time
<?php
echo "Hello, World! Current time: " . date('Y-m-d H:i:s');
?>
// 8. Hello World multiple times
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Hello, World! $i<br>";
}
?>
// 9. Hello World in different languages
<?php
$greetings = [
'en' => 'Hello, World!',
'es' => '¡Hola, Mundo!',
'fr' => 'Bonjour, le Monde!',
'de' => 'Hallo, Welt!',
'zh' => '你好,世界!',
'ja' => 'こんにちは、世界!'
];
$lang = $_GET['lang'] ?? 'en';
echo $greetings[$lang] ?? $greetings['en'];
?>
// 10. Hello World with JSON response
<?php
header('Content-Type: application/json');
$response = [
'message' => 'Hello, World!',
'timestamp' => time(),
'success' => true
];
echo json_encode($response, JSON_PRETTY_PRINT);
?>
// Basic data types examples
<?php
$integer = 42;
$float = 3.14;
$string = "Hello, PHP!";
$boolean = true;
$array = [1, 2, 3, 4, 5];
$associative = [
'name' => 'John Doe',
'age' => 30,
'email' => '[email protected]'
];
$nullValue = null;
echo "Integer: $integer, Type: " . gettype($integer) . "<br>";
echo "Float: $float, Type: " . gettype($float) . "<br>";
echo "String: $string, Type: " . gettype($string) . "<br>";
echo "Boolean: " . ($boolean ? 'true' : 'false') . ", Type: " . gettype($boolean) . "<br>";
echo "Array: " . implode(', ', $array) . ", Type: " . gettype($array) . "<br>";
echo "Associative Array: " . print_r($associative, true) . ", Type: " . gettype($associative) . "<br>";
// Control flow examples
$age = 18;
if ($age >= 18) {
echo "You are an adult<br>";
} else {
echo "You are a minor<br>";
}
// Loop examples
$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
echo "I like $fruit<br>";
}
// Array methods examples
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) { return $n * $n; }, $numbers);
echo "Squared numbers: " . implode(', ', $squared);
// Superglobals examples
echo "Request Method: " . $_SERVER['REQUEST_METHOD'] . "<br>";
echo "Server Name: " . $_SERVER['SERVER_NAME'] . "<br>";
echo "Request URI: " . $_SERVER['REQUEST_URI'] . "<br>";
// Sessions example
<?php
session_start();
$_SESSION['message'] = 'Hello, Session World!';
echo $_SESSION['message'];
?>
💻 PHP Web开发 php
🟡 intermediate
⭐⭐⭐
现代PHP Web开发,包括表单处理、数据库操作和REST API
⏱️ 30 min
🏷️ php, web development, database, api
Prerequisites:
Basic PHP, HTML forms, Database concepts
<?php
// PHP Web Development Examples
// 1. Form Handling with Validation
<?php
$errors = [];
$success = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$age = intval($_POST['age'] ?? 0);
// Validation
if (empty($name)) {
$errors['name'] = 'Name is required';
} elseif (strlen($name) < 2) {
$errors['name'] = 'Name must be at least 2 characters';
}
if (empty($email)) {
$errors['email'] = 'Email is required';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email format';
}
if ($age < 1 || $age > 120) {
$errors['age'] = 'Age must be between 1 and 120';
}
if (empty($errors)) {
// Process the valid data
$success = "Form submitted successfully! Name: $name, Email: $email, Age: $age";
// You could save to database here
// saveUser($name, $email, $age);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Form Validation</title>
</head>
<body>
<?php if ($success): ?>
<div style="color: green;"><?php echo htmlspecialchars($success); ?></div>
<?php endif; ?>
<?php if (!empty($errors)): ?>
<div style="color: red;">
<?php foreach ($errors as $error): ?>
<div><?php echo htmlspecialchars($error); ?></div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form method="post">
<div>
<label>Name:</label>
<input type="text" name="name" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
</div>
<div>
<label>Email:</label>
<input type="email" name="email" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
</div>
<div>
<label>Age:</label>
<input type="number" name="age" value="<?php echo htmlspecialchars($_POST['age'] ?? ''); ?>">
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
// 2. Database Operations with PDO
<?php
class Database {
private $pdo;
public function __construct($host, $dbname, $username, $password) {
try {
$this->pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]
);
} catch (PDOException $e) {
throw new Exception("Database connection failed: " . $e->getMessage());
}
}
public function createUser($name, $email, $age) {
$stmt = $this->pdo->prepare(
"INSERT INTO users (name, email, age, created_at) VALUES (?, ?, ?, NOW())"
);
return $stmt->execute([$name, $email, $age]);
}
public function getUser($id) {
$stmt = $this->pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$id]);
return $stmt->fetch();
}
public function getAllUsers($limit = 10, $offset = 0) {
$stmt = $this->pdo->prepare("SELECT * FROM users LIMIT ? OFFSET ?");
$stmt->execute([$limit, $offset]);
return $stmt->fetchAll();
}
public function updateUser($id, $name, $email, $age) {
$stmt = $this->pdo->prepare(
"UPDATE users SET name = ?, email = ?, age = ?, updated_at = NOW() WHERE id = ?"
);
return $stmt->execute([$name, $email, $age, $id]);
}
public function deleteUser($id) {
$stmt = $this->pdo->prepare("DELETE FROM users WHERE id = ?");
return $stmt->execute([$id]);
}
}
// Usage example:
try {
$db = new Database('localhost', 'myapp', 'username', 'password');
// Create user
$db->createUser('John Doe', '[email protected]', 30);
// Get user
$user = $db->getUser(1);
if ($user) {
echo "User: " . $user['name'];
}
// Get all users
$users = $db->getAllUsers(10, 0);
foreach ($users as $user) {
echo $user['name'] . "<br>";
}
} catch (Exception $e) {
error_log($e->getMessage());
echo "An error occurred. Please try again later.";
}
?>
// 3. REST API Implementation
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');
class UserAPI {
private $db;
public function __construct() {
$this->db = new Database('localhost', 'api_db', 'username', 'password');
}
public function handleRequest() {
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$pathParts = explode('/', trim($path, '/'));
try {
switch ($method) {
case 'GET':
return $this->handleGet($pathParts);
case 'POST':
return $this->handlePost($pathParts);
case 'PUT':
return $this->handlePut($pathParts);
case 'DELETE':
return $this->handleDelete($pathParts);
default:
http_response_code(405);
return ['error' => 'Method not allowed'];
}
} catch (Exception $e) {
http_response_code(500);
return ['error' => $e->getMessage()];
}
}
private function handleGet($pathParts) {
// GET /users - Get all users
if (count($pathParts) == 1 && $pathParts[0] == 'users') {
$users = $this->db->getAllUsers();
return ['data' => $users];
}
// GET /users/{id} - Get specific user
if (count($pathParts) == 2 && $pathParts[0] == 'users') {
$id = intval($pathParts[1]);
$user = $this->db->getUser($id);
if (!$user) {
http_response_code(404);
return ['error' => 'User not found'];
}
return ['data' => $user];
}
http_response_code(404);
return ['error' => 'Endpoint not found'];
}
private function handlePost($pathParts) {
// POST /users - Create new user
if (count($pathParts) == 1 && $pathParts[0] == 'users') {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['name']) || !isset($input['email'])) {
http_response_code(400);
return ['error' => 'Name and email are required'];
}
if ($this->db->createUser($input['name'], $input['email'], $input['age'] ?? null)) {
http_response_code(201);
return ['message' => 'User created successfully'];
} else {
http_response_code(500);
return ['error' => 'Failed to create user'];
}
}
http_response_code(404);
return ['error' => 'Endpoint not found'];
}
private function handlePut($pathParts) {
// PUT /users/{id} - Update user
if (count($pathParts) == 2 && $pathParts[0] == 'users') {
$id = intval($pathParts[1]);
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['name']) || !isset($input['email'])) {
http_response_code(400);
return ['error' => 'Name and email are required'];
}
if ($this->db->updateUser($id, $input['name'], $input['email'], $input['age'] ?? null)) {
return ['message' => 'User updated successfully'];
} else {
http_response_code(404);
return ['error' => 'User not found'];
}
}
http_response_code(404);
return ['error' => 'Endpoint not found'];
}
private function handleDelete($pathParts) {
// DELETE /users/{id} - Delete user
if (count($pathParts) == 2 && $pathParts[0] == 'users') {
$id = intval($pathParts[1]);
if ($this->db->deleteUser($id)) {
return ['message' => 'User deleted successfully'];
} else {
http_response_code(404);
return ['error' => 'User not found'];
}
}
http_response_code(404);
return ['error' => 'Endpoint not found'];
}
}
// Initialize and handle the request
$api = new UserAPI();
$response = $api->handleRequest();
echo json_encode($response, JSON_PRETTY_PRINT);
?>
// 4. File Upload Handling
<?php
class FileUploader {
private $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
private $maxFileSize = 5 * 1024 * 1024; // 5MB
private $uploadDir = 'uploads/';
public function __construct() {
if (!file_exists($this->uploadDir)) {
mkdir($this->uploadDir, 0777, true);
}
}
public function upload($fileKey) {
if (!isset($_FILES[$fileKey])) {
throw new Exception('No file uploaded');
}
$file = $_FILES[$fileKey];
// Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('Upload error: ' . $this->getUploadErrorMessage($file['error']));
}
// Validate file type
if (!in_array($file['type'], $this->allowedTypes)) {
throw new Exception('File type not allowed');
}
// Validate file size
if ($file['size'] > $this->maxFileSize) {
throw new Exception('File too large');
}
// Generate unique filename
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = uniqid() . '.' . $extension;
$filepath = $this->uploadDir . $filename;
// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
throw new Exception('Failed to move uploaded file');
}
return [
'filename' => $filename,
'filepath' => $filepath,
'original_name' => $file['name'],
'size' => $file['size'],
'type' => $file['type']
];
}
private function getUploadErrorMessage($error) {
switch ($error) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive in the HTML form';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:
return 'A PHP extension stopped the file upload';
default:
return 'Unknown upload error';
}
}
}
// Usage example:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
try {
$uploader = new FileUploader();
$result = $uploader->upload('file');
echo json_encode(['success' => true, 'data' => $result]);
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
}
?>
💻 现代PHP特性 php
🟡 intermediate
⭐⭐⭐⭐
PHP 8+现代特性,包括类型属性、联合类型和属性
⏱️ 35 min
🏷️ php, php8, modern php, advanced
Prerequisites:
Object-oriented PHP, Basic PHP syntax
<?php
// Modern PHP 8+ Features Examples
// 1. Typed Properties
class User {
public int $id;
public string $name;
public string $email;
private ?DateTime $createdAt = null;
public function __construct(int $id, string $name, string $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
$this->createdAt = new DateTime();
}
public function getCreatedAt(): ?DateTime {
return $this->createdAt;
}
}
$user = new User(1, 'John Doe', '[email protected]');
echo $user->name; // John Doe
// 2. Constructor Property Promotion (PHP 8.0)
class Product {
public function __construct(
private int $id,
private string $name,
private float $price,
private array $categories = []
) {}
public function getId(): int {
return $this->id;
}
public function getName(): string {
return $this->name;
}
public function getPrice(): float {
return $this->price;
}
public function getCategories(): array {
return $this->categories;
}
}
$product = new Product(1, 'Laptop', 999.99, ['Electronics', 'Computers']);
echo $product->getName(); // Laptop
// 3. Union Types (PHP 8.0)
class Logger {
public function log(string|int $message): void {
echo $this->formatMessage($message);
}
private function formatMessage(string|int $message): string {
return "Log: " . (string) $message;
}
}
$logger = new Logger();
$logger->log("Hello, World!");
$logger->log(42);
// 4. Named Arguments (PHP 8.0)
class EmailService {
public function sendEmail(
string $to,
string $subject,
string $body,
string $from = '[email protected]',
array $cc = [],
array $bcc = []
): bool {
echo "Sending email to: $to
";
echo "Subject: $subject
";
echo "Body: $body
";
echo "From: $from
";
if (!empty($cc)) echo "CC: " . implode(', ', $cc) . "
";
if (!empty($bcc)) echo "BCC: " . implode(', ', $bcc) . "
";
return true;
}
}
$email = new EmailService();
// Using named arguments
$email->sendEmail(
to: '[email protected]',
subject: 'Welcome!',
body: 'Thank you for joining our platform.',
cc: ['[email protected]']
);
// 5. Match Expressions (PHP 8.0)
class HttpStatus {
public function getMessage(int $code): string {
return match ($code) {
200 => 'OK',
201 => 'Created',
204 => 'No Content',
400 => 'Bad Request',
401 => 'Unauthorized',
403 => 'Forbidden',
404 => 'Not Found',
500 => 'Internal Server Error',
default => 'Unknown Status'
};
}
public function isSuccess(int $code): bool {
return match (true) {
$code >= 200 && $code < 300 => true,
default => false
};
}
}
$status = new HttpStatus();
echo $status->getMessage(200); // OK
echo $status->isSuccess(404) ? 'Success' : 'Error'; // Error
// 6. Nullsafe Operator (PHP 8.0)
class Address {
public function __construct(public ?string $city = null) {}
}
class User {
public function __construct(public ?Address $address = null) {}
public function getCity(): ?string {
return $this->address?->city;
}
// Before PHP 8.0 (without nullsafe operator):
public function getCityOld(): ?string {
return $this->address ? $this->address->city : null;
}
}
$user = new User();
echo $user->getCity() ?? 'Unknown City'; // Unknown City
$userWithAddress = new User(new Address('New York'));
echo $userWithAddress->getCity() ?? 'Unknown City'; // New York
// 7. Attributes (PHP 8.0)
#[Attribute]
class Route {
public function __construct(
public string $path,
public string $method = 'GET'
) {}
}
class UserController {
#[Route('/users', 'GET')]
public function index(): array {
return ['users' => []];
}
#[Route('/users/{id}', 'GET')]
public function show(int $id): array {
return ['user' => ['id' => $id]];
}
#[Route('/users', 'POST')]
public function store(): array {
return ['message' => 'User created'];
}
}
// 8. Enums (PHP 8.1)
enum UserRole: string {
case ADMIN = 'admin';
case EDITOR = 'editor';
case USER = 'user';
public function getPermissions(): array {
return match ($this) {
self::ADMIN => ['create', 'read', 'update', 'delete'],
self::EDITOR => ['create', 'read', 'update'],
self::USER => ['read'],
};
}
}
class AuthUser {
public function __construct(
private string $name,
private UserRole $role
) {}
public function can(string $permission): bool {
return in_array($permission, $this->role->getPermissions());
}
}
$admin = new AuthUser('Admin User', UserRole::ADMIN);
echo $admin->can('delete') ? 'Yes' : 'No'; // Yes
// 9. Readonly Properties (PHP 8.1)
class ProductConfig {
public function __construct(
public readonly string $name,
public readonly float $price,
public readonly array $features
) {}
public function getInfo(): array {
return [
'name' => $this->name,
'price' => $this->price,
'features' => $this->features
];
}
}
// $config = new ProductConfig('Premium Plan', 29.99, ['Feature 1', 'Feature 2']);
// $config->name = 'Cannot modify readonly property';
// 10. Fibers (PHP 8.1) - Basic Async Support
use Fiber;
class AsyncTask {
private Fiber $fiber;
public function __construct(callable $callback) {
$this->fiber = new Fiber($callback);
}
public function start(...$args): mixed {
return $this->fiber->start(...$args);
}
public function resume(mixed $value = null): mixed {
return $this->fiber->resume($value);
}
}
// Example async task
function fetchUrl(string $url): string {
echo "Starting fetch from $url
";
// Simulate async operation
Fiber::suspend('waiting...');
echo "Completed fetch from $url
";
return "Content from $url";
}
$task = new AsyncTask('fetchUrl');
$result = $task->start('https://api.example.com');
// Resume the fiber
$content = $task->resume();
echo $content;
// 11. Modern Array Functions
class ArrayHelper {
public static function filterMap(array $array, callable $filter, callable $map): array {
return array_map($map, array_filter($array, $filter));
}
public static function first(array $array, ?callable $callback = null): mixed {
if ($callback === null) {
return empty($array) ? null : $array[0];
}
foreach ($array as $value) {
if ($callback($value)) {
return $value;
}
}
return null;
}
}
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter even numbers and square them
$evenSquares = ArrayHelper::filterMap(
$numbers,
fn($n) => $n % 2 === 0,
fn($n) => $n ** 2
);
print_r($evenSquares); // [4, 16, 36, 64, 100]
// 12. Modern Error Handling with Exceptions
class ValidationException extends Exception {
private array $errors;
public function __construct(array $errors) {
$this->errors = $errors;
parent::__construct('Validation failed');
}
public function getErrors(): array {
return $this->errors;
}
}
class RequestValidator {
public function validate(array $data): void {
$errors = [];
if (empty($data['name'] ?? '')) {
$errors['name'] = 'Name is required';
}
if (!filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Valid email is required';
}
if (!empty($errors)) {
throw new ValidationException($errors);
}
}
}
try {
$validator = new RequestValidator();
$validator->validate([
'name' => '',
'email' => 'invalid-email'
]);
} catch (ValidationException $e) {
echo "Validation errors: " . implode(', ', $e->getErrors());
}