在config中创建config.php,用来保存相应的配置
<?php
// 配置常量
define('ENV_DEV', 'dev');
define('ENV_PRO', 'pro');
// 当前环境(开发环境或生产环境)
$env = ENV_DEV; // 修改为ENV_DEV以切换到开发环境
// OSS配置 这里是阿里云的配置
$oss = [
'accessKeyId' => '',
'accessKeySecret' => '',
'endpoint' => 'oss-cn-shanghai.aliyuncs.com',
'bucket' => ''
];
// MySQL配置
$mysql_config = [
ENV_DEV => ['host' => 'localhost', 'user' => 'root', 'port' => 3306, 'password' => 'asd123', 'database' => 'mychat'],
ENV_PRO => ['host' => 'localhost', 'user' => 'chat', 'port' => 3306, 'password' => 'asd123', 'database' => 'chat']
];
// Redis配置
$redis_config = [
ENV_DEV => ['host' => 'localhost', 'port' => 6379, 'auth' => '123456', 'db' => 2],
ENV_PRO => ['host' => 'localhost', 'port' => 6379, 'auth' => '123456', 'db' => 2]
];
// WebSocket配置 放上自己的配置
$port = 3300;//端口号
$wss = $env === ENV_DEV ? "websocket://127.0.0.1:$port" : "websocket://0.0.0.0:$port";
$client_ws = $env === ENV_DEV ? "ws://127.0.0.1:$port" : "wss://xxx.zzz.cn/wss";
// 获取数据库配置
function getDbConfig() {
global $env, $mysql_config; // 使用全局变量
$dbConfig = $mysql_config[$env];
try {
$pdo = new PDO(
"mysql:host={
$dbConfig['host']};port={
$dbConfig['port']};dbname={
$dbConfig['database']}",
$dbConfig['user'],
$dbConfig['password']
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
echo "数据库连接失败: " . $e->getMessage();
return null;
}
}
// 获取Redis配置(不再需要传递参数)
function getRedisConfig() {
global $env, $redis_config; // 使用全局变量
$redisConfig = $redis_config[$env];
$redis = new Redis();
try {
$redis->connect($redisConfig['host'], $redisConfig['port']);
$redis->auth($redisConfig['auth']);
$redis->select($redisConfig['db']);
return $redis;
} catch (Exception $e) {
echo "Redis连接失败: " . $e->getMessage();
return null;
}
}
要src 中写入几个文件,用来获取历史聊天,好友例表 ,撤回记录等操作。
<?php
// 引入配置文件
require_once __DIR__ . '/../config/config.php';
// 获取 GET 参数并验证
$from_user_id = isset($_GET['from_user_id']) ? intval($_GET['from_user_id']) : 0;
$to_user_id = isset($_GET['to_user_id']) ? intval($_GET['to_user_id']) : 0;
$limit = isset($_GET['limit']) && is_numeric($_GET['limit']) ? intval($_GET['limit']) : 20;
// 验证参数
//if ($from_user_id <= 0 || $to_user_id <= 0) {
// exit(json_encode(['error' => '参数错误: from_user_id 和 to_user_id 是必需的且必须为有效数字']));
//}
try {
$pdo = getDbConfig();