php 实现 功能
PHP 是一种广泛使用的服务器端脚本语言,适用于实现各种功能。以下是几种常见的 PHP 功能实现方法:
表单处理
创建 HTML 表单并处理提交的数据:
<form method="post" action="process.php">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
在 process.php 中处理数据:
$username = $_POST['username'];
echo "Hello, " . htmlspecialchars($username);
数据库连接与操作
使用 MySQLi 连接数据库并查询数据:
$conn = new mysqli("localhost", "username", "password", "database");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"];
}
$conn->close();
文件上传
处理文件上传功能:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
会话管理
使用会话跟踪用户登录状态:
session_start();
$_SESSION["user"] = "username";
if (isset($_SESSION["user"])) {
echo "Welcome " . $_SESSION["user"];
}
session_destroy();
API 调用
使用 cURL 调用外部 API:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
print_r($data);
发送电子邮件
使用 PHP 的 mail 函数发送邮件:
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}
生成 PDF
使用 FPDF 库生成 PDF 文件:
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
数据验证
验证用户输入的数据:
$email = "test@example.com";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";
}
图像处理
使用 GD 库处理图像:
$image = imagecreatefromjpeg("photo.jpg");
$text_color = imagecolorallocate($image, 255, 255, 255);
imagestring($image, 5, 10, 10, "Sample Text", $text_color);
imagejpeg($image, "output.jpg");
imagedestroy($image);
定时任务
使用 cron 执行 PHP 脚本:
* * * * * /usr/bin/php /path/to/script.php
这些示例展示了 PHP 在不同场景下的应用,可以根据具体需求选择适当的方法进行功能实现。







