代码片段仓库

收集、管理和分享有用的代码片段,提高开发效率

代码片段

JSON响应 PHP

发送JSON格式的HTTP响应

function jsonResponse($data, $statusCode = 200) {
  header('Content-Type: application/json');
  http_response_code($statusCode);
  echo json_encode($data);
  exit;
}
生成GUID PHP

生成全局唯一标识符

function generateGUID() {
  if (function_exists('com_create_guid')) {
    return trim(com_create_guid(), '{}');
  }
  return sprintf(
    '%x%x-%x-%x-%x%%x%%x',
    mt_rand(0, 0xffff), mt_rand(0, 0xffff),
    mt_rand(0, 0xffff), mt_rand(0x4000, 0xbfff),
    mt_rand(0x8000, 0xffff), mt_rand(0, 0xffff),
    mt_rand(0, 0xffff), mt_rand(0, 0xffff)
  );
}
PHP验证码生成 PHP

生成6位随机字母数字验证码

function generateVerificationCode($len = 6) {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $code = '';
    $charsLength = strlen($chars) - 1;
    for ($i = 0; $i < $len; $i++) {
        $code .= $chars[rand(0, $charsLength)];
    }
    return $code;
}
Python文件MD5 Python

计算文件的MD5哈希值

import hashlib

def calc_file_md5(filepath):
    hash_md5 = hashlib.md5()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b'' ):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()
Java日期格式化 Java

SimpleDateFormat使用示例

public class DateFormatterExample {
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = formatter.format(date);
        System.out.println("Current Date: " + strDate);
    }
}
C++文件操作 C++

读写文本文件内容

#include <fstream>
#include <iostream>

using namespace std;
int main() {
    // Write to file
    ofstream outFile("output.txt");
    if (outFile.is_open()) {
        outFile << "Hello, World!" << endl;
        outFile.close();
    }
    
    // Read from file
    ifstream inFile("output.txt");
    string line;
    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    }
    return 0;
}

为什么选择CodeSnippets?

高效管理您的代码片段,提高开发效率

智能搜索

通过关键字、语言或分类快速查找代码片段,支持模糊搜索和过滤功能

语法高亮

支持多种编程语言的语法高亮,使代码更加清晰易读

多设备同步

随时随地访问您的代码片段库,支持桌面和移动设备

热门分类

浏览最受欢迎的代码分类