PHP 根据节日节气自动跳转相关图片

看到有很多小伙伴不知道根据节日节气自动跳转相关图片的代码如何写的,现在给大家写个例子,有需要的可以自取,根据自身需求修改。

示例代码如下:

<?php
// 获取当前时间的节气
function getSolarTerms(){
    $solarTerms = array(
        '小寒', '大寒', '立春', '雨水', '惊蛰', '春分', '清明', '谷雨', '立夏', '小满', '芒种', '夏至',
        '小暑', '大暑', '立秋', '处暑', '白露', '秋分', '寒露', '霜降', '立冬', '小雪', '大雪', '冬至'
    );
    $year = date('Y');
    $termStart = array(
        5,20,4,19,6,21,5,20,6,21,6,22,7,23,8,23,8,23,8,23,8,23,7,22
    );
    $time = time();
    $date = date('Y-m-d', $time);
    $i = 0;
    $term = '';
    foreach ($termStart as $start) {
        $termTime = strtotime($year.'-'.$i.'-'.$start);
        if ($time < $termTime) {
            $term = $solarTerms[$i - 1];
            break;
        }
        $i++;
    }
    return $term;
}

// 获取当前时间的节日
function getFestival(){
    $festival = array(
        '0101' => '元旦',
        '0214' => '情人节',
        '0308' => '妇女节',
        '0312' => '植树节',
        '0401' => '愚人节',
        '0501' => '劳动节',
        '0601' => '儿童节',
        '0701' => '建党节',
        '0801' => '建军节',
        '0910' => '教师节',
        '1001' => '国庆节',
        '1224' => '平安夜',
        '1225' => '圣诞节'
    );
    $time = time();
    $date = date('md', $time);
    $fes = isset($festival[$date]) ? $festival[$date] : '';
    return $fes;
}

// 根据节气和节日自动跳转相关图片地址
function redirectImage(){
    $solarTerms = getSolarTerms();
    $festival = getFestival();
    $url = '';
    if ($solarTerms == '春分' || $solarTerms == '清明' || $festival == '清明节') {
        $url = 'http://dc6i.cn/spring.png';
    } elseif ($solarTerms == '夏至' || $festival == '端午节') {
        $url = 'http://dc6i.cn/summer.png';
    } elseif ($solarTerms == '秋分' || $festival == '中秋节') {
        $url = 'http://dc6i.cn/autumn.png';
    } elseif ($solarTerms == '冬至' || $festival == '圣诞节') {
        $url = 'http://dc6i.cn/winter.png';
    }
    if ($url != '') {
        header('Location: '.$url);
        exit();
    }
}

redirectImage();
?>

 

这个代码中,我定义了三个函数:getSolarTerms()用于获取当前时间的节气,getFestival()用于获取当前时间的节日,redirectImage()用于根据节气和节日自动跳转相关图片地址。

在redirectImage()函数中,我们根据不同的节气和节日设置不同的图片地址,然后使用header()函数将页面跳转到相应的图片地址。如果没有符合条件的图片地址,则不进行跳转。

注意:在使用header()函数前,必须确保没有输出任何内容,否则会导致header()函数失效。

 

THE END