PHP 怎么PHP 时间戳验证

wen PHP项目 2

本文目录导读:

PHP 怎么PHP 时间戳验证

  1. 基本时间戳验证
  2. 检查时间戳格式
  3. 验证特定日期格式
  4. 综合验证函数
  5. 常见实用检查函数
  6. 使用场景示例

我来详细介绍 PHP 中时间戳验证的多种方法:

基本时间戳验证

验证是否为有效时间戳

// 方法1:使用 is_numeric() 和范围检查
function isValidTimestamp($timestamp) {
    if (!is_numeric($timestamp)) {
        return false;
    }
    // 检查是否在合理范围内(1970-01-01 到 2100-01-01)
    $minTimestamp = -2147483648;  // 或 0 根据需求
    $maxTimestamp = 4102444800;   // 2100年1月1日
    return $timestamp >= $minTimestamp && $timestamp <= $maxTimestamp;
}
// 使用示例
echo isValidTimestamp(1234567890) ? '有效' : '无效';  // 输出: 有效
echo isValidTimestamp('abc123') ? '有效' : '无效';    // 输出: 无效

使用 date() 函数验证

function validateTimestamp($timestamp) {
    // 使用 date() 函数尝试格式化,如果失败则无效
    if (date('Y-m-d H:i:s', $timestamp) !== false) {
        return true;
    }
    return false;
}
// 或者使用 DateTime 类
function validateTimestampWithDateTime($timestamp) {
    try {
        $dateTime = new DateTime('@' . $timestamp);
        return true;
    } catch (Exception $e) {
        return false;
    }
}

检查时间戳格式

10位(秒级)和13位(毫秒级)时间戳

function validateTimestampFormat($timestamp) {
    // 检查是否是10位或13位数字
    if (preg_match('/^(\d{10}|\d{13})$/', $timestamp)) {
        return 'valid_' . strlen($timestamp) . '位';
    }
    return 'invalid';
}
// 使用示例
echo validateTimestampFormat(1234567890);    // valid_10位
echo validateTimestampFormat(1234567890123); // valid_13位
echo validateTimestampFormat('abc1234567');  // invalid

验证特定日期格式

检查时间戳对应的具体日期

function validateDateFromTimestamp($timestamp, $expectedFormat = 'Y-m-d') {
    $date = date($expectedFormat, $timestamp);
    // 验证日期是否实际存在(避免2月30日这样的无效日期)
    $timestampCheck = strtotime($date);
    return $timestampCheck !== false;
}
// 检查日期是否在特定范围内
function validateTimestampInRange($timestamp, $start, $end) {
    return $timestamp >= $start && $timestamp <= $end;
}

综合验证函数

/**
 * 完整的时间戳验证函数
 * @param mixed $timestamp 要验证的时间戳
 * @param array $options 验证选项
 * @return array 返回验证结果
 */
function validateTimestampComplete($timestamp, $options = []) {
    $result = [
        'valid' => false,
        'message' => '',
        'timestamp' => null,
        'date' => null
    ];
    // 默认选项
    $defaults = [
        'allow_milliseconds' => false,
        'min_year' => 1970,
        'max_year' => 2100,
        'allow_negative' => false,
        'check_string_format' => true
    ];
    $options = array_merge($defaults, $options);
    // 1. 基本数字验证
    if (!is_numeric($timestamp)) {
        $result['message'] = '不是有效的数字';
        return $result;
    }
    // 2. 格式检查
    if ($options['check_string_format']) {
        $strTimestamp = (string)$timestamp;
        if ($options['allow_milliseconds']) {
            if (!preg_match('/^\d{10,13}$/', $strTimestamp)) {
                $result['message'] = '格式不正确';
                return $result;
            }
        } else {
            if (!preg_match('/^\d{10}$/', $strTimestamp)) {
                $result['message'] = '格式不正确(需要10位数字)';
                return $result;
            }
        }
    }
    // 3. 转换为整数
    $timestamp = (int)$timestamp;
    // 4. 处理毫秒时间戳
    if ($options['allow_milliseconds'] && strlen((string)$timestamp) === 13) {
        $timestamp = (int)($timestamp / 1000);
    }
    // 5. 负数检查
    if (!$options['allow_negative'] && $timestamp < 0) {
        $result['message'] = '不允许负时间戳';
        return $result;
    }
    // 6. 尝试创建 DateTime 对象
    try {
        $dateTime = new DateTime('@' . $timestamp);
        $year = (int)$dateTime->format('Y');
        // 7. 年份范围检查
        if ($year < $options['min_year'] || $year > $options['max_year']) {
            $result['message'] = "年份超出范围 ({$options['min_year']}-{$options['max_year']})";
            return $result;
        }
        // 验证成功
        $result['valid'] = true;
        $result['message'] = '有效的时间戳';
        $result['timestamp'] = $timestamp;
        $result['date'] = $dateTime->format('Y-m-d H:i:s');
    } catch (Exception $e) {
        $result['message'] = '无法转换为有效日期';
    }
    return $result;
}
// 使用示例
$validation = validateTimestampComplete(1234567890);
if ($validation['valid']) {
    echo "时间戳有效:{$validation['date']}";
} else {
    echo "验证失败:{$validation['message']}";
}

常见实用检查函数

/**
 * 检查时间戳是否来自今天
 */
function isToday($timestamp) {
    return date('Y-m-d', $timestamp) === date('Y-m-d');
}
/**
 * 检查时间戳是否过期
 */
function isExpired($timestamp, $expireTime = null) {
    $currentTime = $expireTime ?? time();
    return $timestamp < $currentTime;
}
/**
 * 验证会话时间戳
 */
function validateSessionTimestamp($sessionTimestamp, $timeout = 3600) {
    $currentTime = time();
    $diff = $currentTime - $sessionTimestamp;
    if ($diff > $timeout) {
        return false; // 会话过期
    }
    return true; // 会话有效
}

使用场景示例

// 验证用户注册时间
$userRegisterTimestamp = 1234567890;
$validation = validateTimestampComplete($userRegisterTimestamp, [
    'min_year' => 2020,
    'max_year' => 2025
]);
// 验证 API 请求时间戳
function validateApiTimestamp($apiTimestamp, $allowedDeviation = 300) {
    $currentTime = time();
    $diff = abs($currentTime - $apiTimestamp);
    return $diff <= $allowedDeviation;
}

这些方法可以帮助你根据具体需求进行时间戳验证,选择哪种方法取决于你的使用场景和验证要求。

抱歉,评论功能暂时关闭!