收集、管理和分享有用的代码片段,提高开发效率
转换日期到不同时区
<?php
function convertTimezone($date, $fromZone, $toZone) {
$date = new DateTime($date, new DateTimeZone($fromZone));
$date->setTimeZone(new DateTimeZone($toZone));
return $date->format('Y-m-d H:i:s');
}
实现二叉搜索树
<?php
class BSTree {
private $root = null;
public function insert($value) {
$newNode = new BSNode($value);
if ($this->root === null) {
$this->root = $newNode;
return;
}
$this->_insertNode($this->root, $newNode);
}
private function _insertNode(&$parent, &$node) {
if ($parent === null) {
$parent = $node;
} elseif ($node->value < $parent->value) {
if ($parent->left === null) {
$parent->left = $node;
} else {
$this->_insertNode($parent->left, $node);
}
} else {
if ($parent->right === null) {
$parent->right = $node;
} else {
$this->_insertNode($parent->right, $node);
}
}
}
}
class BSNode {
public $value;
public $left = null;
public $right = null;
public function __construct($value) {
$this->value = $value;
}
}
使用PHP实现安全的用户登录验证功能
// 用户登录验证
function loginUser($username, $password) {
$user = getUserByUsername($username);
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
return true;
}
return false;
}
使用PDO连接MySQL数据库的示例代码
<?php
$host = "127.0.0.1";
$dbname = "my_database";
$username = "db_user";
$password = "secure_password";
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
获取并格式化当前日期和时间
function getCurrentDateTime() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hours = String(now.getHours()).padStart(2, "0");
const minutes = String(now.getMinutes()).padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}`;
}
console.log(getCurrentDateTime());
高效管理您的代码片段,提高开发效率
通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能
支持多种编程语言的语法高亮,使代码更加清晰易读
随时随地访问您的代码片段库,支持桌面和移动设备
浏览最受欢迎的代码分类