一、PHP基础语法与常用操作
1.1 变量与数据类型操作
变量检查与类型转换
<?php// 1. 变量存在性检查if (isset($variable)) { echo "变量已设置";}// 2. 空值检查(推荐)if (empty($variable)) { echo "变量为空";}// 3. 类型检查与转换$number = "123";$int_value = (int)$number; // 强制转换为整数$float_value = (float)$number; // 强制转换为浮点数$string_value = (string)$int_value; // 转换为字符串$bool_value = (bool)$number; // 转换为布尔值// 4. 获取变量类型echo gettype($variable);数据类型判断函数
// 常用类型判断函数is_int($var); // 是否是整数is_float($var); // 是否是浮点数is_string($var); // 是否是字符串is_array($var); // 是否是数组is_object($var); // 是否是对像is_null($var); // 是否是nullis_bool($var); // 是否是布尔值is_numeric($var); // 是否是数字或数字字符串1.2 字符串处理大全
基本字符串操作
<?php// 1. 字符串长度$length = strlen("Hello World");// 2. 字符串查找$position = strpos("Hello World", "World"); // 返回位置或false// 3. 字符串替换$new_string = str_replace("World", "PHP", "Hello World");// 4. 大小写转换$lower = strtolower("HELLO");$upper = strtoupper("hello");// 5. 去除空格$trimmed = trim(" hello "); // 去除两端空格$ltrimmed = ltrim(" hello "); // 去除左侧空格$rtrimmed = rtrim(" hello "); // 去除右侧空格// 6. 字符串截取$substring = substr("Hello World", 0, 5); // "Hello"// 7. 字符串分割$parts = explode(" ", "Hello World"); // ["Hello", "World"]$combined = implode("-", $parts); // "Hello-World"// 8. HTML特殊字符转义$safe_html = htmlspecialchars("<script>alert('xss')</script>");正则表达式处理
// 1. 匹配检查if (preg_match("/\d+/", $string)) { echo "包含数字";}// 2. 提取匹配内容preg_match("/\d+/", "价格是100元", $matches);// $matches[0] 包含 "100"// 3. 全局匹配preg_match_all("/\d+/", "价格是100元,数量是5个", $matches);// $matches[0] 包含 ["100", "5"]// 4. 正则替换$result = preg_replace("/\d+/", "***", "价格100元"); // "价格***元"二、数组操作完整指南
2.1 数组创建与基本操作
表1:PHP数组类型对比
类型 | 创建方式 | 特点 | 使用场景 |
索引数组 | $arr = [1, 2, 3] | 数字键名 | 有序数据集合 |
关联数组 | $arr = ['name'=>'John'] | 字符串键名 | 键值对数据 |
多维数组 | $arr = [['id'=>1]] | 嵌套数组 | 复杂数据结构 |
<?php// 1. 数组创建$indexed_array = [1, 2, 3, 4, 5];$assoc_array = [ 'name' => '张三', 'age' => 25, 'city' => '北京'];// 2. 数组遍历foreach ($assoc_array as $key => $value) { echo "$key: $value\n";}// 3. 添加元素$array[] = '新元素'; // 末尾添加array_push($array, '元素1', '元素2'); // 批量添加$assoc_array['email'] = 'test@example.com'; // 关联数组添加// 4. 删除元素unset($array[0]); // 删除指定索引array_pop($array); // 删除最后一个array_shift($array); // 删除第一个2.2 数组高级处理函数
数组过滤与转换
// 1. 数组过滤$numbers = [1, 2, 3, 4, 5, 6];$even_numbers = array_filter($numbers, function($n) { return $n % 2 == 0;}); // [2, 4, 6]// 2. 数组映射(转换)$squared = array_map(function($n) { return $n * $n;}, $numbers); // [1, 4, 9, 16, 25, 36]// 3. 数组归并$sum = array_reduce($numbers, function($carry, $item) { return $carry + $item;}, 0); // 21// 4. 数组排序sort($numbers); // 值升序rsort($numbers); // 值降序asort($assoc_array); // 值升序保持键名ksort($assoc_array); // 键名升序usort($array, function($a, $b) { // 自定义排序 return $a - $b;});数组实用工具函数
// 1. 数组合并$array1 = [1, 2];$array2 = [3, 4];$merged = array_merge($array1, $array2);// 2. 数组切片$slice = array_slice($numbers, 1, 3); // 从索引1开始取3个// 3. 数组搜索$key = array_search(3, $numbers); // 返回键名$in_array = in_array(3, $numbers); // 返回布尔值// 4. 数组去重$unique = array_unique([1, 2, 2, 3]); // [1, 2, 3]// 5. 数组键值操作$keys = array_keys($assoc_array); // 获取所有键$values = array_values($assoc_array); // 获取所有值三、文件操作与目录处理
3.1 文件读写操作
<?php// 1. 文件读取(推荐方式)$content = file_get_contents('file.txt');// 2. 文件写入file_put_contents('file.txt', '新内容', FILE_APPEND | LOCK_EX);// 3. 逐行读取文件$lines = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);// 4. 文件存在性检查if (file_exists('file.txt')) { echo "文件存在";}// 5. 文件信息获取$file_size = filesize('file.txt');$mod_time = filemtime('file.txt');$is_readable = is_readable('file.txt');$is_writable = is_writable('file.txt');3.2 目录操作与文件遍历
// 1. 创建目录if (!is_dir('new_folder')) { mkdir('new_folder', 0755, true); // 递归创建}// 2. 遍历目录$files = scandir('path/to/directory');foreach ($files as $file) { if ($file != '.' && $file != '..') { echo $file . "\n"; }}// 3. 递归遍历目录function scanDirectory($dir) { $result = []; $files = scandir($dir); foreach ($files as $file) { if ($file == '.' || $file == '..') continue; $path = $dir . DIRECTORY_SEPARATOR . $file; if (is_dir($path)) { $result = array_merge($result, scanDirectory($path)); } else { $result[] = $path; } } return $result;}// 4. 文件删除与重命名unlink('file.txt'); // 删除文件rename('old.txt', 'new.txt'); // 重命名copy('source.txt', 'destination.txt'); // 复制文件四、数据库操作(MySQLi + PDO)
4.1 MySQLi 数据库操作
<?php// 1. 数据库连接$mysqli = new mysqli('localhost', 'username', 'password', 'database');// 检查连接if ($mysqli->connect_error) { die('连接失败: ' . $mysqli->connect_error);}// 2. 查询操作$result = $mysqli->query("SELECT * FROM users WHERe age > 18");// 3. 获取结果$users = [];while ($row = $result->fetch_assoc()) { $users[] = $row;}// 4. 预处理语句(防SQL注入)$stmt = $mysqli->prepare("INSERT INTO users (name, email) VALUES (?, ?)");$stmt->bind_param("ss", $name, $email); // s=字符串, i=整数, d=浮点数$name = "John";$email = "john@example.com";$stmt->execute();// 5. 关闭连接$stmt->close();$mysqli->close();4.2 PDO 数据库操作(推荐)
<?phptry { // 1. PDO连接 $pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'username', 'password'); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 2. 查询操作 $stmt = $pdo->query("SELECt * FROM users"); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); // 3. 预处理语句 $stmt = $pdo->prepare("SELECt * FROM users WHERe id = :id AND status = :status"); $stmt->execute([ ':id' => 1, ':status' => 'active' ]); $user = $stmt->fetch(PDO::FETCH_ASSOC); // 4. 插入操作 $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->execute(['John Doe', 'john@example.com']); $last_id = $pdo->lastInsertId(); // 5. 事务处理 $pdo->beginTransaction(); try { $pdo->exec("UPDATe accounts SET balance = balance - 100 WHERe id = 1"); $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERe id = 2"); $pdo->commit(); } catch (Exception $e) { $pdo->rollBack(); throw $e; }} catch (PDOException $e) { die("数据库错误: " . $e->getMessage());}五、表单处理与数据验证
5.1 安全的表单处理
<?php// 1. 检查表单提交if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 2. 数据清理和验证 $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT); // 3. 验证规则 $errors = []; if (empty($name)) { $errors[] = "姓名不能为空"; } if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "邮箱格式不正确"; } if ($age < 1 || $age > 150) { $errors[] = "年龄必须在1-150之间"; } // 4. 处理验证结果 if (empty($errors)) { // 保存到数据库或进行其他操作 echo "表单提交成功!"; } else { // 显示错误信息 foreach ($errors as $error) { echo "<p style='color: red;'>$error</p>"; } }}?><!-- HTML表单 --><form method="post"> <input type="text" name="name" required> <input type="email" name="email" required> <input type="number" name="age" required> <button type="submit">提交</button></form>5.2 文件上传处理
<?phpif ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $upload_dir = 'uploads/'; $max_size = 2 * 1024 * 1024; // 2MB $allowed_types = ['image/jpeg', 'image/png', 'application/pdf']; $file = $_FILES['file']; // 验证文件 if ($file['error'] !== UPLOAD_ERR_OK) { die("文件上传错误: " . $file['error']); } if ($file['size'] > $max_size) { die("文件大小超过限制"); } if (!in_array($file['type'], $allowed_types)) { die("不支持的文件类型"); } // 生成安全文件名 $extension = pathinfo($file['name'], PATHINFO_EXTENSION); $filename = uniqid() . '.' . $extension; $destination = $upload_dir . $filename; // 移动文件 if (move_uploaded_file($file['tmp_name'], $destination)) { echo "文件上传成功: " . $filename; } else { echo "文件上传失败"; }}?>六、会话管理与cookie操作
6.1 Session会话管理
<?php// 1. 开启会话session_start();// 2. 设置会话变量$_SESSION['user_id'] = 123;$_SESSION['username'] = 'john_doe';$_SESSION['login_time'] = time();// 3. 读取会话变量if (isset($_SESSION['user_id'])) { echo "用户ID: " . $_SESSION['user_id'];}// 4. 更新会话变量$_SESSION['last_activity'] = time();// 5. 删除会话变量unset($_SESSION['username']);// 6. 销毁整个会话session_destroy();// 7. 会话安全设置ini_set('session.cookie_httponly', 1);ini_set('session.use_strict_mode', 1);ini_set('session.cookie_secure', 1); // 仅HTTPS6.2 cookie操作
// 1. 设置cookie(有效期7天)setcookie('username', 'john_doe', time() + (7 * 24 * 60 * 60), '/', '', true, true);// 2. 读取cookieif (isset($_cookie['username'])) { $username = $_cookie['username'];}// 3. 删除cookiesetcookie('username', '', time() - 3600, '/');// 4. 安全的cookie操作类class cookieManager { public static function set($name, $value, $expiry_days = 30) { $expiry = time() + ($expiry_days * 24 * 60 * 60); setcookie($name, $value, $expiry, '/', '', true, true); } public static function get($name, $default = null) { return $_cookie[$name] ?? $default; } public static function delete($name) { setcookie($name, '', time() - 3600, '/'); }}// 使用示例cookieManager::set('user_preference', 'dark_mode', 365);$preference = cookieManager::get('user_preference', 'light_mode');七、错误处理与调试技巧
7.1 错误处理机制
<?php// 1. 自定义错误处理函数set_error_handler(function($errno, $errstr, $errfile, $errline) { error_log("错误: $errstr 在 $errfile 第 $errline 行"); if (ini_get('display_errors')) { echo "错误: $errstr"; } return true; // 阻止PHP内置错误处理});// 2. 异常处理try { $result = 1 / 0; // 触发警告} catch (Exception $e) { echo "捕获异常: " . $e->getMessage();} finally { echo "最终执行块";}// 3. 自定义异常类class CustomException extends Exception { public function __construct($message, $code = 0, Exception $previous = null) { parent::__construct($message, $code, $previous); } public function __toString() { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; }}// 4. 抛出异常if ($value < 0) { throw new CustomException("数值不能为负数");}7.2 调试与日志记录
// 1. 简单调试函数function debug($data, $exit = true) { echo '<pre>'; print_r($data); echo '</pre>'; if ($exit) exit;}// 2. 文件日志记录function log_message($message, $level = 'INFO') { $timestamp = date('Y-m-d H:i:s'); $log_entry = "[$timestamp] [$level] $message" . PHP_EOL; file_put_contents('app.log', $log_entry, FILE_APPEND | LOCK_EX);}// 3. 性能调试function benchmark($callback, $iterations = 1000) { $start = microtime(true); for ($i = 0; $i < $iterations; $i++) { $callback(); } $end = microtime(true); return $end - $start;}// 使用示例$time = benchmark(function() { // 测试的代码}, 10000);echo "执行时间: " . $time . " 秒";八、实用工具函数集合
8.1 常用工具函数
<?php// 1. 生成随机字符串function generate_random_string($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $random_string = ''; for ($i = 0; $i < $length; $i++) { $random_string .= $characters[rand(0, strlen($characters) - 1)]; } return $random_string;}// 2. 安全的JSON编码/解码function safe_json_encode($data) { return json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);}function safe_json_decode($json, $assoc = true) { $result = json_decode($json, $assoc); if (json_last_error() !== JSON_ERROR_NONE) { throw new Exception('JSON解码错误: ' . json_last_error_msg()); } return $result;}// 3. URL安全base64编码function base64_url_encode($data) { return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');}function base64_url_decode($data) { return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));}// 4. 密码哈希验证function hash_password($password) { return password_hash($password, PASSWORD_DEFAULT);}function verify_password($password, $hash) { return password_verify($password, $hash);}8.2 日期时间处理
// 1. 日期格式化function format_date($timestamp, $format = 'Y-m-d H:i:s') { return date($format, $timestamp);}// 2. 相对时间显示function relative_time($timestamp) { $diff = time() - $timestamp; if ($diff < 60) return '刚刚'; if ($diff < 3600) return floor($diff / 60) . '分钟前'; if ($diff < 86400) return floor($diff / 3600) . '小时前'; if ($diff < 2592000) return floor($diff / 86400) . '天前'; return date('Y-m-d', $timestamp);}// 3. 时区处理function set_timezone($timezone = 'Asia/Shanghai') { date_default_timezone_set($timezone);}// 4. 日期验证function validate_date($date, $format = 'Y-m-d') { $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) === $date;}总结:PHP开发最佳实践
表2:PHP代码质量检查清单
类别 | 检查项 | 推荐做法 |
安全性 | SQL注入防护 | 使用预处理语句 |
XSS防护 | 输出时使用htmlspecialchars | |
CSRF防护 | 使用Token验证 | |
性能 | 数据库查询 | 使用索引,避免N+1查询 |
内存使用 | 及时unset大变量 | |
文件操作 | 使用缓存减少IO | |
可维护性 | 代码结构 | 使用MVC模式 |
错误处理 | 统一的异常处理机制 | |
配置管理 | 使用配置文件 |
使用建议
- 版本兼容性:确保目标环境支持使用的PHP特性
- 错误报告:开发环境开启错误显示,生产环境关闭
- 安全配置:定期更新PHP版本,配置安全的php.ini
- 代码规范:遵循PSR标准,保持代码一致性
这些代码片段覆盖了PHP开发的常见场景,建议根据实际需求选择使用,并理解其原理以便灵活调整。
