PHP 基础教程
返回首页
技术分享
2025-12-20
基本语法
PHP 标记
<?php
// PHP 代码
?>
变量定义
<?php
$name = "张三"; // 字符串
$age = 25; // 整数
$price = 99.99; // 浮点数
$is_active = true; // 布尔值
?>
函数定义
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
function calculateSum($a, $b) {
return $a + $b;
}
// 调用函数
echo greet("张三");
echo calculateSum(10, 20);
?>
数据类型
基本类型
<?php
// 字符串
$text = "Hello World";
// 整数
$number = 42;
// 浮点数
$decimal = 3.14;
// 布尔值
$flag = true;
// 数组
$fruits = array("apple", "banana", "orange");
$person = array(
"name" => "李四",
"age" => 30,
"city" => "北京"
);
// 对象
class User {
public $name;
public $age;
}
$user = new User();
$user->name = "王五";
$user->age = 25;
?>
常用函数
字符串函数
<?php
$text = "Hello World";
// 字符串长度
echo strlen($text); // 11
// 查找字符串位置
echo strpos($text, "World"); // 6
// 字符串替换
echo str_replace("World", "PHP", $text); // Hello PHP
// 大小写转换
echo strtoupper($text); // HELLO WORLD
echo strtolower($text); // hello world
// 去除空格
echo trim(" hello "); // hello
// 字符串分割
$parts = explode(" ", $text); // ["Hello", "World"]
// 字符串连接
echo $text . " - " . "PHP"; // Hello World - PHP
?>
数组函数
<?php
$fruits = ["apple", "banana", "orange"];
// 数组长度
echo count($fruits); // 3
// 添加元素
array_push($fruits, "grape");
// 删除元素
array_pop($fruits);
// 查找元素
if (in_array("apple", $fruits)) {
echo "Found apple!";
}
// 数组排序
sort($fruits);
rsort($fruits);
// 数组合并
$more_fruits = ["grape", "mango"];
$all_fruits = array_merge($fruits, $more_fruits);
?>
数学函数
<?php
// 基本数学运算
echo pi(); // 3.1415926535898
echo min(1, 3, 5, 7); // 1
echo max(1, 3, 5, 7); // 7
echo abs(-5); // 5
echo sqrt(16); // 4
echo round(3.6); // 4
echo rand(1, 100); // 随机数 1-100
?>
条件语句
if-else 语句
<?php
$score = 85;
if ($score >= 90) {
echo "优秀";
} elseif ($score >= 80) {
echo "良好";
} elseif ($score >= 60) {
echo "及格";
} else {
echo "不及格";
}
?>
switch 语句
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "星期一";
break;
case "Tuesday":
echo "星期二";
break;
default:
echo "其他";
}
?>
循环语句
for 循环
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i . " ";
}
?>
while 循环
<?php
$count = 1;
while ($count <= 5) {
echo "Count: " . $count . "<br>";
$count++;
}
?>
foreach 循环
<?php
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
echo $color . "<br>";
}
// 关联数组
$person = [
"name" => "张三",
"age" => 25,
"city" => "北京"
];
foreach ($person as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
函数进阶
参数默认值
<?php
function greet($name, $greeting = "Hello") {
return $greeting . ", " . $name . "!";
}
echo greet("张三"); // Hello, 张三!
echo greet("李四", "Hi"); // Hi, 李四!
?>
可变参数
<?php
function sum(...$numbers) {
$total = 0;
foreach ($numbers as $number) {
$total += $number;
}
return $total;
}
echo sum(1, 2, 3, 4, 5); // 15
?>
返回多个值
<?php
function getUserInfo($id) {
// 模拟数据库查询
$users = [
1 => ["name" => "张三", "age" => 25],
2 => ["name" => "李四", "age" => 30]
];
return $users[$id] ?? null;
}
$user = getUserInfo(1);
if ($user) {
echo "姓名: " . $user['name'] . ", 年龄: " . $user['age'];
}
?>
前后端交互
表单处理
<?php
// process_form.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$age = $_POST['age'] ?? '';
// 数据验证
if (empty($name) || empty($email)) {
echo "姓名和邮箱不能为空!";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "邮箱格式不正确!";
} else {
echo "提交成功!<br>";
echo "姓名: " . htmlspecialchars($name) . "<br>";
echo "邮箱: " . htmlspecialchars($email) . "<br>";
echo "年龄: " . htmlspecialchars($age) . "<br>";
}
}
?>
HTML 表单
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
</head>
<body>
<form method="POST" action="process_form.php">
<label>姓名:</label>
<input type="text" name="name" required><br><br>
<label>邮箱:</label>
<input type="email" name="email" required><br><br>
<label>年龄:</label>
<input type="number" name="age"><br><br>
<input type="submit" value="提交">
</form>
</body>
</html>
AJAX 交互
<?php
// api.php
header('Content-Type: application/json');
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$action = $_GET['action'] ?? '';
switch ($action) {
case 'get_users':
$users = [
["id" => 1, "name" => "张三", "email" => "zhangsan@example.com"],
["id" => 2, "name" => "李四", "email" => "lisi@example.com"],
["id" => 3, "name" => "王五", "email" => "wangwu@example.com"]
];
echo json_encode(["success" => true, "data" => $users]);
break;
case 'get_user':
$id = $_GET['id'] ?? 0;
$users = [
1 => ["id" => 1, "name" => "张三", "email" => "zhangsan@example.com"],
2 => ["id" => 2, "name" => "李四", "email" => "lisi@example.com"]
];
if (isset($users[$id])) {
echo json_encode(["success" => true, "data" => $users[$id]]);
} else {
echo json_encode(["success" => false, "message" => "用户不存在"]);
}
break;
default:
echo json_encode(["success" => false, "message" => "未知操作"]);
}
} elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
$data = json_decode(file_get_contents('php://input'), true);
if ($data['action'] == 'add_user') {
// 处理添加用户逻辑
echo json_encode(["success" => true, "message" => "用户添加成功"]);
}
}
?>
JavaScript AJAX 调用
// 获取用户列表
fetch('api.php?action=get_users')
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('用户列表:', data.data);
// 渲染用户列表到页面
}
})
.catch(error => console.error('错误:', error));
// 获取单个用户
fetch('api.php?action=get_user&id=1')
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('用户信息:', data.data);
}
});
// 添加用户
fetch('api.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'add_user',
name: '新用户',
email: 'newuser@example.com'
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('添加成功');
}
});
文件上传
<?php
// upload.php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["file"])) {
$file = $_FILES["file"];
$upload_dir = "uploads/";
// 创建上传目录
if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0777, true);
}
// 文件验证
$allowed_types = ["jpg", "jpeg", "png", "gif"];
$file_extension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
if (in_array($file_extension, $allowed_types)) {
if ($file["size"] < 5000000) { // 5MB限制
$new_filename = time() . "_" . basename($file["name"]);
$target_file = $upload_dir . $new_filename;
if (move_uploaded_file($file["tmp_name"], $target_file)) {
echo "文件上传成功: " . $new_filename;
} else {
echo "文件上传失败";
}
} else {
echo "文件太大,请上传小于5MB的文件";
}
} else {
echo "只允许上传图片文件";
}
}
?>
文件上传表单
<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="upload.php">
<label>选择文件:</label>
<input type="file" name="file" accept="image/*" required><br><br>
<input type="submit" value="上传">
</form>
</body>
</html>
数据库交互
MySQL 连接和查询
<?php
// 数据库配置
$host = "localhost";
$username = "root";
$password = "";
$database = "test_db";
// 创建连接
$conn = new mysqli($host, $username, $password, $database);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 设置字符集
$conn->set_charset("utf8");
// 查询数据
$sql = "SELECT id, name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . " - 姓名: " . $row["name"] . " - 邮箱: " . $row["email"] . "<br>";
}
} else {
echo "没有数据";
}
// 插入数据
$name = "新用户";
$email = "newuser@example.com";
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $email);
if ($stmt->execute()) {
echo "新记录插入成功";
} else {
echo "错误: " . $stmt->error;
}
$stmt->close();
$conn->close();
?>
会话管理
Session 使用
<?php
session_start();
// 设置 Session
$_SESSION["user_id"] = 123;
$_SESSION["username"] = "张三";
$_SESSION["login_time"] = time();
// 获取 Session
if (isset($_SESSION["username"])) {
echo "欢迎, " . $_SESSION["username"];
}
// 销毁 Session
session_unset();
session_destroy();
?>
Cookie 使用
<?php
// 设置 Cookie
setcookie("username", "张三", time() + 3600, "/"); // 1小时过期
// 获取 Cookie
if (isset($_COOKIE["username"])) {
echo "欢迎回来, " . $_COOKIE["username"];
}
// 删除 Cookie
setcookie("username", "", time() - 3600, "/");
?>
错误处理
基本错误处理
<?php
// 自定义错误处理函数
function customError($errno, $errstr) {
echo "<b>错误:</b> [$errno] $errstr<br>";
echo "脚本结束";
die();
}
// 设置错误处理函数
set_error_handler("customError");
// 触发错误
echo($test); // 未定义变量
// 异常处理
try {
$result = 10 / 0;
} catch (Exception $e) {
echo "捕获异常: " . $e->getMessage();
}
// 自定义异常
class CustomException extends Exception {
public function errorMessage() {
return "错误行 " . $this->getLine() . " 在 " . $this->getFile()
. ": <b>" . $this->getMessage() . "</b> 不是一个有效的 E-Mail 地址";
}
}
try {
$email = "someone@example...com";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new CustomException($email);
}
} catch (CustomException $e) {
echo $e->errorMessage();
}
?>
Web安全
输入验证和过滤
<?php
// 获取并过滤输入
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$age = filter_input(INPUT_POST, 'age', FILTER_VALIDATE_INT);
// XSS 防护
function escape($string) {
return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
}
// SQL 注入防护 (使用预处理语句)
$stmt = $conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
// CSRF 防护
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die('CSRF 验证失败');
}
// 处理表单提交
}
// 生成 CSRF Token
function generateCSRFToken() {
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
?>