4 php7.4中开发一个websocket 聊天相关配置调用

在config中创建config.php,用来保存相应的配置
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 复制代码
<?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();
    $last_create_at = isset($_GET['last_create_at']) ? $_GET['last_create_at'] : null;
    $last_id = isset($_GET['last_id']) ? intval($_GET['last_id']) : null;

    $sql = "
    SELECT *
    FROM chat
    WHERE 
        (
            (from_userid = :from_user_id AND to_user_id = :to_user_id)
            OR 
            (from_userid = :to_user_id AND to_user_id = :from_user_id)
        )
        " . ($last_create_at ? "AND (create_at < :last_create_at OR (create_at = :last_create_at AND id < :last_id))" : "") . "
    ORDER BY create_at DESC, id DESC
    LIMIT :limit
    ";

    $stmt = $pdo->prepare($sql);

    $stmt->bindParam(':from_user_id', $from_user_id, PDO::PARAM_INT);
    $stmt->bindParam(':to_user_id', $to_user_id, PDO::PARAM_INT);

    if ($last_create_at) {
        $stmt->bindParam(':last_create_at', $last_create_at, PDO::PARAM_STR);
        $stmt->bindParam(':last_id', $last_id, PDO::PARAM_INT);
    }
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $chatHistory = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // 不需要反转顺序,因为前端已经处理
    echo json_encode($chatHistory);
} catch (Exception $e) {
    echo json_encode(['error' => '查询失败: ' . $e->getMessage()]);
}
?>

<?php
require_once __DIR__ . '/../config/config.php';

$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;
$search = isset($_GET['search']) ? $_GET['search'] : '';

if ($user_id <= 0) {
    echo json_encode(['status' => 'error', 'message' => '无效的用户ID']);
    exit;
}

try {
    $pdo = getDbConfig();
    // 获取分页参数
    $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
    $limit = isset($_GET['limit']) ? intval($_GET['limit']) : 20;
    $offset = ($page - 1) * $limit;

    // 获取总记录数
    $searchQuery = $search ? " AND friend_name LIKE :search" : "";
    $countStmt = $pdo->prepare("
        SELECT COUNT(*) as total
        FROM friend_list
        WHERE user_id = :user_id $searchQuery
    ");
    $countStmt->bindParam(':user_id', $user_id);
    $countStmt->execute();
    $totalCount = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];

    // 计算总页数
    $totalPages = ceil($totalCount / $limit);

    $stmt = $pdo->prepare("
        SELECT friend_id, friend_name, friend_header
        FROM friend_list
        WHERE user_id = :user_id $searchQuery
        LIMIT :limit OFFSET :offset
    ");
    $stmt->bindParam(':user_id', $user_id);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $friends = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['status' => 'success', 'data' => $friends]);
} catch (PDOException $e) {
    echo json_encode(['status' => 'error', 'message' => '数据库错误: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => '未知错误: ' . $e->getMessage()]);
} finally {
    if ($pdo) {
        $pdo = null;
    }
}



<?php

// 引入配置文件
require_once __DIR__ . '/../config/config.php';
// Get parameters from GET request
$from_user_id = $_GET['from_user_id'] ?? null;
$to_user_id = $_GET['to_user_id'] ?? null;
$user_name = $_GET['user_name'] ?? null;
$to_user_name = $_GET['to_user_name'] ?? null;
$userAvatar = $_GET['Avatar'] ?? $_GET['userAvatar'] ?? null; // Check both 'Avatar' and 'userAvatar'
$to_user_avatar = $_GET['to_user_avatar'] ?? null;

// Validate input
if (!$from_user_id || !$to_user_id || !$user_name || !$to_user_name || !$userAvatar || !$to_user_avatar) {
    echo json_encode(['status' => 'error', 'message' => '参数错误']);
    exit;
}

try {
    // Close the database connection after all operations are complete

    // Start transaction
    $db = getDbConfig();
    $db->beginTransaction();

    // Check if already friends
    $stmt = $db->prepare("SELECT id FROM friend_list WHERE user_id = ? AND friend_id = ?");
    $stmt->execute([$from_user_id, $to_user_id]);
    $result = $stmt->fetchAll();

    if (count($result) > 0) {
        echo json_encode(['status' => 'info', 'message' => '已是好友']);
        $db->rollBack();
    } else {
        // Add friend (from_user -> to_user)
        $stmt = $db->prepare("INSERT INTO friend_list (user_id, friend_id, friend_name, friend_header, create_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$from_user_id, $to_user_id, $to_user_name, $to_user_avatar]);

        // Add friend (to_user -> from_user)
        $stmt = $db->prepare("INSERT INTO friend_list (user_id, friend_id, friend_name, friend_header, create_at) VALUES (?, ?, ?, ?, NOW())");
        $stmt->execute([$to_user_id, $from_user_id, $user_name, $userAvatar]);

        // Commit transaction
        $db->commit();

        echo json_encode(['status' => 'success', 'message' => '好友增加成功']);
    }

   
} catch (Exception $e) {
    // Rollback transaction on error
    $db->rollback();
    echo json_encode(['status' => 'error', 'message' => 'An error occurred: ' . $e->getMessage()]);
} finally {
    // Close the database connection after all operations are complete
    if (isset($db)) {
        $db = null;
    }
}

// ..


<?php
require_once __DIR__ . '/../config/config.php';
$pdo = getDbConfig();
// 检查是否是POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取POST数据中的uniqueId
    $uniqueId = $_POST['uniqueId'] ?? null;
    // 检查uniqueId是否为空
    if (empty($uniqueId)) {
        echo json_encode(['status' => 'error', 'message' => 'uniqueId不能为空']);
        exit;
    }
    try {
        // 更新withdraw字段的SQL语句
        $sql = "UPDATE chat SET withdraw = 1 WHERE uniqueId = :uniqueId";
        // 预处理SQL语句并执行
        $stmt = $pdo->prepare($sql);
        $stmt->execute([':uniqueId' => $uniqueId]);
        echo json_encode(['status' => 'success', 'message' => '消息撤回成功']);
    } catch (PDOException $e) {
        echo json_encode(['status' => 'error', 'message' => '消息撤回失败']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => '无效的请求方法']);
}


?>

<?php
require_once  __DIR__ . '/../config/config.php';


$pdo=getDbConfig();
// 检查是否是POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取POST数据中的uniqueId
    $uniqueId = $_POST['uniqueId'] ?? null;

    // 检查uniqueId是否为空
    if ($uniqueId) {
        try {
            // 更新withdraw字段为false的SQL语句
            $sql = "SELECT * FROM chat WHERE uniqueId = :uniqueId";
            // 预处理SQL语句
            $stmt = $pdo->prepare($sql);
            // 绑定参数
            $stmt->bindParam(':uniqueId', $uniqueId, PDO::PARAM_STR);
            // 执行SQL语句
            $stmt->execute();
            // 获取查询结果
            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode ($result);
        } catch (PDOException $e) {
            echo json_encode(['status' => 'error', 'message' => '消息撤回失败']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'id不能为空']);
    }
}

<?php
require_once __DIR__ . '/../config/config.php';
$pdo = getDbConfig();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取POST数据
    $postData = [
        'from_userid' => $_POST['from_userid'] ?? null,
        'to_user_id' => $_POST['to_user_id'] ?? null,
        'from_companyId' => $_POST['from_companyId'] ?? null,
        'to_companyId' => $_POST['to_companyId'] ?? null,
        'from_company_name' => $_POST['from_company_name'] ?? null,
        'to_company_name' => $_POST['to_company_name'] ?? null,
        'from_role' => $_POST['from_role'] ?? null,
        'to_role' => $_POST['to_role'] ?? null,
        'filetype' => $_POST['filetype'] ?? null,
        'text' => $_POST['text'] ?? null,
        'from_user_avatar' => $_POST['from_user_avatar'] ?? null,
        'to_user_avatar' => $_POST['to_user_avatar'] ?? null,
        'from_company_avatar' => $_POST['from_company_avatar'] ?? null,
        'to_company_avatar' => $_POST['to_company_avatar'] ?? null,
        'uniqueId' => $_POST['uniqueId'] ?? null,
        'from_name' => $_POST['user_name'] ?? null,
        'to_name' => $_POST['to_name'] ?? null
    ];

    // 检查必填字段
    if (!$postData['from_userid'] || !$postData['to_user_id']) {
        echo json_encode(['status' => 'error', 'message' => 'from_userid 和 to_user_id 是必需的']);
        exit;
    }
var_dump($postData);
    // 准备SQL语句
    $sql = "
        INSERT INTO chat (
            from_userid, to_user_id, from_companyId, to_companyId, from_company_name, to_company_name, 
            from_role, to_role, type, text, from_user_avatar, to_user_avatar, from_company_avatar, 
            to_company_avatar, uniqueId,from_name,to_name
        ) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ";

    try {
        // 开始事务
        $pdo->beginTransaction();
        
        // 预处理SQL
        $stmt = $pdo->prepare($sql);
        
        // 执行SQL并批量绑定参数
        $stmt->execute([
            $postData['from_userid'],
            $postData['to_user_id'],
            $postData['from_companyId'],
            $postData['to_companyId'],
            $postData['from_company_name'],
            $postData['to_company_name'],
            $postData['from_role'],
            $postData['to_role'],
            $postData['filetype'],
            $postData['text'],
            $postData['from_user_avatar'],
            $postData['to_user_avatar'],
            $postData['from_company_avatar'],
            $postData['to_company_avatar'],
            $postData['uniqueId'],
            $postData['from_name'],
            $postData['to_name']
        ]);

        // 提交事务
        $pdo->commit();

        $lastInsertId = $pdo->lastInsertId();
        echo json_encode(['status' => 'success', 'message' => '聊天记录已成功插入', 'id' => $lastInsertId]);

    } catch (PDOException $e) {
        // 回滚事务
        $pdo->rollBack();
        echo json_encode(['status' => 'error', 'message' => '插入聊天记录失败: ' . $e->getMessage()]);
    }
} else {
//    echo json_encode(['status' => 'error', 'message' => '无效的请求方法']);
}
<?php
require __DIR__ . '/../vendor/autoload.php';
global $oss;
use OSS\OssClient;
use OSS\Core\OssException;

$uploadDir = 'upload/';


// 确保上传目录存在
if (!file_exists($uploadDir)) {
    if (!mkdir($uploadDir, 0777, true) && !is_dir($uploadDir)) {
        throw new \RuntimeException(sprintf('Directory "%s" was not created', $uploadDir));
    }
}

// 检查是否有文件上传
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];

    // 生成唯一的文件名
    $fileName = uniqid('', true) . '_' . $file['name'];
    $filePath = $uploadDir . $fileName;

    // 从config.php引入配置信息
    $config = require __DIR__ . '/../config/config.php';

    $accessKeyId = $oss['accessKeyId'];
    $accessKeySecret = $oss['accessKeySecret'];
    $endpoint = $oss['endpoint'];
    $bucket = $oss['bucket'];


    // 尝试移动上传的文件
    if (move_uploaded_file($file['tmp_name'], $filePath)) {

        $object = 'update' . '/' . $fileName;


        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

        $ossClient->setUseSSL(false);

        $data = $ossClient->uploadFile($bucket, $object, $filePath);
        $ossUrl = "https://{$bucket}.{$endpoint}/{$object}";

        // 文件上传成功
        echo json_encode([
            'status' => 'success',
            'message' => '文件上传成功',
            'filePath' => $ossUrl
        ]);
    } else {
        // 文件上传失败
        echo json_encode([
            'status' => 'error',
            'message' => '文件上传失败'
        ]);
    }
} else {
    // 没有文件被上传
    echo json_encode([
        'status' => 'error',
        'message' => '没有文件被上传'
    ]);
}
?>
相关推荐
图王大胜37 分钟前
Android build子系统(01)Ninja构建系统解读
android·gn·ninja·编译子系统·kati·soong
quweiie1 小时前
paypal支付v2.0(php)支付代码
android·开发语言·php
汪子熙1 小时前
什么是 HTTP 请求的 X-Forwarded-Proto 字段
网络·网络协议·http
服装学院的IT男3 小时前
【Android 源码分析】Activity短暂的一生 -- 目录篇 (持续更新)
android
青-叶3 小时前
android 系统默认apn数据库
android·数据库
Java程序之猿4 小时前
Thingsboard 网关实战 modbus通信 rpc下发控制指令
网络·网络协议·rpc
星月黎明4 小时前
Android Webview和ScrollView冲突和WebView使用总结
android
浩水浮生4 小时前
redis 的发布订阅解决分布式下的websocket session 共享问题
redis·分布式·websocket
年薪丰厚8 小时前
Linux中的tr命令详解
android·linux·运维
无尽的大道8 小时前
深入剖析 Android Lifecycle:构建高效稳定的应用
android·java